Sensors are necessary to detect the components of the air. These are used e.g. in smoke detectors. However, instructions for using these gas sensors at the Raspberry Pi are rare, which is why in this tutorial the general use of such MQ modules at the Raspberry Pi is shown. Thus, e.g. smoke detectors or air quality testers can be built.
How to configure any MQ sensor and read it out with the Pi will be shown on the example of the Raspberry Pi gas sensor MQ2 in this tutorial. All other sensors (MQ3, MQ-135, etc.) can also be adapted with a few additional steps.
Accessories
All MQ-X sensors return analogue signals, which we can not easily read at the Raspberry Pi. One possibility would be to use an Arduino, but we can also use an analog-to-digital converter (ADC), which can be read out via the I2C bus. In addition, we also need a logic level converter.
- Analog-Digital Converter (8 Ports): US / UK
- 5V to 3.3V Logic Level Converter: US / UK
- Breadboard: US / UK
- Jumper wire: US / UK
These components are independent of the selected gas sensor. There are also many different sensors for the Raspberry Pi, which are already available for a few bucks and are suitable for different gases:
- MQ-2 (Methane, Butane, LPG, smoke): US / UK
- MQ-3 (Alcohol, Ethanol, smoke): US / UK
- MQ-4 (Methane, CNG Gas): US / UK
- MQ-5 (Natural gas, LPG): US / UK
- MQ-6 (LPG, butane gas): US / UK
- MQ-7 (Carbon Monoxide): US / UK
- MQ-8 (Hydrogen Gas): US / UK
- MQ-9 (Carbon Monoxide, flammable gasses): US / UK
- MQ-131 (Ozone): US / UK
- MQ-135 (Benzene, Alcohol, smoke): US / UK
- MQ-136 (Hydrogen Sulfide gas): US / UK
- MQ-137 (Ammonia): US / UK
- MQ-138 (Benzene, Toluene, Alcohol, Acetone, Propane, Formaldehyde gas): US / UK
- MQ-214 (Methane, Natural gas): US / UK
- MQ-216 (Natural gas, Coal gas): US / UK
- MQ-303A (Alcohol, Ethanol, smoke): US / UK
- MQ-306A (LPG, butane gas): US / UK
- MQ-307A (Carbon Monoxide): US / UK
- MQ-309A (Carbon Monoxide, flammable gasses): US / UK
- MG811 (Carbon Dioxide (CO2)): US / UK
- AQ-104 (air quality): US / UK
- AQ-2 (Flamable gasses, smoke): US / UK
- AQ-3 (Alcohol, Benzine): US / UK
- AQ-7 (Carbon Monoxide): US / UK
You can find the full list with additional information here.
I recommend to use a sensor with a soldered PCB, because no further cabling and the use of resistors and capacitors is necessary.
Details on the individual Raspberry Pi gas sensors can also be found in the corresponding data sheets. Simply google the name of the sensor including “datasheet”. There is also the voltage at which the sensor operates mentioned.
If someone wants to build an alcohol tester or something similar, you should also be aware that these modules are not absolutely accurate and can not compete with a professional measurement.
Connection between MQ-2 and Raspberry Pi
In this example, we use a 5V voltage as output. This is too much for the GPIOs, which is why we use a logic level converter (TTL) that cuts down the voltage. If you use a sensor other than the MQ-2 and it has a different voltage, the setup must of course be adjusted.
After the MCP3008 is correctly connected, we use port 0 and connect it to RX0 of the TTL. On the opposite side is RX1, which is connected to the analog pin (A0) of the MQ2 sensor. Also connect 3.3V from the Raspberry Pi (LV) and 5V (HV) to the TTL. And also 5V to the VCC pin of the gas sensor and GND from the Raspberry Pi comes to GND on the LV and HV side of the TTL, as well as to GND of the MQ2.
Schematically the whole looks as follows:
I use the 5V of the Raspberry Pi’s. However, an external power supply is recommended if other sensors and modules or input devices (keyboard, mouse, touchscreen) are used. For this, the sensor is simply supplied with current from the external source (HV side of the TTL) and the ground connection (Minus / GND) is connected to GND of the Raspberry Pi.
Configuration of the Raspberry Pi Gas Sensor – Preparation
The concentration of a gas is given in PPM (parts per million). One difficulty of the MQ-2 is that a single analog value is given with which the gas content in the air has to be calculated for the various supported gases. However, the sensor must be configured for this purpose. Since this manual is also applicable to another Raspberry Pi gas sensor, the procedure is as follows:
First, we have to see the data sheet of the respective module, which contains a diagram:
However, the scaling of the values is not linear but logarithmic to the base 10 (log). so, the first stroke on the X axis is 200, then 300, etc. The first stroke after 1000 is 2000, etc. The distance between is linear. The idea behind this script for calibration and reading is to create a straight line and calculate the amount of gas (in ppm). To do this, we need two points to calculate the slope.
Let us take the example of LPG. We therefore take the point P1 (x = 200, y = ~ 1.62) and P2 (x = 10000, y = ~ 0.26). To calculate the “real” values, we apply the ten logarithm. Using the two-point form, we can calculate the slope, which in our case is -0.47 (link to the calculation). With the slope and the calculated logarithm from the left point (x = 2.3, y = 0.21), we can now determine the straight line.
For the remaining gases the calculation is equivalent and can be carried out in the same way. Anyone who wants to have more reading material can do this here.
Calibration of the Raspberry Pi Gas Sensor – Code
Enough of the theory – we want to use the sensor now. For this purpose you can use the code I have customized, which is located in a GitHub repository. Also included is a class for reading the MCP3008. First we clone the directory:
git clone https://github.com/tutRPi/Raspberry-Pi-Gas-Sensor-MQ
Then we change to the directory and run the existing Python test file.
cd Raspberry-Pi-Gas-Sensor-MQ sudo python example.py
The calibration is started automatically during initialization. It is important that the sensor is in good / fresh air as smoke / other gases would falsify the calibration. The process takes a few seconds, but the gas content can already be measured thereafter (see video). Some sensors are quite hot, but this should not be a cause for concern.
Some users reported that the values become accurate only after some time. I can not verify this, because I do not have a professional measuring device. If someone can confirm or verify, since he has such a device at home, I would be pleased about feedback as a comment 🙂
204 Comments
I have thanks in raspberry programming for Gas sensor MQ 7 can i ask for help sir ?? Especially in entering calculations for CO gas
If you want to use another sensor, you have to adjust the formula, depending on the sensor’s datasheet (cf. my example).
hi, i’ve been fixed it for MQ138. but how about TGS2620 with just one curve for the main gas?
Hi can you teach me how you do the mq7 gas sensor?
hi can you teach me how to setup MQ 9 gas sensor in rasberrypi 3 b+
Hello !
Thank you for your work ! Also I have a question.
Does the calibration have to be for 48 hours, does the sensor has to be pluged for 48 hours ? And how do you know the value of the load resistance ?
Hi,
usually the calibration needs about 10 seconds (enough precision for my applications). The value was given (you can change it, depending on your sensor).
Thank you for your response 🙂 !
I am using a MQ-7 sensor, do you happen to know what is the load resistance of it ? Or do you put it manualy in series with the sensor ? (in witch case it could be what you want)
Hi Felix, I am a student in University of Ibadan, Nigeria, working on an air quality project, please I need a Nitrogen oxide and Sulphur dioxide gas sensor that is compatible with the raspberry pi. Any suggestions on where to acquire these?
For my mq135 its giving Ro as 0 in the terminal
Hi, I also have a MQ135 sensor, I am having problems with programming it, can you help me? My email is: caroch1179@gmail.com
Please help me with sensor MQ135 & MQ7. I need for my project work. Any type of help is appreciated. 🙂
email id : shivamdurgbuns@gmail.com
Can I also get for mq 135?
Please help me with sensor MQ135. I need for my project work. Any type of help is appreciated. thank you
My email is linghojin1996@gmail.com
Hi I’m using the same setup as yours and din’t change code also. But in the terminal i’m getting something like
“Press CTRL+C to abort.
Calibrating…
Calibration is done…
Ro=0.000000 kohm
Abort by user”
Please let me know what to do.
I keep getting this
pi@octopi:~/Raspberry-Pi-Gas-Sensor-MQ $ sudo python example.py
Traceback (most recent call last):
File “example.py”, line 1, in
from mq import *
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 6, in
from MCP3008 import MCP3008
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/MCP3008.py”, line 1, in
from spidev import SpiDev
ImportError: No module named spidev
You have to install spidev…
Hi Can You Help Me Put Condition For Example Smoke Is Greater Than 1? then my buzzer will turn on..Its A Big Help For Me to Finish My Project..Godbless
i am not using mcp. i have directly connected the sensor to board without any converter.what kind of changes I have to do in code?
It is not possible. You will need an ADC, as the Raspberry Pi cannot read analogue inputs.
i need help i am not using mcp. i have directly connected the sensor to board without any converter.what kind of changes I have to do in code?
If more than 3.3V are connected to the GPIOs, you can break them.
Hello, im using mcp3002 instead mcp3008. What change should I made?
always show “Abort by user”, i’ll tried wiring like this tutorial and use code same on this. anyone can help?
Log the exception.
Please say code sir
how to log the exception?
Hi, I am using an ADS1115 analog to digital converter instead of MCP and MQ-2 sensor
My code is based on https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code
my return result is only one value for ex. 0.095875. Can you help me get those 4 values like yourself in the video (Ro, LPG, CO, smoke)?
Regards
i am using mcp3008 with mq2. but i am facing difficulty in wiring as my mcp has only 5 pins. So I am confuse what to do now.
Probably it is no MCP3008
With only 5 pins I don’t think it could be a mcp3008. Google ‘mcp3008 datasheet’, and you’ll see that they all have the same layout. There’s a 3004 but even that has more pins than 5.
Sorry as I’m new, but I’m unsure of how this could work. Any documentation I can find on a logic level coverter says that they canot be used for analog conversions. They are only on/off. You’d have to take the output from the sensor and divide it using 2 resistors.
That’s why we use the MCP3008 Analog Digital Converter.
I want to put an active buzzer in the project once the gas quality detected by the sensor get too high. In what part should I put the code for the buzzer?
have you a better diagram? mine aborts straight after running it.
Im not sure if i wired the vcc right, were you two red wires merge into one, I placed my sensor in the board and have the two wires in the same row as the vcc connection of the sensor
got it working, had the mcp3008 backwards
Hii frds iam anand….iam using mq135 sensor….i read the value from the sensor by raspberry but I want to sent the data to cloud…and I want sent msg to the particular person…so guys help me
My mail
Krishnan10497kmb@gmail.com
el conversor de nivel logico lo conectan a la salida de dato analogo o digital?
Hello Everyone.. Can you help us with our Capstone we are using a MQ-6 instead of MQ-2 is it posible that it had a the same output later? Thanks in advance
Should be the same, but you have to adjust the formula!
Press CTRL+C to abort.
Calibrating…
abort by user
and im using mq6 sensor
i got an error from this line of code can you please help me?
def MQResistanceCalculation(self, raw_adc):
return float(self.RL_VALUE*(1023.0-raw_adc))/float(raw_adc);
plz suggest the code ,where we have to update
I’m using MQ135 please what do I adjust in the formulae. Also without the Logic Level Connverter could it work?
Do you have codes please programming my mq 5 gas sensor to python using raspberry pi? Need much help about it.
You can create it by using the datasheet. I have shown the way how the calculation works 🙂
Hi, I’m using an MQ135 and the only output I am seeing at the moment is:
Press CTRL+C to abort.
Abort by user
Is anyone experiencing something similar?
Thanks
There is probably some exception thrown. You could log it to find out more.
how can i log out
have u solve ur problem?
I am also experiencing the same issue. Have you got any solutions??
im using mq-2
output i get
Press CTRL+C to abort.
Calibrating…
Abort by user
may i connect 5v or 3.3v of pi with sensor mq2 and
im using mq-2
output i get
Press CTRL+C to abort.
Calibrating…
Abort by user
Just log the exception.
how?
print()
I have everything setup like in the tutorial, I’ve enabled exception logging in python:
Press CTRL+C to abort.
Calibrating…
ERROR:root:message
Traceback (most recent call last):
File “example.py”, line 7, in
mq = MQ();
File “/root/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 48, in __init__
self.Ro = self.MQCalibration(self.MQ_PIN)
File “/root/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 83, in MQCalibration
val += self.MQResistanceCalculation(self.adc.read(mq_pin))
File “/root/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 69, in MQResistanceCalculation
return float(self.RL_VALUE*(1023.0-raw_adc)/float(raw_adc));
ZeroDivisionError: float division by zero
Any ideas?
Your ADC gives values of zero back, so probably there is something wront (check connections and read the value per hand)
I checked it but my mcp3008 giving some value but still facing same issue plz
Hi, i was getting error while running this code, so i commented the try and except,and started from while True:
after executing i got this error
Press CTRL+C to abort.
Calibrating…
Traceback (most recent call last):
File “example.py”, line 7, in
mq = MQ();
File “/home/pi/Desktop/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 48, in __init__
self.Ro = self.MQCalibration(self.MQ_PIN)
File “/home/pi/Desktop/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 83, in MQCalibration
val += self.MQResistanceCalculation(self.adc.read(mq_pin))
File “/home/pi/Desktop/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 69, in MQResistanceCalculation
return float(self.RL_VALUE*(1023.0-raw_adc)/float(raw_adc));
ZeroDivisionError: float division by zero
Your ADC gives values of zero back, so probably there is something wront (check connections and read the value per hand)
with mcp3008 library my ADC is giving output
You can replace it by the other library.
but with the code provided here, it is giving errors
Sunny have you fixed it?
I am getting the same error. I checked ADS1115 output and it is giving values for all 4 channels. Sample output mentioned here. But when running MQ2 example.py, it is giving same error. Please suggest how to check the signal coming from MQ2 sensor to ADS1115 is Ok.
| 0 | 1 | 2 | 3 |
————————————-
| 11516 | 4608 | 4793 | 4954 |
| 11507 | 4832 | 4444 | 4941 |
| 11502 | 4831 | 4450 | 4937 |
| 11480 | 4773 | 4615 | 4641 |
| 11529 | 4522 | 4827 | 4467 |
| 11487 | 4485 | 4859 | 4375 |
| 11515 | 4483 | 4863 | 4374 |
| 11487 | 4491 | 4829 | 4481 |
| 11499 | 4645 | 4744 | 4550 |
| 11474 | 4751 | 4497 | 4926 |
| 11461 | 4839 | 4443 | 4932 |
| 11471 | 4844 | 4435 | 4961 |
| 11497 | 4837 | 4440 | 4957 |
| 11472 | 4819 | 4501 | 4789 |
| 11497 | 4669 | 4628 | 4751 |
Hey, i ran the code and got
Press CTRL+C to abort.
Abort by user
then i tried to log the exception to figure out why it is not calibrating and than i got this error, pls help
Press CTRL+C to abort.
Abort by user
ERROR:root:message
Traceback (most recent call last):
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/example.py”, line 8, in
mq = MQ();
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 32, in __init__
self.adc = MCP3008()
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/MCP3008.py”, line 7, in __init__
self.open()
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/MCP3008.py”, line 10, in open
self.spi.open(self.bus, self.device)
FileNotFoundError: [Errno 2] No such file or directory
I also have the same problem please assist.
Hie you need to enable the SPI interface. You can just google on how to do that
HI Felix thanks for your help and support. I.m having this errrr can you please help me..
pi@raspberrypi:~/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ $ sudo python example.pyPress CTRL+C to abort.
Traceback (most recent call last):
File “example.py”, line 14, in
mq = MQ();
File “/home/pi/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 32, in __init__
self.adc = MCP3008()
File “/home/pi/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ/MCP3008.py”, line 7, in __init__
self.open()
File “/home/pi/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ/MCP3008.py”, line 10, in open
self.spi.open(self.bus, self.device)
IOError: [Errno 2] No such file or directory
Thanks in advance..
You have not enabled SPI or not installed SpiDev.
see this repo https://github.com/shubham0490/MQ-sensor-ppm-conversion
Hi, i was also getting the same errors but i have found the solution for this, check this link
https://github.com/shubham0490/MQ-sensor-ppm-conversion
There is problem with the library, install the adafruit library and the code which is in link will work fine
thanks to both, I had several problems like not enabling the SPI but it still does not work, I’m trying now the other URL, thank you very much.
New error
Press CTRL+C to abort.
Calibrating…
Traceback (most recent call last):
File “/home/pi/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ/examplewithdebug.py”, line 14, in
mq = MQ();
File “/home/pi/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 48, in __init__
self.Ro = self.MQCalibration(self.MQ_PIN)
File “/home/pi/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 83, in MQCalibration
val += self.MQResistanceCalculation(self.adc.read(mq_pin))
File “/home/pi/Desktop/MQ2/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 69, in MQResistanceCalculation
return float(self.RL_VALUE*(1023.0-raw_adc)/float(raw_adc));
ZeroDivisionError: float division by zero
I am facing the same problem and did not find specific solution for float division by zero error. Any suggestion is highly appreciated
ADC checked ..can you please confirm used port are 19,21,23 and 24_?
have you installed the Adafruit library? yup these ports are confirmed, i have also updated the github readme on this with videos
for pins refer to https://pinout.xyz
Press CTRL+C to abort.
Abort by user
the result after i run the example.py
any help?
im using putty
can i connect MQ-5 gas sensor to raspberry pi ? if yes can u pls show me the circuit ?
Yes, the circuit is the same (use the analog output pin).
but it does not work
Hello,
when I run the program it is immediately aborting by user after printing calibrating.
I have rebuilt the device a few times with different parts to minimize the potential for a broken piece. The errors that keep appearing are blank read adc values, no calibration and spi not available even though SpiDev has been enabled. while trying to run the program in Thonny IDE on the Pi, Errors keep appearing on lines 49,72, and 89. Any help would be greatly appreciated!
Turns out I had the ADC chip in backwards. The values are now starting to populate but the program will now randomly exit after only displaying values for a second or two.
how did you do it
this is my output
Press CTRL+C to abort.
Calibrating…
Abort by user
how to solve this
hello sir, had you got solution for this problem, i am also facing the same problem. could you suggest me sir!
Thank you Felix for this awesome tutorial, it helped me a lot! I admire your patience to answer all these Googleable questions.
Please help me with sensor MQ135 & MQ7. I need for my project work. Any type of help is appreciated. ? shreyaghoradkar@gmail.com
i have problems
debugger
‘mq’._init_(), line 32:self.adc=MCP3008()
‘MCP3008’._init_(), line 7: self.spi.max_speed_hz=1000000 #1MHz
please i need help
Como puedo conectar dos sensores mq al mismo raspberry pido saludos y gracias
unbound method read() must be called with MCP3008 instance as first argument (got int instance instead)
this is the error im getting what could be the fix
unbound method read() must be called with MCP3008 instance as first argument (got int instance instead)
this is the problem im having
Hi … I tell you that thanks to you my sensor works. My new question is. how could i conect another sensor, could it be done conecting it to other gate on the same to mc3008 gate, how should i modified the code .. some idea or suggestion
Why don’t you use the digital output from the mq-2 sensor; but use the analog output + ADC?
Was just researching this as well, looks like the DO will only alert if gas is detected and wont give you specific values. You can only measure the amount of gas using analog output + converter
How can I change the configuration of the pins where the sensor is connected
How can I connect two mq sensors to the same raspberry pi, please can someone help me with the code, thanks
May i know how can you get the value of P1 (x = 200, y = ~ 1.62) —–1.62 from the datasheet?
that result is from the table in the datasheet
I am trying to setup a MQ-4 measuring Methane
self.CH4Curve = [2.3,0.24,-0.55] … my Winsen MQ-4 sensor spec indicates lg200 is 0.24 and lg10000 is 0.027 …through wolfram I get ( Log10(0.027) – log10(0.24) ) / ( log10(10000) – log10(200) ) = -0.558
how did you get the 2.3 value ?
any one have code mq-135 sensor with pi In python code.
mq2 gas sensor can detect acetylene?
can you please suggest one to identify it.
why we used MCP3008? i saw mq-135 sensor have already digital pin why we cannot direct digital pin.
That digital pin is not a serial communication pin. On the sensor’s circuit board, there is a potentiometer setting a threshold value. If analog output is above that threshold value, digital output becomes high. If analog output is below that threshold value, digital output becomes low.
This feature is for some basic diy circuits. For example, you can connect a LED to digital output pin. (There is a LED on the circuit board already 🙂 ) And you can set the potentiometer to a value that LED does not turns ON, in a clean air. If air goes bad (or whatever you name the situation), LED will turn ON after a gas density, depending your setting on potentiometer.
Hello sir,
I love this project and i want to make this project. You explain everything in this video but could you please provide me schematic diagram of this project?
i know the equation for -0.47
but
how do you get (x = 2.3, y = 0.21)?
hello sir how will we get the slope for the given x and y?
How about gas sensor for ethylene? is there any?
I am also interested in an ethylene gas sensor or one that at the very least has cross sensitivity.
My Ro=-0.213053 kohm. What’s wrong?
did you find a solution. I have same problem.
Can you please explain me the code or If I can find the code explanation anywhere? Please help, have already googled everything about spidev.
from spidev import SpiDev
class MCP3008:
def __init__(self, bus = 0, device = 0):
self.bus, self.device = bus, device
self.spi = SpiDev()
self.open()
self.spi.max_speed_hz = 1000000 # 1MHz
def open(self):
self.spi.open(self.bus, self.device)
self.spi.max_speed_hz = 1000000 # 1MHz
def read(self, channel = 0):
cmd1 = 4 | 2 | (( channel & 4) >> 2)
cmd2 = (channel & 3) << 6
adc = self.spi.xfer2([cmd1, cmd2, 0])
data = ((adc[1] & 15) << 8) + adc[2]
return data
def close(self):
self.spi.close()
and if possible help me with this code too
https://github.com/tutRPi/Raspberry-Pi-Gas-Sensor-MQ/blob/master/mq.py
Did you get it?
specifically this part of code:
cmd1 = 4 | 2 | (( channel & 4) >> 2)
cmd2 = (channel & 3) << 6
adc = self.spi.xfer2([cmd1, cmd2, 0])
data = ((adc[1] & 15) << 8) + adc[2]
PLEASE HELP
This estimation of Rs/Ro from datasheet come with Big number of Error.
If I have a sensehat will I still be able to attach this or will I have to remove the sensehat? Is there some way to extend the pins or something?
Press CTRL+C to abort.
Calibrating…
Traceback (most recent call last):
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/example.py”, line 5, in
mq = MQ();
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 45, in __init__
self.Ro = self.MQCalibration(self.MQ_PIN)
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 80, in MQCalibration
val += self.MQResistanceCalculation(self.adc.read(mq_pin))
File “/home/pi/Raspberry-Pi-Gas-Sensor-MQ/mq.py”, line 66, in MQResistanceCalculation
return float(self.RL_VALUE*(1023.0-raw_adc)/float(raw_adc));
ZeroDivisionError: float division by zero
Your ADC might be returning 4095.0 instead of 1023.0 for Maximum Analog Voltage, as in my case. First, connect 3.3 V to your channel 0 and print the ADC read value to the screen. After realizing a value ~4095, you should replace 1023.0 with 4095.0
Channel 0 is connected to RX0. So should we remove that connection?
You just need to test the digital value which is generated by the software and hardware both. You can use any of the ADC’s channels. You should connect a line(cable, etc, whatevery you call) to an ADC pin at a time.
For your specific question: Yes you should remove that to measure the correct value.
Did you find solution for negative Ro? I am having similar results with gases not being detected.
Hi,
I realized that there is a little mistake on the code. In python math.log() takes log on base 2, not on base 10. math.log10() should be used for log based on 10.
“`
def MQGetPercentage(self, rs_ro_ratio, pcurve):
return (math.pow(10,( ((math.log(rs_ro_ratio)-pcurve[1])/ pcurve[2]) + pcurve[0])))
“`
Therefore the code above should be updated as like the below.
“`
def MQGetPercentage(self, rs_ro_ratio, pcurve):
return (math.pow(10,( ((math.log10(rs_ro_ratio)-pcurve[1])/ pcurve[2]) + pcurve[0])))
“`
Hi,
I am doing this project with mq135. However when i print adc in the following code
def read(self, channel = 0):
cmd1 = 4 | 2 | (( channel & 4) >> 2)
cmd2 = (channel & 3) << 6
adc = self.spi.xfer2([cmd1, cmd2, 0])
print(adc)
data = ((adc[1] & 15) << 8) + adc[2]
return data
I get a list of 0 like[0 0 0]. Due to this I am getting a divided by 0 error. What can I do to resolve it?
Could you please check your connections? Do not forget ALL OF THE 8 pins of MCP3008 which are on the opposite side of the channel pins. After being sure of this, check return value again. If the problem still occurs, instead of sensor output, connect 3.3 V to a channel and check the printed value again.
how is its gonna be only 1 curve ? i’m using TGS how the code “def … percentage” should be ?
“ALL OF THE 8 pins of MCP3008 which are on the opposite side of the channel pins” should be connected. Do not skip any of them.
Hi,
Thanks for you help.
I checked for the values after connecting 3.3V I was getting 1023 constantly. Yet the program is aborting
I followed all the steps and when I type sudo python example.py it says abort by user even though I did not abort. How can this be fixed?
I am trying to do a project where I am utilizing multiple gas sensors. I know that the MCP3008 can support 8 devices at once, but I have read in forums that the Raspberry Pi can only handle 2 SPI slaves. I have made gas sensors multiple circuits utilizing one MCP3008 and TTL, so will that work? (They are soldered circuits). I have already utilized one of those circuits and that works fine. I have a GPIO expansion board with three GPIO pin headers, so I have 120 pins to utilize, all with the same layout as the normal pin header. If not, could I connect 8 sensors to one MCP3008? And what kind of changes would I need to make to MCP3008?
Sorry, I meant MCP3008.py.
“Abort by user” is being displayed. Anything you can help?
I have the same problem. Have you solved?
Have u got the solution plz contact me
On this email laxmanrathod455@gmail.com
I’m trying to understand why logic level converter is needed between ADC (MCP3008) and MQ sensor.
according to this comment
https://www.raspberrypi.org/forums/viewtopic.php?t=189209#p1191345
there is no need for that and IMHO this comment makes sense.
Hi, I’m just try to get it running.
The error-messages say, that “no module named spidev”
Ok, I checked that on the net, using
mkdir python-spi
cd python-spi
wget https://raw.github.com/doceme/py-spidev/master/setup.py
wget https://raw.github.com/doceme/py-spidev/master/spidev_module.c sudo python setup.py install
ending up with the following message:
Traceback (most recent call last):
File “setup.py”, line 29, in
long_description= open(‘README.md’).read() + “n” + open(‘CHANGELOG.md’).read(),
IOError: [Errno 2] No such file or directory: ‘README.md’
Unfortunately I did not find a suitable solution on the net.
Do you have any suggestions?
Best regards
B.
Hi,
I am using ARPI600 on my RPI as ADC, can you tell me what changes I will have to make for MQ-137 and MQ-135 to get it work?
It will be of great help
arpi600 https://www.waveshare.com/wiki/ARPI600
Does the code work for Python 3 too?
i use it too and it’s work
from the python code is calculated only GAS LNG, CO and SMOKE, to get the values of others (H2, air, propane, alcohol, etc.) is it enough to add in the class class MQ () the calculated points?
It worked for me! Thank you so much. Is it possible though to have Mathematica read off the sensor (instead of concentration displaying in the terminal?) Thanks!
I followed all the steps given but why does the value of resistance is negative?
Press CTRL+C to abort.
Calibrating…
Calibration is done…
Ro=-0.231164 kohm
LPG: 0.0076744 ppm, CO: 0.00497707 ppm, Smoke: 0.0204785 ppm
and there is no change on the value when I spray some lighter gas on the sensor
I encounter the same problem. when gas/smoke is added, the values go down! Must be something in “example.py”?
Ro=-0.247752
LPG: 0.00542804 ppm, CO: 0.00308366 ppm, Smoke: 0.0141463 ppm
I encounter the same problem. when gas/smoke is added, the values go down! Must be something in “example.py”?
Ro=-0.247752
Hi bro I also refer the same git hub code but I am facing divide by zero. Error exception
As u said you are getting some value atleast plz contact me or help me
Thanks is advance
On this email id
laxmanrathod455@gmail.com
I’m getting error on MQ-5
Press CTRL+C to abort.
Calibrating…
float division by zero
Why?
Hi! First: THANK YOU VERY MUCH for your great work!
I was using your wiring and code with a MQ-5 and it worked fine! However, when I changed the MQ-5 with a MQ-2 – the same sensor you are using – I get a strange behaviour: LPG and CO values drop when the sensor is exposed to LPG / CO instead of rising which means, the values are going down to an e-05 value… Do you have any explanation for this? Do I need to do a 1 / [value] calculation to correct that?
THANK YOU!
(and yes, I already tried another MQ-2 sensor)
Thanks for having this article, it helps a lot. It’s a well-written blog and it is very informative. Keep on blogging, looking forward to see more of your posts!
Hi, actually i am using raspberry pi 3b+
i need a help on MQ3 and ADC
How to install and how to run the program….?
Hiii, does anyone know how to get (x=2.3, y=0.21) for the calibration?
ooo silly me! its log(200)=2.3 and log(1.62)=0.21
Please help the code is showing this error while logging the exception
Press CTRL+C to abort.
Calibrating…
ERROR:root:
Abort by user
Traceback (most recent call last):
File “/home/pi/Documents/a/r/example.py”, line 8, in
mq = MQ();
File “/home/pi/Documents/a/r/mq.py”, line 48, in __init__
self.Ro = self.MQCalibration(self.MQ_PIN)
File “/home/pi/Documents/a/r/mq.py”, line 83, in MQCalibration
val += self.MQResistanceCalculation(self.adc.read(mq_pin))
File “/home/pi/Documents/a/r/mq.py”, line 69, in MQResistanceCalculation
return float(self.RL_VALUE*(1023.0-raw_adc)/float(raw_adc));
ZeroDivisionError: float division by zero
can i not using the voltage converter?
What do you mean?
I agree with you.
I don’t understand the voltage converter role.
hei felix. how is its gonna be only 1 curve ? i’m using TGS how the code “def … percentage” should be ? The value just show Ro if i delete 2 other curve
Hi Dewi
regarding the datasheet, with one value, we can read out all three values for the gases.
Hi,
you mention the I2C bus in the article but you’ve used the SPI bus in the Python code.
Why ? Is the SPI bus is better than the I2C.
Which one to prefer ?
Hi,
I don´t know where to find the MCP3008 library. Can you help me please?
Hi,
I have the ads1115 ADC instead of the MCP3008. I want to connect it two analog devices.
Is it better to connect devices on a single ADC or one ADC per device must be wired ?
Thanks
Hi, I follow all the steps as shown in the video but I am stuck after enter the example.py, it just showing me Ctrl + C to abort without calibrating… Anyone can help me with this?
mesropgugeseva@mail.ru
Hello,
I don’t understand the role of the TTL, and don’t understand the phrase “In this example, we use a 5V voltage as output. This is too much for the GPIOs, which is why we use a logic level converter (TTL) that cuts down the voltage.”
If i understand, the input value of the Raspberry is a numeric value because the Raspberry can’t read analog value.
So, what is the voltage you send to the Raspberry ?
At the output of the ADC is necessarily a numeric, right ? So what is the limit of 5V ? there is no analog value between the ADC and the Raspberry, right ?
Thanks
looking at the image… where must I connect the yellow cable?
how’s the wiring if I have this waveshare hat?
https://www.waveshare.com/wiki/High-Precision_AD/DA_Board
Hello friends, someone has the values for the mq-3 sensor with mcp3008. I am new to programming. I thank you very much.
Did you ever find them?
Is there a code example to get this to work with the ads1115??
I’m stuck because I’m not using the same ADC…
Hi, I have a simple question.
As you mentioned, we need two points on the graph for calibration.
How can we know the exact coordinates like (200, 1.62), (10000, 0.26)?
Datasheets only give the figure of the graph, not the exact values. So, it’s a bit confusing to me what numbers I should use.
Thank you in advance!
Can I use PCF8591 Module in place of (MCP3008 ADC + 3.3v 5v I2C logic level converter)?
Kindly someone confirm?
i kept getting abort by user
do i need to rearrange the whole connection back or what?
Hi felix! Thank you for this. I tried on MQ135 changing the values from the datasheet and it worked. I wonder where did you get Ro=3.46 tho? my values were 25000 ppm above. Thank you, any help is appreciated.
actually i just tried it again, and it gave me negative value for Ro and 0.0000x for the ppm
I get the same -Ro , I don’t know what’s wrong.
I get the same -Ro , I don’t know what’s wrong.
how do you connect 2 mq sensors? just follow the pins like your example and connect to analog pin 1 of mcp3008? how about the code?
Just an FYI This library only supports Smoke, CO and Propane. For methane etc you need look elsewhere.