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

92 lines
1.4 KiB
C++
Raw Normal View History

//
// FILE: AnalogPin.cpp
// AUTHOR: Rob Tillaart
2022-10-28 15:33:10 -04:00
// VERSION: 0.2.7
2020-11-27 05:10:47 -05:00
// DATE: 2013-09-09
// PURPOSE: wrapper for analogRead with smoothing and noise filtering
//
2022-10-28 15:33:10 -04:00
// HISTORY: see changelog
2021-10-17 13:20:48 -04:00
#include "AnalogPin.h"
2021-10-17 13:20:48 -04:00
2015-03-06 08:26:17 -05:00
AnalogPin::AnalogPin(const uint8_t pin)
{
2021-01-29 06:31:58 -05:00
_pin = pin;
_prescale = 7;
_alpha = 0;
_noise = 0;
2021-10-17 13:20:48 -04:00
_rawRead();
2021-01-29 06:31:58 -05:00
_prevValue = _value;
}
2021-10-17 13:20:48 -04:00
void AnalogPin::setPrescaler(const uint8_t prescale)
{
2022-10-28 15:33:10 -04:00
_prescale = prescale;
if (_prescale < 2) _prescale = 2;
else if (_prescale > 7) _prescale = 7;
2021-10-17 13:20:48 -04:00
};
void AnalogPin::setSmoothWeight(const uint8_t alpha)
{
_alpha = alpha;
if (_alpha > 31) _alpha = 31;
};
2020-11-27 05:10:47 -05:00
int AnalogPin::read(const bool twice)
{
2021-10-17 13:20:48 -04:00
if (twice) _rawRead();
_rawRead();
2021-01-29 06:31:58 -05:00
if ( (_noise == 0) || (((_value - _prevValue) & 0x7FFF) > _noise) )
{
_prevValue = _value;
}
return _prevValue;
}
2021-10-17 13:20:48 -04:00
2020-11-27 05:10:47 -05:00
int AnalogPin::readSmoothed()
{
2021-10-17 13:20:48 -04:00
_rawRead();
2021-01-29 06:31:58 -05:00
if (_alpha > 0)
{
_value = _value + (_alpha * (_prevValue - _value)) / 32;
}
_prevValue = _value;
return _value;
}
2021-10-17 13:20:48 -04:00
void AnalogPin::_rawRead()
{
2020-11-27 05:10:47 -05:00
#if defined(ARDUINO_ARCH_AVR)
2022-10-28 15:33:10 -04:00
// remember old register value
2021-01-29 06:31:58 -05:00
uint8_t ADCSRA_TMP = ADCSRA;
ADCSRA = (ADCSRA | 0x07) & (0xF8 | _prescale);
2020-11-27 05:10:47 -05:00
#elif defined(ARDUINO_ARCH_SAM)
2021-01-29 06:31:58 -05:00
2020-11-27 05:10:47 -05:00
#else
2021-01-29 06:31:58 -05:00
#endif
_value = analogRead(_pin);
2020-11-27 05:10:47 -05:00
#if defined(ARDUINO_ARCH_AVR)
2022-10-28 15:33:10 -04:00
// restore register
2021-01-29 06:31:58 -05:00
ADCSRA = ADCSRA_TMP;
2020-11-27 05:10:47 -05:00
#elif defined(ARDUINO_ARCH_SAM)
2021-01-29 06:31:58 -05:00
2020-11-27 05:10:47 -05:00
#else
2021-01-29 06:31:58 -05:00
#endif
}
2020-11-27 05:10:47 -05:00
2021-12-12 09:57:24 -05:00
2020-11-27 05:10:47 -05:00
// -- END OF FILE --
2021-12-12 09:57:24 -05:00