sensoresp/include/sensor_htu21d.cpp

105 lines
2.8 KiB
C++

//Connect SCL to D1, SDA to D2, GND and 3v3
#include "sensor_htu21d.h"
#include <Adafruit_HTU21DF.h>
Sensor_HTU21D::Sensor_HTU21D()
{
Adafruit_HTU21DF htu;
}
void Sensor_HTU21D::init() //Things to be done during setup()
{
Serial.println("initializing HTU21D");
if (!htu->begin()) {
Serial.println("#ERROR: HTU21D init fail\n");
}else{
init_ok=true; //stays false if init failed, sensor will not be read in loop
}
}
//Also called during setup()
void Sensor_HTU21D::setSettings_Temperature(float minchange, unsigned long senddelaymax, unsigned long readdelay)
{
data_temperature.minchange=minchange;
data_temperature.senddelaymax=senddelaymax;
data_temperature.readdelay=readdelay;
}
//Also called during setup()
void Sensor_HTU21D::setSettings_Humidity(float minchange, unsigned long senddelaymax, unsigned long readdelay)
{
data_humidity.minchange=minchange;
data_humidity.senddelaymax=senddelaymax;
data_humidity.readdelay=readdelay;
}
//Called during setup
void Sensor_HTU21D::advertise(HomieNode& p_sensorNode)
{
sensorNode = &p_sensorNode;
sensorNode->advertise("temperature_htu");
sensorNode->advertise("humidity_htu");
}
void Sensor_HTU21D::sensorloop()
{
if (init_ok) {
loop_HTU21D_temperature();
loop_HTU21D_humidity();
}
}
void Sensor_HTU21D::loop_HTU21D_temperature()
{
sensordata &d=data_temperature;
bool _changed=false;
if (millis() >= (d.lastreadtime+d.readdelay)) {
d.value = htu->readTemperature();
if (fabs(d.lastsentvalue-d.value)>=d.minchange){
_changed=true;
}
d.lastreadtime=millis();
}
if (_changed || millis() >= (d.lastsent+d.senddelaymax)) {
Serial.print("Sending HTU21D_temperature. reason=");
if (_changed) Serial.println("change"); else Serial.println("time");
if (!(isnan(d.value) == 1)){ //success
sensorNode->setProperty("temperature_htu").send(String(d.value));
Homie.getLogger() << "temperature_htu " << ": " << d.value << endl;
d.lastsentvalue=d.value;
}
d.lastsent=millis();
}
}
void Sensor_HTU21D::loop_HTU21D_humidity()
{
sensordata &d=data_humidity;
bool _changed=false;
if (millis() >= (d.lastreadtime+d.readdelay)) {
d.value = htu->readHumidity();
if (fabs(d.lastsentvalue-d.value)>=d.minchange){
_changed=true;
}
d.lastreadtime=millis();
}
if (_changed || millis() >= (d.lastsent+d.senddelaymax)) {
Serial.print("Sending HTU21D_humidity. reason=");
if (_changed) Serial.println("change"); else Serial.println("time");
if (!(isnan(d.value) == 1)){ //success
sensorNode->setProperty("humidity_htu").send(String(d.value));
Homie.getLogger() << "humidity_htu " << ": " << d.value << endl;
d.lastsentvalue=d.value;
}
d.lastsent=millis();
}
}