sensoresp/include/sensor_ml8511.cpp

80 lines
2.2 KiB
C++
Raw Normal View History

//ML8511 UV Sensor outputs an analog voltage. ML8511PIN needs to be an ADC pin
2021-11-04 17:47:43 +00:00
//value as uvIntensity (mW/cm^2)
#include "sensor_ml8511.h"
Sensor_ML8511::Sensor_ML8511(int pin)
{
ml8511pin=pin;
}
void Sensor_ML8511::init() //Things to be done during setup()
{
Serial.println("initializing ml8511");
pinMode(ml8511pin, INPUT);
analogRead(ml8511pin); //first read adc. just to avoid problems
init_ok=true;
}
//Also called during setup()
void Sensor_ML8511::setSettings(float minchange, unsigned long senddelaymax, unsigned long readdelay)
{
data.minchange=minchange;
data.senddelaymax=senddelaymax;
data.readdelay=readdelay;
}
//Called during setup
void Sensor_ML8511::advertise(HomieNode& p_sensorNode)
{
sensorNode = &p_sensorNode;
sensorNode->advertise("uv");
}
void Sensor_ML8511::sensorloop()
{
if (init_ok) {
sensordata &d=data;
bool _changed=false;
if (millis() >= (d.lastreadtime+d.readdelay)) {
Serial.print("analogRead="); Serial.println(analogRead(ml8511pin));
d.value = getUV_ML8511(ml8511pin); //uvIntensity (mW/cm^2)
if (fabs(d.lastsentvalue-d.value)>=d.minchange){
_changed=true;
}
d.lastreadtime=millis();
}
if (_changed || millis() >= (d.lastsent+d.senddelaymax)) {
Serial.print("Sending uv ML8511. reason=");
if (_changed) Serial.println("change"); else Serial.println("time");
Homie.getLogger() << "uv " << ": " << d.value << endl;
sensorNode->setProperty("uv").send(String(d.value));
d.lastsentvalue=d.value;
d.lastsent=millis();
}
}
}
float Sensor_ML8511::getUV_ML8511(int pin) {
float uvadc=0;
#define UVADCSAMPLES 32
for (uint16_t _s=0;_s<UVADCSAMPLES;_s++) {
uvadc += 3.06 / 1023 * analogRead(pin) ; //assumes 1023 = 3.069V (10-bit adc on esp8266)
}
uvadc=uvadc/UVADCSAMPLES; //average
return max(mapfloat(uvadc, 0.99, 2.8, 0.0, 15.0), 0.0F); //uvIntensity (mW/cm^2)
}
//The Arduino Map function but for floats
//From: http://forum.arduino.cc/index.php?topic=3922.0
float Sensor_ML8511::mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}