Advertisement
microrobotics

MH-Z19 NDIR CO2 Sensor 5000PPM

Mar 30th, 2023
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. The MH-Z19 NDIR CO2 Sensor is a non-dispersive infrared sensor that measures the concentration of carbon dioxide (CO2) in the air. Here's an example code in Arduino that reads the CO2 concentration from the sensor:
  3.  
  4. Note: This code assumes that the MH-Z19 NDIR CO2 Sensor is connected to pins 2 and 3 of the Arduino board for the software serial connection. If you're using different pins or a hardware serial connection, you'll need to modify the SoftwareSerial initialization and co2Serial object accordingly. Also, note that the sensor requires a warm-up time of at least 3 minutes after power-on before providing accurate readings, so be sure to wait for this period before reading from the sensor. Finally, note that the sensor is designed to detect carbon dioxide specifically and may not detect other gases or vapors.
  5. */
  6.  
  7. #include <SoftwareSerial.h>
  8.  
  9. SoftwareSerial co2Serial(2, 3);  // RX, TX pins of the software serial connection to the sensor
  10.  
  11. void setup() {
  12.   Serial.begin(9600);
  13.   co2Serial.begin(9600);  // start the software serial connection to the sensor
  14. }
  15.  
  16. void loop() {
  17.   co2Serial.write("\xff\x01\x86\x00\x00\x00\x00\x00\x79");  // request a CO2 concentration reading from the sensor
  18.   delay(10);
  19.   while (co2Serial.available() > 0) {
  20.     if (co2Serial.read() == '\xff') {
  21.       if (co2Serial.read() == '\x86') {
  22.         int co2_concentration = co2Serial.read() * 256;
  23.         co2_concentration += co2Serial.read();
  24.         Serial.print("CO2 Concentration: ");
  25.         Serial.print(co2_concentration);
  26.         Serial.println(" ppm");
  27.       }
  28.     }
  29.   }
  30.   delay(1000);
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement