#include <Arduino.h>
#include <Streaming.h>
Print &cout = Serial;
//////////////////////////////////////////////////
// Definitions
//////////////////////////////////////////////////
//
// Moving average
//
template <const size_t BUFFERSIZE = 2> class AnalogFilter {
static_assert(BUFFERSIZE > 0 && BUFFERSIZE < 256, "The buffer size must be between 2 and 255 bytes. ");
public:
constexpr size_t bufferSize() { return BUFFERSIZE; }
uint16_t &operator[](size_t idx) { return buffer[idx]; }
uint16_t average(uint16_t);
private:
uint16_t buffer[BUFFERSIZE] {0};
uint8_t bufferIndex {0};
uint32_t total {0};
};
template <const size_t BUFFERSIZE> uint16_t AnalogFilter<BUFFERSIZE>::average(uint16_t reading) {
// Perform average on sensor readings
total = total - buffer[bufferIndex]; // subtract the last reading:
buffer[bufferIndex] = reading; // store adc value
total = total + buffer[bufferIndex]; // add value to total:
bufferIndex = ((BUFFERSIZE - 1) > bufferIndex) ? bufferIndex + 1 : 0;
// calculate and return the average (rounded):
return static_cast<uint16_t>(((total * 10) / BUFFERSIZE + 5) / 10);
}
//////////////////////////////////////////////////
// Global constants and variables
//////////////////////////////////////////////////
constexpr byte ANALOG_READ_PIN {A0};
AnalogFilter<16> aFilter;
//////////////////////////////////////////////////
// Functions forward declaration(s)
//////////////////////////////////////////////////
void setup() {
Serial.begin(115200);
}
void loop() {
uint16_t result= aFilter.average(analogRead(ANALOG_READ_PIN));
cout << result << F(" Buffer at pos 3 ") << aFilter[2] << endl;
delay(500);
}