Skip to content

Instantly share code, notes, and snippets.

@TIny-Hacker
Last active October 2, 2023 13:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Key debouncing with timer
#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;
}
@mateoconlechuga
Copy link

should really be using CLOCKS_PER_SECOND rather than magic numbers

@TIny-Hacker
Copy link
Author

Thanks, should be better now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment