#include "esphome.h" #define DS75_ADDR 0b1001000 class Ds75Sensor : public PollingComponent, public Sensor { public: Ds75Sensor() : PollingComponent(60000) {} float get_setup_priority() const override { return esphome::setup_priority::DATA; } void setup() override { uint8_t err = 0; // ... and set up 12-bit conversion. Wire.beginTransmission(DS75_ADDR); Wire.write((uint8_t)0b00000001); // Configuration pointer byte. Wire.write((uint8_t)0b01100000); // Configuration value. err = Wire.endTransmission(); if (err) { ESP_LOGD("error", "Could not configure DS75 resolution!"); } Wire.beginTransmission(DS75_ADDR); Wire.write((uint8_t)0b00000000); // Temperature pointer byte. err = Wire.endTransmission(); if (err) { ESP_LOGD("error", "Could not configure DS75 for reads!"); } } void update() override { Wire.requestFrom(DS75_ADDR, 2); uint8_t i = 0; while (true) { if (Wire.available() >= 2) break; if (i++ == 250) { return; } delay(6); } // Union helps us cast the raw bits read from the Wire into the 16 bit // twos-complement value. union ds75_reading { int16_t val; uint8_t buf[2]; }; ds75_reading r; r.buf[1] = Wire.read(); // MS byte, whole part. r.buf[0] = Wire.read(); // LS byte, fractional part. // Raw value (after shifting out the four unused LSBs) divided into float: // 12 bit reading minus 8 bit whole part leaves 4 bit fractional part. float deg_c = (float)(r.val>>4) / (float)(1<<4); ESP_LOGD("ds75", "Got temperature=%.1f°C", deg_c); publish_state(deg_c); } };