Key debouncing with timer
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
#include <keypadc.h> | |
#include <time.h> | |
int main(void) { | |
// Ensure no key is pressed when the program is first opened | |
while(kb_AnyKey()); | |
bool keyPressed = false; | |
// Keep track of an offset for timer stuff | |
clock_t clockOffset = clock(); | |
// Key detection loop | |
while(!kb_IsDown(kb_KeyClear)) { | |
// If no key is pressed, reset timer and variable for keeping track of if a key is held down. | |
if (!kb_AnyKey() && keyPressed) { | |
keyPressed = false; | |
clockOffset = clock(); | |
} | |
// If no key is being held, allow an input | |
// If a key is being held, introduce a small delay between inputs. In this example the delay is | |
// CLOCKS_PER_SECOND / 32, but it can be changed to what feels most natural. | |
if (kb_AnyKey() && (!keyPressed || clock() - clockOffset > CLOCKS_PER_SECOND / 32)) { | |
// Do whatever you want with key inputs here | |
// If this is the first instance of an input after a release (the key has not already been held | |
// down for some time), wait for a longer delay to ensure the user wants to continue holding down | |
// the key and creating more inputs. In this example the delay is CLOCKS_PER_SECOND / 4, but it can | |
// be changed to what feels most natural. | |
if (!keyPressed) { | |
while (clock() - clockOffset < CLOCKS_PER_SECOND / 4 && kb_AnyKey()) { | |
kb_Scan(); | |
} | |
} | |
// Now we know that the user is holding down a key (If not, we'll reset keyPressed back to false | |
// at the beginning of the loop. Reset the timer so we can continue to count the delay between | |
// inputs. | |
keyPressed = true; | |
clockOffset = clock(); | |
} | |
} | |
return 0; | |
} |
Thanks, should be better now :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
should really be using CLOCKS_PER_SECOND rather than magic numbers