summaryrefslogtreecommitdiff
path: root/platformio/temphum/src/temphum.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'platformio/temphum/src/temphum.cpp')
-rw-r--r--platformio/temphum/src/temphum.cpp73
1 files changed, 45 insertions, 28 deletions
diff --git a/platformio/temphum/src/temphum.cpp b/platformio/temphum/src/temphum.cpp
index 9fcc2cc..164f01e 100644
--- a/platformio/temphum/src/temphum.cpp
+++ b/platformio/temphum/src/temphum.cpp
@@ -1,14 +1,12 @@
#ifndef CONFIG_TARGET_ESP01
#include <Arduino.h>
#endif
-
+#include <homekit/logging.h>
#include "temphum.h"
namespace homekit::temphum {
-static const int addr = 0x40;
-
-void setup() {
+void BaseSensor::setup() const {
#ifndef CONFIG_TARGET_ESP01
pinMode(CONFIG_SDA_GPIO, OUTPUT);
pinMode(CONFIG_SCL_GPIO, OUTPUT);
@@ -17,43 +15,62 @@ void setup() {
#else
Wire.begin();
#endif
-
- Wire.beginTransmission(addr);
- Wire.write(0xfe);
- Wire.endTransmission();
-
- delay(500);
}
-struct data read() {
- // Request temperature measurement from the Si7021 sensor
- Wire.beginTransmission(addr);
- Wire.write(0xF3); // command to measure temperature
+void BaseSensor::writeCommand(int reg) const {
+ Wire.beginTransmission(dev_addr);
+ Wire.write(reg);
Wire.endTransmission();
-
delay(500); // wait for the measurement to be ready
+}
- // Read the temperature measurement from the Si7021 sensor
- Wire.requestFrom(addr, 2);
+SensorData Si7021::read() {
+ writeCommand(0xf3); // command to measure temperature
+ Wire.requestFrom(dev_addr, 2);
uint16_t temp_raw = Wire.read() << 8 | Wire.read();
double temperature = ((175.72 * temp_raw) / 65536.0) - 46.85;
- // Request humidity measurement from the Si7021 sensor
- Wire.beginTransmission(addr);
- Wire.write(0xF5); // command to measure humidity
- Wire.endTransmission();
-
- delay(500); // wait for the measurement to be ready
-
- // Read the humidity measurement from the Si7021 sensor
- Wire.requestFrom(addr, 2);
+ writeCommand(0xf5); // command to measure humidity
+ Wire.requestFrom(dev_addr, 2);
uint16_t hum_raw = Wire.read() << 8 | Wire.read();
double humidity = ((125.0 * hum_raw) / 65536.0) - 6.0;
return {
- .temp = temperature,
- .rh = humidity
+ .temp = temperature,
+ .rh = humidity
};
}
+SensorData DHT12::read() {
+ SensorData sd;
+ byte raw[5];
+
+ writeCommand(0);
+ Wire.requestFrom(dev_addr, 5);
+
+ if (Wire.available() < 5) {
+ PRINTLN("DHT12: could not read 5 bytes");
+ goto end;
+ }
+
+ // Parse the received data
+ for (uint8_t i = 0; i < 5; i++)
+ raw[i] = Wire.read();
+
+ if (((raw[0] + raw[1] + raw[2] + raw[3]) & 0xff) != raw[4]) {
+ PRINTLN("DHT12: checksum error");
+ goto end;
+ }
+
+ // Calculate temperature and humidity values
+ sd.temp = raw[2] + (raw[3] & 0x7f) * 0.1;
+ if (raw[3] & 0x80)
+ sd.temp *= -1;
+
+ sd.rh = raw[0] + raw[1] * 0.1;
+
+end:
+ return sd;
+}
+
} \ No newline at end of file