view Potentiometer.cpp @ 6:4e32bc18a7f7 default tip

adjusted jitter threshold, added ignore heuristic
author ark
date 2017-07-03 00:24 +0200
parents ea44b28e12ab
children
line wrap: on
line source

#include "Arduino.h"
#include "Potentiometer.h"

/**
    see Potentiometer.h for description.
*/
    
Potentiometer::Potentiometer() {}

void Potentiometer::setup(byte pin) {
    this->pin = pin;
    pinMode(this->pin, INPUT);
    this->isStopped = false;
    this->sum = 0.0;
    this->avg = 0.0;
    this->num = 0;
}

void Potentiometer::update() {
    int v = analogRead(this->pin);
    // if value is within jitter threshold of current value, add to average
    int diff = abs(this->value - v);
    if(this->num == 0 || diff <= Potentiometer::JITTER_THRESHOLD) {
        if(this->num == Potentiometer::MAX_SAMPLES) {
            this->sum -= this->avg;
            this->num--;
            this->isStopped = true;
        }
        this->sum += v;
        this->num++;
        this->avg = this->sum/this->num;
        this->value = (int)(this->avg+.5);
        this->ignore = false;
    }
    // otherwise
    else {
        // ignore one value above jitter
        if(!this->ignore) {
            this->ignore = true;
        }
        // otherwise, if already ignored one spike, reset average
        else {
            this->value = v;
            this->sum = v;
            this->avg = v;
            this->num = 1;
            this->isStopped = false;
            this->ignore = false;
        }
    }
    #ifdef DEBUG
    Serial.print("pin=");
    Serial.print(pin);
    Serial.print(", sum=");
    Serial.print(sum);
    Serial.print(", num=");
    Serial.print(num);
    Serial.print(", avg=");
    Serial.print(avg);
    Serial.print(", v=");
    Serial.print(v);
    Serial.print(", diff=");
    Serial.print(diff);
    Serial.print(", ignore=");
    Serial.print(ignore);
    Serial.print(", isStopped=");
    Serial.print(this->isStopped);
    Serial.println("");
    #endif
}


void Potentiometer::update(unsigned long ms) {
    this->update();
}