This is a debounced version of DigitalIn for Mechanical Switches. It is simplistic, and should be easy to use.

Dependents:   PID_ENCODER

Committer:
mr63
Date:
Fri Aug 16 17:49:32 2013 +0000
Revision:
0:323110faffe5
This is a Debounced version of DigitalIn

Who changed what in which revision?

UserRevisionLine numberNew contents of line
mr63 0:323110faffe5 1 #include "DebouncedIn.h"
mr63 0:323110faffe5 2 #include "mbed.h"
mr63 0:323110faffe5 3
mr63 0:323110faffe5 4 #define CHECK_MSEC 5 // Read hardware every 5 msec
mr63 0:323110faffe5 5 #define PRESS_MSEC 100 // Stable time before registering pressed
mr63 0:323110faffe5 6 #define RELEASE_MSEC 100 // Stable time before registering released
mr63 0:323110faffe5 7
mr63 0:323110faffe5 8
mr63 0:323110faffe5 9 bool DebounceKeyPress = false;
mr63 0:323110faffe5 10 /*v
mr63 0:323110faffe5 11 * Constructor
mr63 0:323110faffe5 12 */
mr63 0:323110faffe5 13 DebouncedIn::DebouncedIn(PinName pin): _pin(pin)
mr63 0:323110faffe5 14 {
mr63 0:323110faffe5 15 _pin.mode(PullDown);
mr63 0:323110faffe5 16 _poll.attach(this, &DebouncedIn::CheckState, 0.005);
mr63 0:323110faffe5 17 }
mr63 0:323110faffe5 18
mr63 0:323110faffe5 19 bool DebouncedIn::get()
mr63 0:323110faffe5 20 {
mr63 0:323110faffe5 21 return(DebounceKeyPress);
mr63 0:323110faffe5 22 }
mr63 0:323110faffe5 23
mr63 0:323110faffe5 24 bool DebouncedIn::get_pin()
mr63 0:323110faffe5 25 {
mr63 0:323110faffe5 26 return(_pin);
mr63 0:323110faffe5 27 }
mr63 0:323110faffe5 28
mr63 0:323110faffe5 29
mr63 0:323110faffe5 30 void DebouncedIn::CheckState()
mr63 0:323110faffe5 31 {
mr63 0:323110faffe5 32 static int Count = RELEASE_MSEC / CHECK_MSEC;
mr63 0:323110faffe5 33 bool RawState = DebouncedIn::get_pin();
mr63 0:323110faffe5 34 if(RawState==DebounceKeyPress)
mr63 0:323110faffe5 35 {
mr63 0:323110faffe5 36 if(DebounceKeyPress)
mr63 0:323110faffe5 37 Count = RELEASE_MSEC / CHECK_MSEC;
mr63 0:323110faffe5 38 else
mr63 0:323110faffe5 39 Count = PRESS_MSEC / CHECK_MSEC;
mr63 0:323110faffe5 40 }
mr63 0:323110faffe5 41 else
mr63 0:323110faffe5 42 {
mr63 0:323110faffe5 43 if(--Count == 0)
mr63 0:323110faffe5 44 {
mr63 0:323110faffe5 45 DebounceKeyPress = RawState;
mr63 0:323110faffe5 46 if(DebounceKeyPress)
mr63 0:323110faffe5 47 Count = RELEASE_MSEC / CHECK_MSEC;
mr63 0:323110faffe5 48 else
mr63 0:323110faffe5 49 Count = PRESS_MSEC / CHECK_MSEC;
mr63 0:323110faffe5 50
mr63 0:323110faffe5 51 }
mr63 0:323110faffe5 52 }
mr63 0:323110faffe5 53
mr63 0:323110faffe5 54 }
mr63 0:323110faffe5 55
mr63 0:323110faffe5 56
mr63 0:323110faffe5 57