반응형

안녕하세요. 약 두 달만에 글을 씁니다.

 

공모전과 기사 시험의 지옥을 뒤로 잠시 여유가 생겨 시간을 냅니다.

 

오늘은 MQ 시리즈에서 공기질 센서를 PPM으로 변환하는 방법에 대해 글을 쓰겠습니다.

 

MQ 시리즈 센서를 사용할 때 PPM 변환이 설명이 친절하지 않아 작은 힘을 보태겠습니다.

 

프로젝트에 필요한 공기질 센서를 엑셀로 정리하다 보니 이렇게 블로그 글 쓰는데 도움이 되네요.

 

MQ 시리즈마다 측정할 수 있는 센서값이 굉장히 많습니다. 

 

Gas_Sensor.xlsx
0.01MB

 

MQ 시리즈 중 하나를 사용할 수 있다면, 다른 시리즈 또한 쉽게 사용할 수 있습니다. 

 

MQ 시리즈

글을 세 편정도로 나누어서 글을 쓸 예정인데, 

 

1편은 센서의 원리가 궁금한 것이 아닌, 아두이노로 PPM 변환 결과만 필요하신 분을 위한 글입니다.

2편은 데이터시트를 보면서 회로를 보고, 원리를 확인합니다.

3편은 C파일의 코드를 뜯어보면서 파이썬으로 PPM으로 변환하는 코드를 작성하겠습니다.

 

 

github.com/miguel5612/MQSensorsLib

 

miguel5612/MQSensorsLib

We present a unified library for MQ sensors, this library allows to read MQ signals easily from Arduino, Genuino, ESP8266, ESP-32 boards whose references are MQ2, MQ3, MQ4, MQ5, MQ6, MQ7, MQ8, MQ9,...

github.com

 

GitHub MQ 시리즈 주소 입니다.

 

MQSensorsLib-master.zip
0.50MB

 

다운받아서 압축을 풀고 아두이노 라이브러리에 추가해주면 됩니다. 

 

 

원리가 다 같기 때문에 MQ-2 예제를 보면서 코드 사용법을 설명하겠습니다.

 

 

모든 코드를 보지 않고, 아두이노로 바로 사용할 수 있게 중요한 코드만 설명하겠습니다.

 

 

 

 

 

1. Calibration - 칼리브레이션

 

다른 센서와 다르게 드론과 같은 칼리브레이션 단계가 있습니다. 

 

MQ 시리즈에서 말하는 칼리브레이션은 처음 센서의 값을 영점을 조절하기 때문에 이런 표현을 쓰는 것 같습니다. 

 

쉽게 말해서 센서를 처음 측정할 때, 공기가 깨끗한 곳을 기준으로 공기질을 상대적으로 측정합니다.

 

칼리브레이션

 

센서로 바로 측정하는 것이 아니라 10번 정도 깨끗한 공기를 측정하고, 평균을 내어 R0을 영점을 맞춥니다.

 

여기서 RatioMQ2CleanAir는 센서마다 정의한 값이 서로 다르기 때문에 예제가 정의한 값을 사용합니다.

 

Clean Air

MQ2는 9.83ppm을 깨끗한 공기라고 가정을 하고 시작합니다. 이는 개발자들이 여러 시행착오를 거쳐 최적의 값을 낸 것 이기 때문에 그대로 사용하시면 됩니다.

 

 

 

 

 

 

2. PPM 출력

 

 

칼리브레이션이 끝나면, 아두이노에서 MQ Lib에서 알아서 저항 값이 PPM값으로 변환되어 나옵니다. 

 

바로 예제를 돌려보시면 아시겠지만, PPM값 뿐만 아니라, 센서에 사용된 전압, 저항 등이 모두 출력 됩니다.

 

 

 

3. a, b 선언

 

그리고 중요한 것이 어떤 공기를 측정할 것인지 상수를 선언하는 부분입니다. 

 

최대한 쉽게 설명하기 위해 데이터 시트는 보고 싶지 않지만, Figure는 하나 보고 가시는걸 추천드립니다.

 

MQ 시리즈 센서는 상수 값에 따라, 지수 회귀식 기울기 정도가 크게 바뀌기 때문에 a, b를 제대로 선언해주지 않으면, 이상한 PPM 값이 나오며 값의 차이가 굉장히 커집니다.

 

ppm = a * ratio ^ b

ratio = rs / ro

 

ro = 칼리브레이션된 저항값 (고정값)

rs = 공기질이 측정되는 저항값 (가변값)

 

만약 H2의 PPM을 원하면 아래처럼  a, b 값을 바꾸면 됩니다.

 

MQ2.setA(987.99); 

MQ2.setB(-2.162);

 

참고로 Figure에 보이는 RL은 MQ 센서에 붙어 있는 가변 저항입니다. 센서의 예민 정도를 조정할 수 있습니다. 

 

/*
  MQUnifiedsensor Library - reading an MQ2

  Demonstrates the use a MQ2 sensor.
  Library originally added 01 may 2019
  by Miguel A Califa, Yersson Carrillo, Ghiordy Contreras, Mario Rodriguez
 
  Added example
  modified 23 May 2019
  by Miguel Califa 

  Updated library usage
  modified 26 March 2020
  by Miguel Califa 
  Wiring:
  https://github.com/miguel5612/MQSensorsLib_Docs/blob/master/static/img/MQ_Arduino.PNG
  Please take care, arduino A0 pin represent the analog input configured on #define pin

 This example code is in the public domain.

*/

//Include the library
#include <MQUnifiedsensor.h>
/************************Hardware Related Macros************************************/
#define         Board                   ("Arduino UNO")
#define         Pin                     (A2)  //Analog input 3 of your arduino
/***********************Software Related Macros************************************/
#define         Type                    ("MQ-2") //MQ2
#define         Voltage_Resolution      (5)
#define         ADC_Bit_Resolution      (10) // For arduino UNO/MEGA/NANO
#define         RatioMQ2CleanAir        (9.83) //RS / R0 = 9.83 ppm 

/*****************************Globals***********************************************/
MQUnifiedsensor MQ2(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);
/*****************************Globals***********************************************/

void setup() {
  //Init the serial port communication - to debug the library
  Serial.begin(9600); //Init serial port

  //Set math model to calculate the PPM concentration and the value of constants
  MQ2.setRegressionMethod(1); //_PPM =  a*ratio^b
  MQ2.setA(574.25); MQ2.setB(-2.222); // Configurate the ecuation values to get LPG concentration
  /*
    Exponential regression:
    Gas    | a      | b
    H2     | 987.99 | -2.162
    LPG    | 574.25 | -2.222
    CO     | 36974  | -3.109
    Alcohol| 3616.1 | -2.675
    Propane| 658.71 | -2.168
  */

  /*****************************  MQ Init ********************************************/ 
  //Remarks: Configure the pin of arduino as input.
  /************************************************************************************/ 
  MQ2.init(); 
  /* 
    //If the RL value is different from 10K please assign your RL value with the following method:
    MQ2.setRL(10);
  */
  /*****************************  MQ CAlibration ********************************************/ 
  // Explanation: 
  // In this routine the sensor will measure the resistance of the sensor supposing before was pre-heated
  // and now is on clean air (Calibration conditions), and it will setup R0 value.
  // We recomend execute this routine only on setup or on the laboratory and save on the eeprom of your arduino
  // This routine not need to execute to every restart, you can load your R0 if you know the value
  // Acknowledgements: https://jayconsystems.com/blog/understanding-a-gas-sensor
  Serial.print("Calibrating please wait.");
  float calcR0 = 0;
  for(int i = 1; i<=10; i ++)
  {
    MQ2.update(); // Update data, the arduino will be read the voltage on the analog pin
    calcR0 += MQ2.calibrate(RatioMQ2CleanAir);
    Serial.print(".");
  }
  MQ2.setR0(calcR0/10);
  Serial.println("  done!.");
  
  if(isinf(calcR0)) {Serial.println("Warning: Conection issue founded, R0 is infite (Open circuit detected) please check your wiring and supply"); while(1);}
  if(calcR0 == 0){Serial.println("Warning: Conection issue founded, R0 is zero (Analog pin with short circuit to ground) please check your wiring and supply"); while(1);}
  /*****************************  MQ CAlibration ********************************************/ 

  MQ2.serialDebug(true);
}

void loop() {
  MQ2.update(); // Update data, the arduino will be read the voltage on the analog pin
  MQ2.readSensor(); // Sensor will read PPM concentration using the model and a and b values setted before or in the setup
  MQ2.serialDebug(); // Will print the table on the serial port
  delay(500); //Sampling frequency
}

 

코드를 보면 복잡해보이지만, 주석을 걷어내고 필요한 부분만 본다면 굉장히 짧은 코드임을 알 수 있습니다. 

 

MQ2를 예제를 확인했지만, 다른 MQ 시리즈 또한 이런 방식이기 때문에 쉽게 따라하실 수 있습니다.

 

 

다음 글은 데이터 시트를 보면서 회로를 보겠습니다.

 

coding-yoon.tistory.com/121

 

[아두이노] MQ 시리즈 공기질 센서 PPM으로 변환하기! (2) 회로도 (Schematic)

안녕하세요. MQ시리즈 두 번째 글을 작성합니다. 확실히 글은 바로 바로 작성하는 것이 중요한 것 같습니다. 글을 쓰려고 보니 기억이 안 나서 다시 새로 공부했습니다. 저번 글은 아두이노 라이

coding-yoon.tistory.com

 

728x90
반응형

+ Recent posts