Created
October 19, 2012 16:05
-
-
Save Crenshinibon/3919048 to your computer and use it in GitHub Desktop.
Debouncing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//arbitrary number to signal that a | |
//key is not bouncing | |
const uint8_t NOT_BOUNCING = 20; | |
//how many ms a key is expected to bounce | |
const uint8_t BOUNCE_TIME = 10; | |
//how many bouncing keys can be handled | |
//in parallel | |
const uint8_t MAX_BOUNCING = 5; | |
//the index where the last bouncing key | |
//is stored in the below array | |
uint8_t bounceIndex = 0; | |
//an array to store the bounce times | |
unsigned long bounceTimers[MAX_BOUNCING]; | |
struct Key { | |
byte id; | |
boolean pressed; | |
uint8_t bounceKey; | |
Key(byte id) : id(id), pressed(false), bounceKey(NOT_BOUNCING) {}; | |
}; | |
boolean toggleKey(struct Key *key) { | |
key->bounceKey = checkStillBouncing(key->bounceKey); | |
if(key->bounceKey == NOT_BOUNCING){ | |
key->bounceKey = debounceKey(); | |
key->pressed ? key->pressed = false : key->pressed = true; | |
return true; | |
} | |
return false; | |
} | |
uint8_t checkStillBouncing(uint8_t bounceKey){ | |
//check if the key is actually bouncing | |
if(bounceKey == NOT_BOUNCING) return NOT_BOUNCING; | |
//check if the bounce time is over | |
if(millis() - bounceTimers[bounceKey] > BOUNCE_TIME) return NOT_BOUNCING; | |
//else return the index of the bouncing counter | |
return bounceKey; | |
} | |
uint8_t debounceKey(){ | |
//get the next available index | |
//in the bounceTimers array | |
//or wrap around | |
(bounceIndex + 1) == MAX_BOUNCING ? bounceIndex = 0 : bounceIndex++; | |
//store the current time stamp | |
bounceTimers[bounceIndex] = millis(); | |
return bounceIndex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment