跳到主要內容


Testing the MH-Z19 Infrared CO2 Sensor Module


CO2 sensor type MH-Z19 infrared

Introduction:

In this article we will do a simple functional test of the MH-Z19 CO2 sensor by connecting it to a raspberry pi 3 UART and run a simple datalogger python program which prints results to the screen and stores results in a csv formatted file.
The file can later be imported to matlab or excel for further analysis or just plot a graph of the collected data.
If you want to use a PC or Raspberry Pi or Beaglebone or any other SOC to measure CO2 levels, a sensor with a serial interface is a good choice. The MH-Z19 features a UART serial interface and 5V power supply and 3.3V IO levels. This makes is easy to connect it directly to a Raspberry Pi or to a PC (If PC, you need to use an USB/serial converter(CMOS/TTL levels, not RS232 levels)). It also features an pulse width modulated (PWM) output where the duty cycle changes with CO2 concentration which could be buffered and low pass filtered to get an analog signal representing the CO2 level.

Save health and energy with CO2 sensors

When breathing, humans and animals increase the concentration if CO2 in the exhaled air. This is a normal biological process. In the outside, this is not a problem as plants consume the additional CO2. Burning fossil fuels also increase the outside CO2 levels, and the plants cannot handle such a huge amounts which creates very negative long term effects, but that is not what we are talking about here.
However, in closed living rooms without enough ventilation, CO2 levels can increase quite a lot from the initial outside levels of 400 ppm to inside levels of 2000-3000ppm. High CO2 levels, above 1000ppm, can lead to drowsiness, poor concentration, loss of attention or increased heart rate.
Especially modern buildings without a well-designed ventilation system can be a bit problematic. Therefore, monitoring CO2 levels in living rooms is a good idea as it gives you a good indication when you should increase the ventilation (e.g. by opening the windows for some time).
Large buildings like schools and office buildings have huge ventilation systems which use a lot of electric power just to make sure that the inside air is cooled or heated and replaced within a certain interval of time to make sure the inside air is of good quality 24/7. A lot of energy can be saved by controlling such a system based on strategically placed CO2 sensors around the building and run the system based on demand caused by occupancy rather than continuously or controlled by a simple timer.
Such a CO2-based demand controlled ventilation system can control the amount of outdoor fresh air supply in a building depending on the number of people and their activity. People are the main source of CO2 in a building. If the number of people in a room is doubled, the CO2 level will accordingly double. If one or few people leave a room, the level of CO2 will proportionally decrease. Hence, demand controlled ventilation saves energy solely by not replacing, heating, or cooling, unnecessary amount of outdoor air.

MH-Z19 sensor picture
Fig.2. The MH-Z19 CO2 sensor manufactured by Winsen Ltd.

About the MH-Z19 CO2 sensor

The MH-Z19 sensor is manufactured by Winsen Lt., China and the measurement method used is based on the non-dispersive infrared (NDIR) principle to detect the existence of CO2 in the air.
Key features according to the manufacturer are:
  • good sensitivity.
  • non-oxygen dependent.
  • long life.
  • built-in temperature compensation.
  • UART serial interface and Pulse Width Modulation (PWM) output.
A nondispersive infrared sensor (or NDIR sensor) is a relatively simple spectroscopic sensor often used as a gas detector. It is nondispersive in the sense of optical dispersion since the infrared energy is allowed to pass through the atmospheric sampling chamber without deformation.
Principle of operation:
The main components of an NDIR sensor are an infrared source (lamp), a sample chamber or light tube, a light filter and an infrared detector. The IR light is directed through the sample chamber towards the detector. In parallel there is another chamber with an enclosed reference gas, typically nitrogen. The gas in the sample chamber causes absorption of specific wavelengths according to the Beer–Lambert law, and the attenuation of these wavelengths is measured by the detector to determine the gas concentration. The detector has an optical filter in front of it that eliminates all light except the wavelength that the selected gas molecules can absorb.
The MH-Z19B NDIR infrared CO2 gas detection module is typically used in:
  • HVAC equipment in schools, office buildings etc.
  • Green houses
  • Indoor air quality monitoring.
  • Smart home appliances
The user manual can be found here.  or at //www.winsen-sensor.com
Technical specification :
Technical Specifications MH-Z19
Target gasCarbon Dioxide CO2
Operating Voltage3.6 to 5.5 Vdc
Operating current< 18mA average
Interface levels3.3 Vdc
Output signal formatUART or PWM
Preheat time3 min
Response time<60 s="" td="">
Accuracy± (50 ppm+5% reading value)
Measuring range0 to 5000 ppm
Operating temperature range0 to + 50°C
Dimensions33mm×20mm×9mm(L×W×H)
Looking at the sensor from the bottom, you will see the following pins:

MH-Z19 pins
Fig 1. MH-Z19 pinning

The pins have a 2.54mm (0.1″) pitch, that makes it easy to solder a simple one-row pin header as shown in Fig. 1 above.

Connecting to the Raspberry Pi:


Raspberry Pi 3 connected to MH-Z19 sensor
Fig. 3. MH-Z19 connected to Raspberry PI 3

FunctionRaspi pinMH-Z19 pin
Vcc +5V2 +5V6 Vin
GND6 GND7 GND
UART8 TXD02 RXD
UART10 RXD03 TXD

MH-Z19 pin placement and definitions
Fig.6. MH-Z19 pin definitions.

The MH-Z19 have a internal 5V to 3.3V low drop analog voltage regulator. This makes the logic signals on RX and TX compatible to the Raspberry Pi logic levels which are CMOS 3.3V. Hence, no level converters are needed.

Preparing the Raspberry Pi 3 for UART communication.

The Raspberry pi UART present on the GPIO (the 40-pin connector) requires some preparing before use.
You have to:
-Turn off the console if it is using the UART as login shell.
-Enable the UART in the /dev/config.txt file.
Detailed information on how to configure the UART on Raspberry Pi 3 can be found here.

MH-Z19 python datalogger test program

The simple test program opens the UART com port serial0 and tries to read CO2 measurement values from the CO2 sensor every minute. The program prints every measurement to the screen and logs timestamped measurements to a csv formatted file, which is given the current date and time as the filename. Improvements to the program are welcome 🙂
#!/usr/bin/python
import serial, os, time, sys, datetime, csv

def logfilename():
    now = datetime.datetime.now()
    #Colon is not alowed in filenames so we have to include a lookalike char 
    return 'CO2LOG-%0.4d-%0.2d-%0.2d-%0.2d%s%0.2d%s%0.2d.csv' % 
            (now.year, now.month, now.day, now.hour,
            u'ua789',now.minute, u'ua789', now.second)

#Function to calculate MH-Z19 crc according to datasheet
def crc8(a):
    crc=0x00
    count=1
    b=bytearray(a)
    while count<8:
        crc+=b[count]
        count=count+1
    #Truncate to 8 bit
    crc%=256
    #Invert number with xor
    crc=~crc&0xFF
    crc+=1
    return crc

    # try to open serial port
    
port='/dev/serial0'
sys.stderr.write('Trying port %sn' % port)
            
try:
    # try to read a line of data from the serial port and parse    
    with serial.Serial(port, 9600, timeout=2.0) as ser:
        # 'warm up' with reading one input
        result=ser.write("xffx01x86x00x00x00x00x00x79")
        time.sleep(0.1)
        s=ser.read(9)
        z=bytearray(s)
        # Calculate crc
        crc=crc8(s) 
        if crc != z[8]:
            sys.stderr.write('CRC error calculated %d bytes= %d:%d:%d:%d:%d:%d:%d:%d crc= %dn' % (crc, z[0],z[1],z[2],z[3],z[4],z[5],z[6],z[7],z[8]))
        else:
            sys.stderr.write('Logging data on %s to %sn' % (port, logfilename()))
        # log data
        outfname = logfilename()
        with open(outfname, 'a') as f:
        # loop will exit with Ctrl-C, which raises a KeyboardInterrupt
            while True:
                #Send "read value" command to MH-Z19 sensor
                result=ser.write("xffx01x86x00x00x00x00x00x79")
                time.sleep(0.1)
                s=ser.read(9)
                z=bytearray(s)
                crc=crc8(s)
                #Calculate crc
                if crc != z[8]:
                    sys.stderr.write('CRC error calculated %d bytes= %d:%d:%d:%d:%d:%d:%d:%d crc= %dn' % (crc, z[0],z[1],z[2],z[3],z[4],z[5],z[6],z[7],z[8]))
                else:       
                    if s[0] == "xff" and s[1] == "x86":
                        print "co2=", ord(s[2])*256 + ord(s[3])
                co2value=ord(s[2])*256 + ord(s[3])
                now=time.ctime()
                parsed=time.strptime(now)
                lgtime=time.strftime("%Y %m %d %H:%M:%S")
                row=[lgtime,co2value]
                w=csv.writer(f)
                w.writerow(row)
                #Sample every minute, synced to local time
                t=datetime.datetime.now()
                sleeptime=60-t.second
                time.sleep(sleeptime)
except Exception as e:
    f.close()
    ser.close()
    sys.stderr.write('Error reading serial port %s: %sn' % (type(e).__name__, e))
except KeyboardInterrupt as e:
    f.close()
    ser.close()
    sys.stderr.write('nCtrl+C pressed, exiting log of %s to %sn' % (port, outfname))

Running the test program

Save the testprogram above as mhz19.py.
Open a terminal window (Rasbian Lxterminal) and enter:
sudo python mhz10.py 
The figure below shows the output of the simple mhz19.py test program. The CO2 measurements are sampled every minute.

terminal out datalogger mh-z19
Fig.4. Datalogger mhz19.py terminal output when running.

This is the contents of the csv formatted log file:

mh-z19 logfile csv format
Fig.5. MH-Z19 logfile csv format.

This csv file format can easily be imported to excel and plotted as a graph:

CO2 excel graph
Fig.5 An excel graph of the CO2 levels during 20 hours

Calibrating the CO2 sensor

CO2 Sensor Calibration: What You Need to Know
All carbon dioxide sensors need calibration. Depending on the application, this can be accomplished by calibrating the sensor to a known gas, or using the automatic baseline calibration (ABC) method. Both have pros and cons you should know.
Why Calibrate?
The non-dispersive infrared (NDIR) carbon dioxide sensors rely on an infrared light source and detector to measure the number of CO2 molecules in the sample gas between them. Over many years, both the light source and the detector deteriorate, resulting in slightly lower CO2 molecule counts.
To combat sensor drift, during calibration a sensor is exposed to a known gas source, multiple readings are taken, an average is calculated, and the difference between the new reading and the original reading when the sensor was originally calibrated at the factory is stored in EPROM memory. This “offset” value is then automatically added or subtracted to any subsequent readings taken by the sensor during use.
Calibration Using Nitrogen
The most accurate method of CO2 sensor calibration is to expose it to a known gas (typically 100% nitrogen) in order to duplicate the conditions under which the sensor was originally calibrated at the factory. Nitrogen calibration is also required if CO2 levels between 0-400 ppm will be measured. The problem with calibrating using nitrogen is the expense. A sealed calibration enclosure, a tank of pure nitrogen, and calibration software is required to match the original factory testing environment. Otherwise, the accuracy of the calibration cannot be ensured.
Calibration Using Fresh Air
Where maximum accuracy is less important than cost, a CO2 sensor can be calibrated in fresh air. Instead of calibrating at 0ppm CO2 (nitrogen), the sensor is calibrated at 400ppm CO2 (outdoor air is actually very close to 400ppm), then 400 ppm is subtracted from the newly calculated offset value.
Fresh air calibration is best for sensors in manufacturing settings or greenhouses where the sensor is constantly exposed to different CO2 levels.
Automatic calibration
Automatic calibration is based on the fact that in a common environment, the CO2 level comes back to the norm (400ppm CO2) periodically, at least every few days. Starting from there, you can make your measurement software constantly monitor the lowest observed CO2 level over a period of several days. If these lowest values diverge from the norm, your sensor software could gradually make a correction to compensate for the change.

This is an efficient and reliable method for a typical environment where the CO2 level goes back to normal when there is no CO2 production for a few hours: during the night for businesses, during the day for a bedroom.

Conclusion

The MH-Z19 seems to work as expected.

留言

這個網誌中的熱門文章

opencv4nodejs Asynchronous OpenCV 3.x Binding for node.js   122     2715     414   0   0 Author Contributors Repository https://github.com/justadudewhohacks/opencv4nodejs Wiki Page https://github.com/justadudewhohacks/opencv4nodejs/wiki Last Commit Mar. 8, 2019 Created Aug. 20, 2017 opencv4nodejs           By its nature, JavaScript lacks the performance to implement Computer Vision tasks efficiently. Therefore this package brings the performance of the native OpenCV library to your Node.js application. This project targets OpenCV 3 and provides an asynchronous as well as an synchronous API. The ultimate goal of this project is to provide a comprehensive collection of Node.js bindings to the API of OpenCV and the OpenCV-contrib modules. An overview of available bindings can be found in the  API Documentation . Furthermore, contribution is highly appreciated....

2017通訊大賽「聯發科技物聯網開發競賽」決賽團隊29強出爐!作品都在11月24日頒獎典禮進行展示

2017通訊大賽「聯發科技物聯網開發競賽」決賽團隊29強出爐!作品都在11月24日頒獎典禮進行展示 LIS   發表於 2017年11月16日 10:31   收藏此文 2017通訊大賽「聯發科技物聯網開發競賽」決賽於11月4日在台北文創大樓舉行,共有29個隊伍進入決賽,角逐最後的大獎,並於11月24日進行頒獎,現場會有全部進入決賽團隊的展示攤位,總計約為100個,各種創意作品琳琅滿目,非常值得一看,這次錯過就要等一年。 「聯發科技物聯網開發競賽」決賽持續一整天,每個團隊都有15分鐘面對評審團做簡報與展示,並接受評審們的詢問。在所有團隊完成簡報與展示後,主辦單位便統計所有評審的分數,並由評審們進行審慎的討論,決定冠亞季軍及其他各獎項得主,結果將於11月24日的「2017通訊大賽頒獎典禮暨成果展」現場公佈並頒獎。 在「2017通訊大賽頒獎典禮暨成果展」現場,所有入圍決賽的團隊會設置攤位,總計約為100個,展示他們辛苦研發並實作的作品,無論是想觀摩別人的成品、了解物聯網應用有那些新的創意、尋找投資標的、尋找人才、尋求合作機會或是單純有興趣,都很適合花點時間到現場看看。 頒獎典禮暨成果展資訊如下: 日期:2017年11月24日(星期五) 地點:中油大樓國光廳(台北市信義區松仁路3號) 我要報名參加「2017通訊大賽頒獎典禮暨成果展」>>> 在參加「2017通訊大賽頒獎典禮暨成果展」之前,可以先在本文觀看各團隊的作品介紹。 決賽29強團隊如下: 長者安全救星 可隨意描繪或書寫之電子筆記系統 微觀天下 體適能訓練管理裝置 肌少症之行走速率檢測系統 Sugar Robot 賽亞人的飛機維修輔助器 iTemp你的溫度個人化管家 語音行動冰箱 MR模擬飛行 智慧防盜自行車 跨平台X-Y視覺馬達控制 Ironmet 菸消雲散 無人小艇 (Mini-USV) 救OK-緊急救援小幫手 穿戴式長照輔助系統 應用於教育之模組機器人教具 這味兒很台味 Aquarium Hub 發展遲緩兒童之擴增實境學習系統 蚊房四寶 車輛相控陣列聲納環境偵測系統 戶外團隊運動管理裝置 懷舊治療數位桌曆 SeeM智能眼罩 觸...
自製直播音源線 Bird Liang   October 6, 2016   in  View Bird Liang, Chief Engineer (梁子凌 / 技術長兼工程輔導長) 負責 AppWorks 技術策略與佈署,同時主導工程輔導。人生的第一份正職工作是創業,之後在外商圈電子業中闖蕩多年,經歷過 NXP、Sony、Newport Imagining、Crossmatch 等企業,從事無線通訊、影像系統、手機、面板、半導體、生物辨識等不同領域產品開發。熱愛學習新事物,協助團隊解決技術問題。放棄了幾近退休般的生活加入 AppWorks,為的是幫助更多在創業路上的人,並重新體驗創業的熱情。台大農機系、台科大電子所畢業,熱愛賞鳥、演奏管風琴,亦是不折不扣的熱血 Maker。 隨著 Facebook 開放一般帳號直播,現在我們只要拿起手機,隨時隨地都可以開始直播。回想幾年前 AppWorks 剛開始進行 Demo Day 直播時,還要將 HDMI 訊號接進 PC 中、再編碼打進 YouTube 的複雜度,實不可同日而語。 但用手機或平板直播最大的問題往往不是影像而是聲音。iPhone 或 iPad 上的攝影機,感度和解析度早已不輸數年前的專業攝影機,只要現場光不太差,大概都可以拍出令人滿意的畫面。但直播的聲音一直是個大問題,手機上的麥克風跟人耳所聽到的聲音其實有很大的差距,在比較大的場子裡,光是仰賴內建麥克風的收音多半無法有令人滿意的效果。 在大型的活動中,現場通常會有 PA 系統,最理想的方式還是想辦法將 PA 的訊號餵進 iPad 或 iPhone 中,保證聲音乾淨又清楚,絕對不會有其它有的沒的現場音。 iPhone 的耳機孔雖然可以插帶有麥克風的耳機 (如 Apple 原廠的 EarPods),但它的訊號位準是電容式麥克風的位準。PA 控台的輸出幾乎都是 line level 的,兩者的訊號電壓相差百倍以上,我們得做個小東西來解決這個差距。 Line 與 Mic 在 mixer 上,我們常會看到輸入可以在兩種規格中切換: line level 和 mic level。Mic level 顧名思義就是從麥克風來的訊號,這個訊號的規格是從不需供電的傳統動圈麥克風來的。因為不需...