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

Dependents:   PID_ENCODER

DebouncedIn.cpp

Committer:
mr63
Date:
2013-08-16
Revision:
0:323110faffe5

File content as of revision 0:323110faffe5:

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

#define CHECK_MSEC 5 // Read hardware every 5 msec 
#define PRESS_MSEC 100 // Stable time before registering pressed 
#define RELEASE_MSEC 100 // Stable time before registering released
 

bool DebounceKeyPress = false;
 /*v
  * Constructor
  */
 DebouncedIn::DebouncedIn(PinName pin): _pin(pin)
 {    
	  _pin.mode(PullDown);
    _poll.attach(this, &DebouncedIn::CheckState, 0.005);     
 }
 
 bool DebouncedIn::get()
 {
	 return(DebounceKeyPress);
 }
 
 bool DebouncedIn::get_pin()
 {
	 return(_pin);
 }
 
 
 void DebouncedIn::CheckState()
 {
	 static int Count = RELEASE_MSEC / CHECK_MSEC;
	 bool RawState = DebouncedIn::get_pin();
	 if(RawState==DebounceKeyPress)
	 {
		 if(DebounceKeyPress)
			Count = RELEASE_MSEC / CHECK_MSEC;
		 else
			Count = PRESS_MSEC / CHECK_MSEC; 
	 }
	 else
	 {
		 if(--Count == 0)
		 {
			 DebounceKeyPress = RawState;
			 if(DebounceKeyPress)
				Count = RELEASE_MSEC / CHECK_MSEC;
			 else
				Count = PRESS_MSEC / CHECK_MSEC; 
				 
		 }
	 }
	 
 }