A library for debouncing any type of signal. This library does not really have documentation yet and is not really intended for public use.

Dependents:   LineFollowing DeadReckoning

GeneralDebouncer.h

Committer:
DavidEGrayson
Date:
2014-02-24
Revision:
0:22a56daa5d4f

File content as of revision 0:22a56daa5d4f:

#pragma once

#include <mbed.h>

class GeneralDebouncer
{
    public:
    GeneralDebouncer(int32_t maxUpdateIntervalMicroseconds)
      : maxUpdateIntervalMicroseconds(maxUpdateIntervalMicroseconds)
    {
        timer.start();
        //this->maxUpdateIntervalMicroseconds = maxUpdateIntervalMicroseconds;
        reset();
    }
    
    void reset()
    {
        firstReportReceived = false;
        lastReportTimeMicroseconds = 0;
        spanBeginTimeMicroseconds = 0;
        currentState = 0;
    }

    uint32_t getState()
    {
        return currentState;   
    }

    uint32_t getTimeInCurrentStateMicroseconds()
    {
        //if ((time() - lastReportTimeMicroseconds) > maxUpdateIntervalMicroseconds)
        //{
        //    return 0;
        //}        
        return time() - spanBeginTimeMicroseconds;
    }

    void update(uint32_t state)
    {
        uint32_t time = this->time();
        // || (time - lastReportTimeMicroseconds) > maxUpdateIntervalMicroseconds
        if (!firstReportReceived  || state != currentState)
        {
            firstReportReceived = true;
            spanBeginTimeMicroseconds = time;
            currentState = state;
        }        
        lastReportTimeMicroseconds =  time;
    }
    
    private:
    uint32_t time()
    {
        return (uint32_t)timer.read_us();  // Cast int32_t to uint32_t.
    }
    
    private:
    public: // tmphax
    bool firstReportReceived;
    uint32_t const maxUpdateIntervalMicroseconds;
    uint32_t lastReportTimeMicroseconds;
    uint32_t spanBeginTimeMicroseconds;
    uint32_t currentState;
    Timer timer;
};