WifWaf / MH-Z19

For Arduino Boards (&ESP32). Additional Examples/Commands., Hardware/Software Serial
GNU Lesser General Public License v3.0
196 stars 41 forks source link

getCO2() sends wrong serial command? #7

Closed kordian-kowalski closed 4 years ago

kordian-kowalski commented 5 years ago

According to the MH-Z19's manual, the command to get the co2 reading is 0x86. Following the basic usage example in this repository, it seems that 0x85 is being sent instead. Here's a screenshot from a logic analyzer showing Tasmota correctly polling for the reading: Logic_eUTjYcvB8w Here's your arduino library: Logic_wRio3f2ICs

The code I'm using:

#include <MHZ19.h>
#include <SoftwareSerial.h>
#define RX_PIN 8
#define TX_PIN 9
#define BAUDRATE 9600

MHZ19 myMHZ19;
SoftwareSerial mhzSerial(RX_PIN, TX_PIN);

unsigned long getDataTimer = 0; 

void setup() {
  mhzSerial.begin(BAUDRATE);
  myMHZ19.begin(mhzSerial);
  myMHZ19.setRange(2000);
  myMHZ19.setSpan(2000);

  Serial.begin(115200);
}

void loop() {
    if (millis() - getDataTimer >= 2000)                    // Check if interval has elapsed (non-blocking delay() equivilant)
    {
        int CO2;                                            // Buffer for CO2
        CO2 = myMHZ19.getCO2();                             // Request CO2 (as ppm)

        Serial.print("CO2 (ppm): ");                      
        Serial.println(CO2);                          

        getDataTimer = millis();                            // Update interval
    }
}

Am I doing something wrong here?

kordian-kowalski commented 5 years ago

Also the reading itself is way off, it starts off at ~8000 and goes down to ~3000 after a minute.

kordian-kowalski commented 5 years ago

It seems that using .getCO2(false); will issue the correct command - not sure why this is not the default behavior.

WifWaf commented 5 years ago

The default is an alternative not documented which allows you to return a CO2 reading uncapped (unlimited by range or background CO2); it's useful to see if the sensor is misbehaving. For example in your case it might be above your defined range - you know there's an issue. You can find these details in the examples (though not in BasicUsage, I've updated this) or in the library it's self which is mostly annotated.

I would guess that your sensor has not been calibrated correctly, which can be awkward. If you're not having any luck with the example, try pulling the zero HD pin low for 7 Sec (see the datasheets in extras) or the Calibration example (which has been updated to be clearer also).

WifWaf commented 4 years ago

Closing due to inactivity - feel free to reopen.