sensoresp/include/sensor_bh1750.cpp

66 lines
1.7 KiB
C++

//Connect SCL to D1, SDA to D2, GND and 3v3
#include "sensor_bh1750.h"
Sensor_BH1750::Sensor_BH1750()
{
bh1750 = new BH1750(0x23); //0x23 if addr connected to ground (=pin open), 0x5c if addr pulled high
}
void Sensor_BH1750::init() //Things to be done during setup()
{
Serial.println("initializing bh1750");
Wire.begin();
if (bh1750->begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
Serial.println(F("BH1750 Advanced begin"));
init_ok=true;
} else {
Serial.println(F("Error initialising BH1750"));
}
bh1750->readLightLevel(); //make first reading, could be 0
}
//Also called during setup()
void Sensor_BH1750::setSettings(float minchange, unsigned long senddelaymax, unsigned long readdelay)
{
data.minchange=minchange;
data.senddelaymax=senddelaymax;
data.readdelay=readdelay;
}
//Called during setup
void Sensor_BH1750::advertise(HomieNode& p_sensorNode)
{
sensorNode = &p_sensorNode;
sensorNode->advertise("light");
}
void Sensor_BH1750::sensorloop()
{
if (init_ok) {
sensordata &d=data;
bool _changed=false;
if (millis() >= (d.lastreadtime+d.readdelay)) {
d.value = bh1750->readLightLevel(); // [lux]
if (fabs(d.lastsentvalue-d.value)>=d.minchange){
_changed=true;
}
d.lastreadtime=millis();
}
if (_changed || millis() >= (d.lastsent+d.senddelaymax)) {
Serial.print("Sending BH1750. reason=");
if (_changed) Serial.println("change"); else Serial.println("time");
Homie.getLogger() << "light " << ": " << d.value << endl;
sensorNode->setProperty("light").send(String(d.value));
d.lastsentvalue=d.value;
d.lastsent=millis();
}
}
}