Debaunced Input like InterruptIn.
Dependents: LcdClock idd_hw2_martincowell_bicyclehid IDD_FALL15_HW2_JMARQUIS_Keypadentry
Diff: DebouncedEdgeIn.cpp
- Revision:
- 0:471239ea932b
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/DebouncedEdgeIn.cpp Sat Feb 22 23:55:10 2014 +0000 @@ -0,0 +1,78 @@ +#include "DebouncedEdgeIn.h" +#include "mbed.h" + +/* + * Constructor + */ +DebouncedEdgeIn::DebouncedEdgeIn(PinName in) + : _in(in), + _ticker(), + _rise(), + _fall(), + // reset all the flags and counters + _samples(0), + _output(0), + _output_last(0) +{ + // Attach ticker + _ticker.attach(this, &DebouncedEdgeIn::_sample, 0.005); +} + +DebouncedEdgeIn::~DebouncedEdgeIn() { + _ticker.detach(); +} + +void DebouncedEdgeIn::rise(void (*fptr)(void)) +{ + _rise.attach(fptr); +} + +void DebouncedEdgeIn::fall(void (*fptr)(void)) +{ + _fall.attach(fptr); +} + +void DebouncedEdgeIn::mode(PinMode pull) { + _in.mode(pull); +} + +// return the debounced status +int DebouncedEdgeIn::read(void) +{ + return(_output); +} + +// shorthand for read() +DebouncedEdgeIn::operator int() +{ + return read(); +} + +void DebouncedEdgeIn::_sample(void) +{ + // take a sample + _samples = _samples >> 1; // shift left + + 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)) { + _rise.call(); + } + // Falling edge detection + else if ((_output == 0) && (_output_last == 1)) { + _fall.call(); + } + + // update the output + _output_last = _output; +}