Mamecontroller/joystick device wrapper library

Dependencies:   USBDevice mbed

DebounceIn.h

Committer:
uswickra
Date:
2014-12-10
Revision:
4:4f6e38b6c07e
Parent:
2:018f204f6037

File content as of revision 4:4f6e38b6c07e:

#ifndef DEBOUNCEIN_H
#define DEBOUNCEIN_H
#include "mbed.h"

class DebounceIn : public DigitalIn {
    public:
    
        /** set_debounce_us
         *
         * Sets the debounce sample period time in microseconds, default is 1000 (1ms)
         *
         * @param int i The debounce sample period time to set.
         */        
        void set_debounce_us(int i) { _ticker.attach_us(this, &DebounceIn::_callback, i); }
        
        /** set_samples
         *
         * Defines the number of samples before switching the shadow 
         * definition of the pin. 
         *
         * @param int i The number of samples.
         */        
        void set_samples(int i) { _samples = i; }
        
        /** read
         *
         * Read the value of the debounced pin.
         */
        int read(void) { return _shadow; }
        
#ifdef MBED_OPERATORS
        /** operator int()
         *
         * Read the value of the debounced pin.
         */
        operator int() { return read(); }
#endif  
 
        /** Constructor
         * 
         * @param PinName pin The pin to assign as an input.
         */
        DebounceIn(PinName pin) : DigitalIn(pin) { _counter = 0; _samples = 10; set_debounce_us(1000); };
        
    protected:
        void _callback(void) { 
            if (DigitalIn::read()) { 
                if (_counter < _samples) _counter++; 
                if (_counter == _samples) _shadow = 1; 
            }
            else { 
                if (_counter > 0) _counter--; 
                if (_counter == 0) _shadow = 0; 
            }
        }
        
        Ticker _ticker;
        int    _shadow;
        int    _counter;
        int    _samples;
};
#endif