#include <stdio.h>
#include "pico/stdlib.h"
// Define rows and columns
#define ROWS 4
#define COLS 3
uint row_pins[ROWS] = {2, 3, 4, 5}; // GPIO pins for rows
uint col_pins[COLS] = {6, 7, 8}; // GPIO pins for columns
// Function to initialize GPIOs for matrix keypad
void init_keypad() {
for (int i = 0; i < ROWS; i++) {
gpio_init(row_pins[i]);
gpio_set_dir(row_pins[i], GPIO_OUT);
gpio_put(row_pins[i], 0); // Set all rows to LOW initially
}
for (int i = 0; i < COLS; i++) {
gpio_init(col_pins[i]);
gpio_set_dir(col_pins[i], GPIO_IN);
gpio_pull_down(col_pins[i]); // Pull-down resistors
}
}
// Function to scan keypad and detect button presses
char scan_keypad() {
char keys[ROWS][COLS] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};
for (int r = 0; r < ROWS; r++) {
// Set the current row HIGH
gpio_put(row_pins[r], 1);
// Check each column for a HIGH signal
for (int c = 0; c < COLS; c++) {
if (gpio_get(col_pins[c])) {
// Debounce delay
sleep_ms(10);
if (gpio_get(col_pins[c])) { // Confirm keypress
gpio_put(row_pins[r], 0); // Reset row
return keys[r][c]; // Return detected key
}
}
}
// Reset the current row LOW
gpio_put(row_pins[r], 0);
}
return '\0'; // No key pressed
}
int main() {
stdio_init_all();
init_keypad();
while (true) {
char key = scan_keypad();
if (key != '\0') {
printf("Key Pressed: %c\n", key);
}
sleep_ms(50); // Reduce CPU usage
}
}