view TiltSwitch.cpp @ 0:f2ccfa3f20ad default tip

more complete version from magic rattle
author ark
date 2017-06-28 00:48 +0200
parents
children
line wrap: on
line source

#include "TiltSwitch.h"

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


void TiltSwitch::setup(byte pin, bool pu, float secs) {
    this->pin = pin;
    this->isPullup = pu;
    this->dus = 1000000*secs;
    pinMode(this->pin, this->isPullup?INPUT_PULLUP:INPUT);
    this->isOn = this->readState();
    this->act = 0.0;
}


void TiltSwitch::update(uint32_t us) {
    bool s = this->readState();

    // calculate rate of change per secs seconds
    if(this->isOn != s) {
        this->ref = this->act + 1.0;
        this->refUs = us;
        this->act = this->ref;
    }
    else {
        uint32_t dt = (us - this->refUs);
        if(dt >= this->dus) {
            this->act = 0.0;
            // guard against overflow
            this->refUs = us - this->dus;
        } else {
            this->act = this->ref * ((float)(this->dus-dt)/(float)this->dus);
        }
    }
    this->isOn = s;
    
    // calculate average to determine up/down
    // if collected MAX_SAMPLES already, simulate dropping a sample
    if(this->num == MAX_SAMPLES) {
        this->sum -= this->avg;
        this->num--;
    }
    // add current sample
    this->sum += (s ? 1.0 : 0.0);
    this->num++;
    this->avg = this->sum/this->num;
    // if average is closer to 0 or 1 than 1/MAX_SAMPLES, meaning that it's
    // less than one sample away from the stable bounds, truncate 
    if(this->num == MAX_SAMPLES) {
        float e = 1/(float)MAX_SAMPLES-.001;
        if(this->avg < e) {
            this->avg = 0.0;
            this->sum = 0.0;
        }
        else if(this->avg > 1.0-e) {
            this->avg = 1.0;
            this->sum = 1.0 * MAX_SAMPLES;
        }
    }
}


bool TiltSwitch::readState() {
    bool s = digitalRead(this->pin);
    if(this->isPullup) s = !s;
    return s;
}