strange-v / MHZ19

Arduino library for MH-Z19/MH-Z19B CO2 sensor
GNU General Public License v3.0
57 stars 12 forks source link

sendCommand failure? #2

Closed holgerlembke closed 6 years ago

holgerlembke commented 6 years ago

I'm not sure whether the sendCommand approach works as intended.

If you do a

while (_hs->available()) { _hs->read(); }

it assumes that the sensor instantly starts to send after sending the command and does it continuously instantly and so fast, that the µC always has data to poll away.

I think a better approach would be to just count the 9 bytes and encapsulate it with a timeout. (I never assume that I get all the data due to all sorts of things that could happen...)

Reason I mention is that I implemented a new function

MHZ19_RESULT MHZ19::rawdataread(byte (*cmd)[9]) {
    memset(*cmd, 0, 9);

    if (_hs)
    {
        _hs->readBytes(*cmd, 9);
    }
    else
    {
        _ss->readBytes(*cmd, 9);
    }

    byte crc = calcCRC(*cmd);

    MHZ19_RESULT _result = MHZ19_RESULT_OK;
    if ((*cmd)[0] != 0xFF)
        _result = MHZ19_RESULT_ERR_FB;
    if ((*cmd)[8] != crc)
        _result = MHZ19_RESULT_ERR_CRC;

    return _result;
}

and this happily reads the returned data from sendCommand.

In the end I think there needs to be some sort of redesign, whether sendCommand eats the returned data or allows to get it via rawdataread. For my simple solution I removed the reading and let sendCommand only do a send.

strange-v commented 6 years ago

The sendCommand method was introduced only for calibration purposes where no response. However, it has to be as general as possible so I'll merge your pull request. Also, I'll refactor the code a bit to save backward compatibility.