Library for debouncing inputs, originally by Andres Mora Bedoya. Updated to include PinMode capability and class documentation.

Fork of DebouncedIn by Andrés Mora Bedoya

DebouncedIn.cpp

Committer:
faucherb94
Date:
2014-10-09
Revision:
3:41d314732786
Parent:
2:261228f701a1
Child:
4:e88ec98d2b7e

File content as of revision 3:41d314732786:

/**
 * DebouncedIn class version 1.0
 * Created by Andres Moya Bedoya, updated by Ben Faucher
 */

#include "DebouncedIn.h"
#include "mbed.h"

DebouncedIn::DebouncedIn(PinName in) 
    : _in(in) {    
        
    // Reset all the flags and counters    
    _samples = 0;
    _output = 0;
    _output_last = 0;
    _rising_flag = 0;
    _falling_flag = 0;
    _state_counter = 0;
    
    // Attach ticker
    _ticker.attach(this, &DebouncedIn::_sample, 0.005);     
}

DebouncedIn::DebouncedIn(PinName in, PinMode mode) 
    : _in(in, mode) {    
        
    // Reset all the flags and counters    
    _samples = 0;
    _output = 0;
    _output_last = 0;
    _rising_flag = 0;
    _falling_flag = 0;
    _state_counter = 0;
    
    // Attach ticker
    _ticker.attach(this, &DebouncedIn::_sample, 0.005);     
}

// Public member functions

int DebouncedIn::read(void) {
    return(_output);
}

DebouncedIn::operator int() {
    return read();
}
 
// return number of rising edges
int DebouncedIn::rising(void) {
    int return_value = _rising_flag; 
    _rising_flag = 0;
    return(return_value);
}
 
// return number of falling edges
int DebouncedIn::falling(void) {
    int return_value = _falling_flag; 
    _falling_flag = 0;
    return(return_value);
}
 
// return number of ticks we've bene steady for
int DebouncedIn::steady(void) {
return(_state_counter);
}

// Private member functions
void DebouncedIn::_sample() {
 
    // take a sample
    _samples = _samples >> 1; // shift right 1 bit
      
    if (_in) {
        _samples |= 0x80;
    }  
      
    // examine the sample window, look for steady state
    if (_samples == 0x00) {
        _output = 0;
    } 
    else if (_samples == 0xFF) {
        _output = 1;
    }
 
 
    // Rising edge detection
    if ((_output == 1) && (_output_last == 0)) {
        _rising_flag++;
        _state_counter = 0;
    }
 
    // Falling edge detection
    else if ((_output == 0) && (_output_last == 1)) {
        _falling_flag++;
        _state_counter = 0;
    }
    
    // steady state
    else {
        _state_counter++;
    }
    
   // update the output
    _output_last = _output;
    
}