/* 1. Include Library
Purpose: The Keypad.h library simplifies the scanning and debouncing of matrix keypads.
Key Features:
Automatically handles key matrix rows and columns.
Provides the getKey() function to detect key presses. */
#include <Keypad.h> //header for keypad commands enabling
/* 2. Keypad Configuration
rows: Number of horizontal lines in the keypad matrix.
cols: Number of vertical lines in the keypad matrix. */
const byte rows = 4; // Four rows
const byte cols = 4; // Four columns
// Defines the mapping of keys on the keypad
char keys [rows][cols] =
{{ '1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}};
/* - rowpin: Specifies which STM32 GPIO pins are connected to the keypad rows.
- colpin: Specifies which STM32 GPIO pins are connected to the keypad columns. */
// Connect keypad ROW1, ROW2, ROW3 and ROW4 to these GPIO pins.
byte rowpin[rows] = {10,11,12,13};
// Connect keypad COL1, COL2, COL3 and COL4 to these GPIO pins.
byte colpin[cols] = {6,7,8,9};
/* 3. Create Keypad Object
- makeKeymap(keys): Converts the keys array into a format usable by the Keypad library.
- Keypad Constructor Parameters:
- The keymap (keys).
- GPIO pins connected to rows (rowpin).
- GPIO pins connected to columns (colpin).
- Dimensions of the keypad matrix (rows, cols). */
Keypad keypad = Keypad( makeKeymap(keys), rowpin, colpin, rows, cols);
/* 4. Setup Function
Serial.begin(9600): Initializes serial communication at a baud rate of 9600.
Serial.println(): Outputs text messages to the serial monitor for user instructions or debugging. */
void setup() {
Serial.begin(9600);
Serial.println("Hello, Welcome to STM32 Nucleo Keypad Interfacing Demo!");
Serial.println("Enter Number or Character:");
}
/* 5. Loop Function
keypad.getKey():
- Continuously scans the keypad for key presses.
- Returns the character of the pressed key (e.g., '1', 'A').
- Returns NO_KEY if no key is pressed. */
void loop() {
char key = keypad.getKey(); //storing pressed key value in a char
/* - Ensures that only valid key presses are processed (key != NO_KEY).
- Displays the pressed key on the serial monitor.
- The delay(10) prevents multiple detections of the same key due to bouncing. */
if (key != NO_KEY){
Serial.print("Key Pressed: ");
Serial.println(key);
delay(10); // this speeds up the simulation
}
}