82 lines
1.7 KiB
C++
82 lines
1.7 KiB
C++
#ifndef DHT22_H
|
|
#define DHT22_H
|
|
|
|
#include "DHT_U.h"
|
|
#include "humidityRelative.h"
|
|
#include "mqtt.h"
|
|
|
|
class DHT22Sensor {
|
|
|
|
int pin;
|
|
|
|
DHT_Unified dht;
|
|
|
|
unsigned long last = 0UL;
|
|
|
|
double temperature = NAN;
|
|
|
|
double relative = NAN;
|
|
|
|
double absolute = NAN;
|
|
|
|
public:
|
|
|
|
const String name;
|
|
|
|
unsigned long intervalMs;
|
|
|
|
explicit DHT22Sensor(String name, const int pin, const unsigned long intervalMs = 5000) : pin(pin), dht(pin, DHT22), name(std::move(name)), intervalMs(intervalMs) {
|
|
//
|
|
}
|
|
|
|
void setup() {
|
|
dht.begin();
|
|
}
|
|
|
|
void loop() {
|
|
const auto now = max(1UL, millis());
|
|
if (now - last >= intervalMs) {
|
|
sensors_event_t event;
|
|
|
|
dht.temperature().getEvent(&event);
|
|
temperature = event.temperature;
|
|
if (isnan(temperature)) {
|
|
absolute = NAN;
|
|
Log.error("Error reading temperature!");
|
|
} else {
|
|
mqttPublishValue(name + "/temperature", temperature, "TEMPERATURE_C");
|
|
}
|
|
|
|
dht.humidity().getEvent(&event);
|
|
relative = event.relative_humidity;
|
|
if (isnan(relative)) {
|
|
absolute = NAN;
|
|
Log.error("Error reading humidity!");
|
|
} else {
|
|
mqttPublishValue(name + "/humidity/relative", relative, "HUMIDITY_RELATIVE_PERCENT");
|
|
if (!isnan(temperature)) {
|
|
absolute = calculateHumidityAbsolute(temperature, relative);
|
|
mqttPublishValue(name + "/humidity/absolute", absolute, "HUMIDITY_ABSOLUTE_GM3");
|
|
}
|
|
}
|
|
|
|
last = now;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] double getTemperature() const {
|
|
return temperature;
|
|
}
|
|
|
|
[[nodiscard]] double getRelative() const {
|
|
return relative;
|
|
}
|
|
|
|
[[nodiscard]] double getAbsolute() const {
|
|
return absolute;
|
|
}
|
|
|
|
};
|
|
|
|
#endif
|