Mh-z16 problem esp 32

I am working on a project with a CO 2 sensor (MH-Z16) and I am using the ESP32 module. After several tries I still can't get it to work. The monitor sends me values like: 128 144 31 251 63 152 1 252 63 . I still don't understand why, please help me. I am using this code And the result is
resultat capteur mh z16

/*
  This test code is write for Arduino AVR Series(UNO, Leonardo, Mega)
  If you want to use with LinkIt ONE, please connect the module to D0/1 and modify:
 
  // #include <SoftwareSerial.h>
  // SoftwareSerial s_serial(2, 3);      // TX, RX
 
  #define sensor Serial1
*/
 
 
#include <SoftwareSerial.h>
SoftwareSerial s_serial(17, 16);      // TX, RX
 
#define sensor s_serial
 
const unsigned char cmd_get_sensor[] =
{
    0xff, 0x01, 0x86, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x79
};
 
unsigned char dataRevice[9];
int temperature;
int CO2PPM;
 
void setup()
{
    sensor.begin(9600);
    Serial.begin(115200);
    Serial.println("get a 'g', begin to read from sensor!");
    Serial.println("********************************************************");
    Serial.println();
}
 
void loop()
{
    if(dataRecieve())
    {
        Serial.print("Temperature: ");
        Serial.print(temperature);
        Serial.print("  CO2: ");
        Serial.print(CO2PPM);
        Serial.println("");
    }
    delay(1000);
}
 
bool dataRecieve(void)
{
    byte data[9];
    int i = 0;
 
    //transmit command data
    for(i=0; i<sizeof(cmd_get_sensor); i++)
    {
        sensor.write(cmd_get_sensor[i]);
    }
    delay(10);
    //begin reveiceing data
    if(sensor.available())
    {
        while(sensor.available())
        {
            for(int i=0;i<9; i++)
            {
                data[i] = sensor.read();
            }
        }
    }
 
    for(int j=0; j<9; j++)
    {
        Serial.print(data[j]);
        Serial.print(" ");
    }
    Serial.println("");
 
    if((i != 9) || (1 + (0xFF ^ (byte)(data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7]))) != data[8])
    {
        return false;
    }
 
    CO2PPM = (int)data[2] * 256 + (int)data[3];
    temperature = (int)data[4] - 40;
 
    return true;
}

I'm curious as to why are you using software serial with an esp32 when an esp32 has several hardware serial ports?

In global I declare the hardware serial port #include <HardwareSerial.h> and //serial(2) = pin25 RX, pin26 TX HardwareSerial co2Serial ( 2 );
In setup() the declared hardware serial port is initialized.
co2Serial.begin( 9600 , SERIAL_8N1, 25, 26 ); // pin25 RX, pin26 TX

1 Like

I have a project school and my teacher said i need to do with an ESP 32 , i will try monday if it work for me and thank you for your answer .

Hello again please i can have the whole code this can really help me thank you

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.