GY-63_MS5611/libraries/AnalogUVSensor/AnalogUVSensor.cpp

80 lines
1.5 KiB
C++
Raw Normal View History

2021-09-29 11:06:47 -04:00
//
// FILE: AnalogUVSensor.h
// AUTHOR: Rob Tillaart
2022-10-28 15:40:39 -04:00
// VERSION: 0.1.3
2021-09-29 11:06:47 -04:00
// DATE: 2021-09-25
2022-10-28 15:40:39 -04:00
// PURPOSE: Arduino library for an analogue UV sensor.
2021-09-29 11:06:47 -04:00
//
2022-10-28 15:40:39 -04:00
// HISTORY: see changelog
2021-09-29 11:06:47 -04:00
#include "AnalogUVSensor.h"
AnalogUVSensor::AnalogUVSensor()
{
2022-10-28 15:40:39 -04:00
// defaults from UNO.
2021-09-29 11:06:47 -04:00
_analogPin = 14; // A0
_volts = 5;
_maxADC = 1023;
_powerPin = -1;
_invert = false;
}
void AnalogUVSensor::begin(uint8_t analogPin, float volts, uint16_t maxADC)
{
_analogPin = analogPin;
_volts = volts;
_maxADC = maxADC;
}
float AnalogUVSensor::read(uint8_t times)
{
uint32_t sum = 0;
2021-10-17 15:22:43 -04:00
if (times == 0) times = 1;
2021-09-29 11:06:47 -04:00
for (int i = 0; i < times; i++)
{
sum += analogRead(_analogPin);
}
uint16_t milliVolt = sum * (_volts * 1000.0) / (times * _maxADC);
return mV2index(milliVolt);
}
float AnalogUVSensor::mV2index(uint16_t milliVolt)
{
if (milliVolt < 50) return 0.0;
2022-10-28 15:40:39 -04:00
// linear interpolation between 0..1
2021-09-29 11:06:47 -04:00
if (milliVolt < 227) return 0.0 + (1.0 * milliVolt - 50.0) / (227.0 - 50.0);
2022-10-28 15:40:39 -04:00
// linear interpolation between 1..11
// formula derived with spreadsheet.
2021-10-17 15:22:43 -04:00
if (milliVolt < 1200) return 0.0104865310 * milliVolt - 1.289154988;
return 12;
2021-09-29 11:06:47 -04:00
}
char AnalogUVSensor::index2color(float index)
{
if (index <= 2) return 'G';
if (index <= 5) return 'Y';
if (index <= 7) return 'O';
if (index <= 10) return 'R';
return 'P';
}
void AnalogUVSensor::setPowerPin(uint8_t powerPin, bool invert)
{
_invert = invert;
_powerPin = powerPin;
pinMode(_powerPin, OUTPUT);
switchOn();
}
2021-12-12 11:20:41 -05:00
2021-09-29 11:06:47 -04:00
// -- END OF FILE --