summaryrefslogtreecommitdiff
path: root/platformio/temphum/src/temphum.cpp
blob: 9fcc2cc7a68a1371605437e7e15f899ecfd142cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#ifndef CONFIG_TARGET_ESP01
#include <Arduino.h>
#endif

#include "temphum.h"

namespace homekit::temphum {

static const int addr = 0x40;

void setup() {
#ifndef CONFIG_TARGET_ESP01
    pinMode(CONFIG_SDA_GPIO, OUTPUT);
    pinMode(CONFIG_SCL_GPIO, OUTPUT);

    Wire.begin(CONFIG_SDA_GPIO, CONFIG_SCL_GPIO);
#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
    Wire.endTransmission();

    delay(500); // wait for the measurement to be ready

    // Read the temperature measurement from the Si7021 sensor
    Wire.requestFrom(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);
    uint16_t hum_raw = Wire.read() << 8 | Wire.read();
    double humidity = ((125.0 * hum_raw) / 65536.0) - 6.0;

    return {
        .temp = temperature,
        .rh = humidity
    };
}

}