reimplement mhz19 read function and add delay between cmd send and response reading

This commit is contained in:
interfisch 2020-10-22 23:00:33 +02:00
parent 5acd91bf34
commit 0c6306e8d6
1 changed files with 45 additions and 2 deletions

View File

@ -129,6 +129,8 @@ struct sensordata
MHZ19 mhz19; MHZ19 mhz19;
bool mhz19_ready=false; bool mhz19_ready=false;
int value_co2=-1; //[ppm] int value_co2=-1; //[ppm]
int mhz19_readValue_reimplemented(Stream *_streamRef, MHZ19 *_mhz19Ref); //declare function
#endif #endif
// data/homie/config.json hochladen mit platformio run --target uploadfs // data/homie/config.json hochladen mit platformio run --target uploadfs
@ -517,8 +519,9 @@ void loop_MHZ19()
bool _changed=false; bool _changed=false;
if (millis() >= (d.lastreadtime+d.readdelay)) { if (millis() >= (d.lastreadtime+d.readdelay)) {
mhz19_ready=mhz19.isReady(); mhz19_ready=mhz19.isReady();
value_co2=mhz19.readValue(); //[ppm] //value_co2=mhz19.readValue(); //[ppm]
//Homie.getLogger() << "co2 " << ": " << value_co2 << " status=" << mhz19_ready << endl; 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){ if (fabs(d.lastsentvalue-value_co2)>=d.minchange){
_changed=true; _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 // interpolate in the right segment for the rest
return map(val, _in[pos-1], _in[pos], _out[pos-1], _out[pos]); 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 #endif