Advertisement
Blue_595

Keypad scanner with debounce

Jul 10th, 2021
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Example: 4x4 matrix, rows on D2-D5, columns on D6-D9
  2. const int NUM_ROWS = 4;
  3. const int ROW_PINS[] = {2, 3, 4, 5};
  4. const int NUM_COLS = 4;
  5. const int COL_PINS[] = {6, 7, 8, 9};
  6.  
  7. // Must be volatile since its values aren't guaranteed to change
  8. volatile bool buttons[NUM_ROWS * NUM_COLS];
  9. bool debounce[NUM_ROWS * NUM_COLS];
  10.  
  11. volatile char buf[8]; // Used to send back keycodes
  12.  
  13. void setup() {
  14.    
  15.     Serial.begin(9600);
  16.    
  17.     // Make all row pins initially inputs, but also set them low
  18.     // A row will be pulled low by setting its pin to an output
  19.     for (int i = 0; i < NUM_ROWS; i++) {
  20.         pinMode(ROW_PINS[i], INPUT);
  21.         digitalWrite(ROW_PINS[i], LOW);
  22.     }
  23.    
  24.     // Make all column pins inputs with pullups
  25.     for (int i = 0; i < NUM_COLS; i++) {
  26.         pinMode(COL_PINS[i], INPUT);
  27.     }
  28.    
  29. }
  30.  
  31. void loop() {
  32.     pollKeys();
  33.    
  34.     // Example: Far top-left button
  35.     if (keyPresed(0)) {
  36.         Serial.println("Hello, world!");
  37.     }
  38.    
  39.     delay(20);
  40. }
  41.  
  42. // Broken off into its own function, so loop() isn't as messy
  43. // This is especially important with more complex programs
  44. void pollKeys() {
  45.     for (int i = 0; i < NUM_ROWS; i++) {
  46.         pinMode(ROW_PINS[i], OUTPUT);
  47.         for (int j = 0; j < NUM_COLS; j++) {
  48.             int k = i * NUM_COLS + j;
  49.             debounce[k] = buttons[k];
  50.             buttons[k] = !digitalRead(COL_PINS[j]);
  51.         }
  52.         pinMode(ROW_PINS[i], INPUT);
  53.     }
  54. }
  55.  
  56. // Read the state of a key using the debounce array
  57. bool keyPressed(int i) {
  58.     return buttons[i] && !debounce[i];
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement