From 0c6306e8d6ca3330e7ecf82a9463b4629af5760d Mon Sep 17 00:00:00 2001 From: Fisch Date: Thu, 22 Oct 2020 23:00:33 +0200 Subject: [PATCH] reimplement mhz19 read function and add delay between cmd send and response reading --- src/main.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index ee4785e..27f3606 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -129,6 +129,8 @@ struct sensordata MHZ19 mhz19; bool mhz19_ready=false; int value_co2=-1; //[ppm] + + int mhz19_readValue_reimplemented(Stream *_streamRef, MHZ19 *_mhz19Ref); //declare function #endif // data/homie/config.json hochladen mit platformio run --target uploadfs @@ -517,8 +519,9 @@ void loop_MHZ19() bool _changed=false; if (millis() >= (d.lastreadtime+d.readdelay)) { mhz19_ready=mhz19.isReady(); - value_co2=mhz19.readValue(); //[ppm] - //Homie.getLogger() << "co2 " << ": " << value_co2 << " status=" << mhz19_ready << endl; + //value_co2=mhz19.readValue(); //[ppm] + value_co2=mhz19_readValue_reimplemented(&mhz19_swSerial, &mhz19); //[ppm] reimplemented function to fix no response issue + Homie.getLogger() << "read co2 " << ": " << value_co2 << " status=" << mhz19_ready << endl; if (fabs(d.lastsentvalue-value_co2)>=d.minchange){ _changed=true; } @@ -628,4 +631,44 @@ int get_lux(const unsigned int* _in, const unsigned int* _out, byte size) // interpolate in the right segment for the rest return map(val, _in[pos-1], _in[pos], _out[pos-1], _out[pos]); } +#endif + + +#ifdef SENSOR_MHZ19 +byte mhz19_getCheckSum(byte* packet) { + byte checksum = 0; + for(uint8_t i = 1; i < 8; i++) { + checksum += packet[i]; + } + checksum = 0xff - checksum; + checksum += 1; + return checksum; +} + +int mhz19_readValue_reimplemented(Stream *_streamRef, MHZ19 *_mhz19Ref) { //same function as in mhz19 library from klevytskyi, but with delay between cmd send and response check + byte CMD_READ[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; // Read command + unsigned int co2 = -1; + unsigned char response[9]; + _streamRef->write(CMD_READ, 9); + + unsigned long _startwait=millis(); + while (millis()-_startwait<100) { //wait for mhz19 to send response + //wait + } + + if (_streamRef->available()) { + _streamRef->readBytes(response, 9); + + byte crc = mhz19_getCheckSum(response); + + if (response[0] == 0xFF && response[1] == CMD_READ[2] && response[8] == crc) { + unsigned int responseHigh = (unsigned int) response[2]; + unsigned int responseLow = (unsigned int) response[3]; + unsigned int ppm = (256*responseHigh) + responseLow; + co2 = ppm; + } + } + + return co2; +} #endif \ No newline at end of file