Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example: 4x4 matrix, rows on D2-D5, columns on D6-D9
- const int NUM_ROWS = 4;
- const int ROW_PINS[] = {2, 3, 4, 5};
- const int NUM_COLS = 4;
- const int COL_PINS[] = {6, 7, 8, 9};
- // Must be volatile since its values aren't guaranteed to change
- volatile bool buttons[NUM_ROWS * NUM_COLS];
- bool debounce[NUM_ROWS * NUM_COLS];
- volatile char buf[8]; // Used to send back keycodes
- void setup() {
- Serial.begin(9600);
- // Make all row pins initially inputs, but also set them low
- // A row will be pulled low by setting its pin to an output
- for (int i = 0; i < NUM_ROWS; i++) {
- pinMode(ROW_PINS[i], INPUT);
- digitalWrite(ROW_PINS[i], LOW);
- }
- // Make all column pins inputs with pullups
- for (int i = 0; i < NUM_COLS; i++) {
- pinMode(COL_PINS[i], INPUT);
- }
- }
- void loop() {
- pollKeys();
- // Example: Far top-left button
- if (keyPresed(0)) {
- Serial.println("Hello, world!");
- }
- delay(20);
- }
- // Broken off into its own function, so loop() isn't as messy
- // This is especially important with more complex programs
- void pollKeys() {
- for (int i = 0; i < NUM_ROWS; i++) {
- pinMode(ROW_PINS[i], OUTPUT);
- for (int j = 0; j < NUM_COLS; j++) {
- int k = i * NUM_COLS + j;
- debounce[k] = buttons[k];
- buttons[k] = !digitalRead(COL_PINS[j]);
- }
- pinMode(ROW_PINS[i], INPUT);
- }
- }
- // Read the state of a key using the debounce array
- bool keyPressed(int i) {
- return buttons[i] && !debounce[i];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement