#include #include #include #include #include #include #include float ds2438_convert_voltage(const struct owaddr *addr) { unsigned char buf[9]; ow_matchrom(addr); ow_writecommand(DS2438_CONV_V); usleep(10000); if (!ds2438_readsp(addr, 0, buf)) return NAN; return (((int)buf[4] << 8) | buf[3]) * 0.01f; } /* Public functions */ bool ds2438_readsp(const struct owaddr *addr, int page, unsigned char *buf) { // Read 8-byte stratchpad page and verifies CRC. Returns false on failure. ow_matchrom(addr); ow_writecommand(DS2438_RECALL); ow_writecommand(page); ow_matchrom(addr); ow_writecommand(DS2438_READSP); ow_writecommand(page); ow_readbytes(buf, 9); return ow_crc(buf, 9) == 0; } bool ds2438_writesp(const struct owaddr *addr, int page, const unsigned char *buf) { // Write 8-byte stratchpad page and verify. Returns false on failure. ow_matchrom(addr); ow_writecommand(DS2438_WRITESP); ow_writecommand(page); ow_writebytes(buf, 8); unsigned char verifybuf[8]; return (ds2438_readsp(addr, page, verifybuf) && memcmp(buf, verifybuf, 8) == 0); } bool ds2438_config(const struct owaddr *addr, unsigned char config) { // Write and verify just one byte of the first page. ow_matchrom(addr); ow_writecommand(DS2438_WRITESP); ow_writecommand(0); ow_writecommand(config); unsigned char buf; ow_matchrom(addr); ow_writecommand(DS2438_READSP); ow_writecommand(0); ow_readbytes(&buf, 1); return buf == config; } float ds2438_temperature(const struct owaddr *addr) { unsigned char buf[9]; ow_matchrom(addr); ow_writecommand(DS2438_CONV_T); usleep(10000); if (!ds2438_readsp(addr, 0, buf)) return NAN; float result; result = (int16_t)((buf[2] << 8) | buf[1]) / 256.0f; return result; } float ds2438_humidity(const struct owaddr *addr) { float vdd, vout, temperature, rh; if (!ds2438_config(addr, DS2438_CONF_AD)) return NAN; vdd = ds2438_convert_voltage(addr); if (!ds2438_config(addr, 0)) return NAN; vout = ds2438_convert_voltage(addr); temperature = ds2438_temperature(addr); // Sensor RH rh = (vout/vdd - 0.16f) / 0.0062f; // Temperature compensation rh = rh / (1.0546f - 0.00216f * temperature); return rh; }