Skip to content
Snippets Groups Projects
Potentiometer.h 1.87 KiB
Newer Older
#ifndef POTENTIOMETER_h
#define POTENTIOMETER_h

class Potentiometer {

  int EMA_S = 0;          //initialization of EMA S
  float EMA_a = 0.6;
  int _previousReading;

  bool _inputFlag = false;
  bool _changeFlag = false;

  unsigned long _previousTimer;
  int _interval = 200;

  void (*_cb)(Potentiometer*, uint8_t, uint8_t); // Callback function

  int _read() {
    int sensorValue = analogRead(_pin);                //read the sensor value using ADC
    EMA_S = (EMA_a*sensorValue) + ((1-EMA_a)*EMA_S);   //run the EMA
    int mappedValue = map(EMA_S, 5, 1023, 0, 100);

    return mappedValue;
  }

  void _setValue(int x) {
    _value = x;
  }

    static const uint8_t kEventStableUpdate = 0;
    static const uint8_t kEventUnstableUpdate = 1;
    Potentiometer(int pin, int id = 99) : _pin(pin), _id(id) {
      pinMode(pin, INPUT);
      EMA_S = analogRead(_pin);  //set EMA S for t=1
      _previousReading = EMA_S;

      _previousTimer = millis();
    };

    void setEventHandler(void(*function)(Potentiometer*, uint8_t, uint8_t)) {
      _cb = function;
    }

    int getValue() {
    }

    int getId() {
      return _id;
    }

    void check() {
      unsigned long timer = millis();
      unsigned long deltaTime = timer - _previousTimer;
      int reading = _read();
      int deltaValue = abs(reading - _value);
      if (reading != _value) {
        _inputFlag = true;
      if (_inputFlag == true && deltaValue > 1) {
        _inputFlag = false;
        _changeFlag = true;
        _previousTimer = timer;
        _setValue(reading);
        _cb(this, kEventUnstableUpdate, getValue());
      }
      if (_changeFlag == true &&  deltaTime > _interval) {
        _changeFlag = false;
        _cb(this, kEventStableUpdate, getValue());
      }