Connecting mq 2 to arduino. Gas sensors MQ series (Trema module v2.0). Program code for Arduino IDE

  1. Gas sensor MQ-2: http://ali.ski/6JRA_
  2. Arduino uno: http://ali.ski/gC_mOa
  3. Development board: http://ali.ski/rq8wz8
  4. Contact wires: http://ali.ski/Exjr3
  5. Diodes and resistors: http://fas.st/KK7DwjyF

In this tutorial we will connect a gas sensor to Arduino. With its help, we can monitor the amount of carbon dioxide in the room.

The sensor board itself consists of a 6-pin sensor itself, which for accurate readings must remain running for some time and heat up to the required temperature. Potentiometer for changing the sensitivity of the sensor. Well, 4 pins, 2 of which are +, - and two pins, one Analog, the other digital. Therefore, you need to connect either to the analog pin of the Arduino or to the digital pin.

For implementation this example we'll take the MQ-2 sensor. In general, there are a lot of MQ series sensors, there are carbon dioxide sensors, carbon monoxide sensors, and an alcohol vapor and air purity sensor. You can choose a sensor to suit your needs without any problems, but since we will carbon dioxide search, so you need an MQ-2 sensor.

We will connect the sensor to the Arduino analog pin A0. Accordingly, we will take an analog pin from the MQ-2 sensor, and not a digital one.

After connecting correctly according to the diagram, you need to copy the program code presented below and upload it to the Arduino.

Const int analogInPin = A0; // Specify the pin to which the sensor is connected const int ledPin = 13; int sensorValue = 0; // Declare a variable to store values ​​from the sensor // and set its initial value to 0 void setup() ( Serial.begin(9600); pinMode(ledPin, OUTPUT); // Set the mode for pin 13 Serial.println("MQ2 Test "); //Send text to the port monitor to monitor the execution of the program) void loop() ( sensorValue = analogRead(analogInPin); //read values ​​from the sensor if (sensorValue >= 350) //and if the specified threshold is exceeded ( digitalWrite(ledPin, HIGH); // then turn on the LED. ) else // and if not ( digitalWrite(ledPin, LOW); // then turn off ) Serial.print("MQ2 value= "); // To monitor data from the sensor, we translate it to the port monitor Serial.println(sensorValue); delay(1000); )

After loading the program code, you can breathe on the sensor, or release gas from the lighter - in the serial port monitor window you will see the corresponding values ​​received from the sensor.

You can watch more details in the video below.

Video:

Description

The gas sensor module, the main element of which is the MQ-2 gas analyzer, allows you to detect the presence of hydrocarbon gases (propane, methane, n-butane), smoke, and hydrogen in the ambient air. The sensor can be used in gas leak detection and smoke detection projects. The analogue-digital module allows you to both receive data on the content of gases to which the gas analyzer is susceptible, and work directly with devices, giving digital signal about exceeding/decrease of the threshold value. It has a sensitivity regulator, which allows you to adjust the sensor to the needs of a specific project. The module has two LEDs: the first (red) is a power indication, the second (green) is an indication of exceeding/decrease of the threshold value.

The main working element of the sensor is the heating element, due to which a chemical reaction occurs, as a result of which information about the gas concentration is obtained. During operation, the sensor should heat up - this is normal. It is also necessary to remember that due to the heating element, the sensor consumes a large current, so it is recommended to use external power.

Please note that sensor readings are affected by ambient temperature and humidity. Therefore, if the sensor is used in a changing environment, compensation for these parameters will be necessary.

Measuring ranges:

    0-1% - propane

    0.03-0.5% - butane

    0.05-2% - methane

    0.03-0.5% - hydrogen

Specifications

    Supply voltage: 4.8 - 5.2 V

    Current consumption: 170 mA

    Warm-up time when turned on: 1 min

Physical Dimensions

    Module (L x W x H): 35 x 20 x 21 mm

Pros of use

    The optimal low-cost solution for gas and smoke detection projects

    Easy-to-use module due to the presence of digital and analog outputs

Disadvantages of use

    Requires a long warm-up period (at least 24 hours) before use.

    Warming up is required to take readings (at least 1 minute)

    High power consumption (additional power is desirable)

Example of connection and use

The example demonstrates connecting a sensor and outputting the received data to the Serial port monitor. (The example was tested on the Smart UNO controller)

Connection diagram:

Sketch to download:

const int analogSignal = A0; //connect analog signal pin const int digitalSignal = 8 ; //connect digital signal pin boolean noGas; //variable for storing the value about the presence of gas int gasValue = 0 ; //variable for storing the amount of gas void setup() ( pinMode (digitalSignal, INPUT ) ; //set pin mode Serial.begin(9600); //initialize Serial port) void loop() ( noGas = digitalRead(digitalSignal); //read the value about the presence of gas gasValue = analogRead(analogSignal); // and about its quantity //output message Serial.print("There is"); if (noGas) Serial .print ("no gas" ) ; else Serial .print ( "gas" ) ; Serial.print(", the gas value is "); Serial.println(gasValue); delay(1000); //delay 1 s ) mq2Heater.ino #include // name for the pin to which the sensor is connected#define PIN_MQ2 A0 // name for the pin to which the sensor heater is connected#define PIN_MQ2_HEATER 13 // create an object to work with the sensor // and pass it the number of the output signal pin and the heater MQ2 mq2(PIN_MQ2, PIN_MQ2_HEATER) ; void setup() ( Serial.begin ( 9600 ) ; // turn on the heater mq2.heaterPwrHigh(); Serial.println("Heated sensor"); ) void loop() ( // and calibration was not completed if (! mq2.isCalibrated () && mq2.heatingCompleted () ) ( mq2.calibrate () ; Serial.print ("Ro = " ) ; Serial.println (mq2.getRo () ) ; ) // if the sensor heating interval has passed // and calibration was completed if (mq2.isCalibrated () && mq2.heatingCompleted () ) ( Serial.print ("LPG: " ) ; Serial.print (mq2.readLPG () ) ; Serial.print ( " ppm " ) ; Serial.print ( " Methane: " ) ; Serial.print (mq2.readMethane () ) ; Serial.print ( " ppm " ) ; Serial.print ( " Smoke: " ) ; Serial.print (mq2.readSmoke () ) ; Serial.print ( "ppm" ; Serial.print ("Hydrogen: " ) ; Serial.print (mq2.readHydrogen () ) ; Serial.println ( " ppm " ) ; delay(100 ) ; ) )

A sensor can be connected to Arduino boards with 5 V logic using just one. To do this, install a jumper on the “heater power supply selection” connector.

Let's output the current value of harmful gases in ppm to the Serial port, while the heater is always on.

mq2.ino // library for working with MQ sensors (Troyka module)#include //name for the pin to which the sensor is connected#define PIN_MQ2 A0 // create an object to work with the sensor and pass it the pin number MQ2 mq2(PIN_MQ2) ; void setup() ( // open serial port Serial.begin(9600); // before calibrating the sensor, warm it up for 60 seconds // calibrate the sensor to clean air mq2.calibrate(); // output the resistance of the sensor in clean air (Ro) to the serial port Serial.print("Ro = "); Serial.println(mq2.getRo()); ) void loop() ( // display the ratio of the current sensor resistance // to the sensor resistance in clean air (Rs/Ro) Serial.print ("Ratio: " ) ; Serial.print(mq2.readRatio()); // display gas values ​​in ppm Serial.print("LPG: "); Serial.print(mq2.readLPG()); Serial.print("ppm"); Serial.print("Methane:"); Serial.print(mq2.readMethane()); Serial.print("ppm"); Serial.print("Smoke:"); Serial.print(mq2.readSmoke()); Serial.print("ppm"); Serial.print("Hydrogen:"); Serial.print(mq2.readHydrogen()); Serial.println("ppm"); delay(100); )

The MQ-2 gas sensor allows you to record the concentration of gases such as hydrogen, smoke and flammable hydrocarbon gases (methane, propane, butane). The sensor belongs to the widespread MQ sensor family. This family of sensors has gained popularity due to its low cost and ease of use. The sensor has an analog and digital output. A signal is sent to the digital output when a certain gas concentration threshold is exceeded, which is adjusted by a trimming resistor. The sensor is easy to connect, has high sensitivity and short response time.

The sensor is a small board, on the front side of which there is a sensitive gas analyzer (detector), and on back side there are 4 legs for connecting the sensor, power and output signal indicators, as well as a potentiometer.

MQ-2 sensors are used in smart home systems, in gas or smoke detection systems at industrial or private facilities, in automobile ventilation filters, etc.

Characteristics

  • Supply voltage: 5V;
  • Current consumption (heater current): 180mA;
  • Sensitivity range 300-10000 ppm;
  • Gas for which the sensor is rated: isobutane, 1000ppm;
  • Response time: less than 10s;
  • Operating temperature: -10 to +50 °C;
  • Operating air humidity: no more than 95% RH;
  • Interface: analog and digital;

Principle of operation

The operating principle of the sensor is based on a sensitive detector made of a mixture of aluminum and tin oxides, in which a chemical reaction occurs due to heating. This is why the gas analyzer heats up significantly during operation, so don’t be alarmed. As a result chemical reaction The resistance of the element changes and a signal is transmitted. Depending on the sensitivity of the element to certain gases, the effect of their detection is achieved.

Gas concentration is measured in ppm. It stands for parts per million. Thus 1ppm corresponds to a concentration of 0.0001%. To obtain the exact value of the measured gas concentration ppm, it is necessary to perform a complex nonlinear voltage conversion at the analog output of the sensor according to the conversion tables from the documentation for the sensor, taking into account the ambient temperature.

Using a potentiometer, you can change the sensitivity threshold of the digital output of the sensor. Keep in mind that the sensitivity threshold will not be the same for different gases.

Indicators located on the sensor notify us that the power is connected and the digital output sensitivity threshold has been exceeded.

Connection

You can connect the sensor to Arduino board or directly to the relay module. In the first case, the analog output A0 of the sensor is used, which is connected to the analog input on the Arduino board. In the case of a relay, the digital output of the sensor is used.


Attention. Do not supply the sensor with a supply voltage of more than 5V, avoid moisture and alkali getting into the gas analyzer, and avoid frostbite of the sensor at very low temperatures.

The connection diagram is shown in the picture below:


Program code for Arduino IDE

An example of the source code for checking the functionality of the sensor for Arduino is presented below. The code displays the current value of the analog input ADC and information about exceeding the threshold value to the port monitor. In the #define smokePin A0 line of code you can specify the number of the Arduino pin to which the analog output of the sensor is connected. You can set the threshold value for gas concentration in the air yourself.

#define smokePin A0 // define the analog output to which the sensor is connected
int sensorThres = 400; // threshold value of the ADC at which we assume that there is gas

Void setup() (
Serial.begin(9600); // Set the port speed to 9600 baud
}

Void loop() (
int analogSensor = analogRead(smokePin); // read ADC values ​​from analog input
// to which the sensor is connected
Serial.print(analogSensor); // output the value of the ADC signal from the sensor to the port

// Check if the threshold has been reached
if (analogSensor > sensorThres) ( // if the value is greater than acceptable...
Serial.println("Gaz!"); // output to the port an inscription that there is gas
}
else ( // otherwise...
Serial.println("normal"); // output to the port an inscription that there is no gas
}
delay(500); // delay of 500 milliseconds.

While walking through the catalogs of Chinese sellers on E-bay, I accidentally came across an MQ-4 gas sensor. This sensor is designed to determine the concentration of methane (CH4) in the air. And since this gas is the main component of household gas, having such a sensor is very useful - you can assemble a gas leak detector or something similar. In general, it’s an interesting thing, I’m especially pleased with the price of $4.5 and the analog communication interface - there will be no problems with connection.

To connect the sensor under its belly there are 6 pins, 4 of which duplicate each other. Therefore, only 4 pins are used for connection:

N-N These are the heater leads. A voltage of 5 volts is supplied to it, and it does not matter whether it is constant or alternating.

A-A And B-B these are electrodes. The signal can be taken from any of them. For example, in the diagram below, power is applied to A-A, and the signal is taken from electrode B-B. But you can also do the opposite - feed to B-B, and remove the signal from A-A. It will work in both cases. In this way, the sensor is somewhat similar to a vacuum tube

Resistor RL adjusts the sensitivity of the sensor. It is recommended to bet in the 10k range. The sensitivity of the sensor, according to the documentation, ranges from 200 to 10,000 ppm (what is this?)

The datasheet on the MQ-4 shows a graph that shows that in addition to methane, the sensor responds very well to propane (LPG), and to a lesser extent to hydrogen gas, carbon monoxide and alcohol vapor


In general in the family MQ-x sensors There are sensors specifically designed to detect these gases. Here are some of them:

MQ-3 - alcohol vapor sensor

MQ-5 and MQ-6 - designed for propane detection/ butane

MQ-7 - sensitive to carbon monoxide (IMHO, deserves special attention)

MQ-8 - specializes in hydrogen H2

Etc. The list can be supplemented with a couple more sensors, all of them are easy to Google.

To connect my sensor, I assembled a simple circuit with LEDs. Four LEDs, each will light up when reachinga certain thresholdgas concentration. The result will be something like a gas pollution scale, albeit dimensionless.


The sensor is connected to ADC0 (PortC.0). The internal 2.54 volt reference voltage is used as the ADC reference voltage. Therefore, a voltage divider is assembled on resistors R5-R6 so that no more than 2.5 volts reaches the ADC input. Resistor R7 is an additional pull-up to ground according to the diagram from the datasheet, I took it 3.3 kilo-ohms - whatever was at hand.

I sketched out a small program for ATmega8, clock frequency 1 MHz

$regfile = "m8def.dat"
$crystal = 1000000
$baud = 1200

"ADC configuration
Config adc = Single, Prescaler = Auto , Reference = Internal

"connecting LEDs
Config Portb. 1 = Output
Config Portb. 2 = Output
Config Portb. 3 = Output
Config Portb. 4 = Output

Dim W AsInteger"to store the value received from the ADC

Do

"starting and reading readings from the sensor
Start Adc
W= Getadc(0 ) "sensor is connected to PortC.0

"depending on the value of the readings, we will light the indication LEDs
If W< 700 Then
Portb = &B00000000 "the value is less than the response threshold, everything is buzzing
End If

If W>700 And W< 750 Then"low level of gas pollution
Portb = &B00000010
End If

If W>750 And W< 800 Then"average level
Portb = &B00000110
End If

If W>850 And W< 900 Then"a little less than completely gassed
Portb = &B00001110
End If

If W>900 Then"guard!
Portb = &B00011110
End If

Print W "send readings to UART

Wait 1

Loop

End

The readings from the sensor will be read at a frequency of 1 time per second. And depending on the readings, a certain number of LEDs will light up or not light up at all. I took the threshold values ​​after a trial test and displaying the readings in the UART.

Test circuit assembled on a breadboard


Soldered sensor


For testing, I took a regular gas lighter; it uses propane as fuel, which is also well captured by the sensor.


After power is applied, the sensor needs time to enter operating mode, approximately 10-15 seconds. This time is needed for the heater inside the sensor to raise the temperature to the required value. By the way, the sensor itself also heats up quite a bit during operation, it feels like up to 50 degrees. So don't panic, this is the norm :)



What else to read