WifWaf / MH-Z19

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

MHZ19::read returns sometimes RESULT_MATCH forever #25

Closed mumpitzstuff closed 3 years ago

mumpitzstuff commented 3 years ago

The library seems to get out of sync sometimes after 2-3 days running without any problems. If such an error occurs i always get the response RESULT_MATCH forever. I tried to analyze the code of MHZ19::read and what i understand so far is that you wait until you received at least 9 bytes of data. But what happens if you get more than 9 bytes because of an error? It seems that you just read 9 bytes, also if 10 bytes would be available. The next time the read function is called, you would have again 10 and not 9 bytes in your receive buffer (1 old byte from the previous corrupt message and the 9 bytes from the new message). But now everything is out of sync because of the invalid byte in the receive buffer which is never deleted. Does this make any sense and could this be the reason for my problems?

I added the following patch to give it a try but i dont have any results so far:

while (mySerial->available() < MHZ19_DATA_LEN)
{
...
}

/* try to resync data */
while (mySerial->available() > MHZ19_DATA_LEN && (unsigned char)mySerial->peek() != 0xFF) 
{
    mySerial->read(); 
}

/* response recieved, read buffer */
mySerial->readBytes(inBytes, MHZ19_DATA_LEN);

/* clear receive buffer */
while (mySerial->available())
{
    mySerial->read();
} 
WifWaf commented 3 years ago

This makes sense and cheers for taking the time to work it out.

Not to sure if there is a downside to cleaning up the rx buffer every time read is called (apart from the extra clock tick)? For now, I've just moved the existing code to a function and called it as below.

Changes are: Function and called here and here.

The branch is here for now https://github.com/WifWaf/MH-Z19/tree/Testing_Original_Branch.

mumpitzstuff commented 3 years ago

Downloaded your patch today and will give it a try the next days.

mumpitzstuff commented 3 years ago

The patch seems to work. I have not seen the error since 2 weeks now. Anyway i am not sure if the cleanup should also be added in case of a crc error because such out of sync error could also trigger an crc error and could hang forever. You could also check the message structure before you calculate and check the crc to avoid the problem.

WifWaf commented 3 years ago

Great, and cheers the feedback.

I think this should be okay as if the CRC check does fail (it's called first), the mismatch check is still called which should also error in a desync event and clean up the buffer - I'll try and give it a test anyway.

If all is okay, I'll close the issue, but just open another one if anything else comes up.