Code Explanation
Code Explanation
#include <Keypad.h>
• Includes the Keypad library to handle user input from a 4x4 matrix keypad.
2. Keypad Setup
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
int counterValueInt = 0;
4. Setup Function
void setup() {
Serial.begin(9600);
pinMode(bcdA[i], OUTPUT);
pinMode(bcdB[i], OUTPUT);
pinMode(bcdC[i], OUTPUT);
pinMode(bcdD[i], OUTPUT);
pinMode(buzzerPin, OUTPUT);
keypad.addEventListener(keypadEvent);
keypad.setDebounceTime(10);
• Configures the buzzer and keypad.
displayCounter();
void loop() {
if (button) {
Serial.println(button);
previousMillis = currentMillis;
if (isCounterRunning) {
if (isCountingUp) {
if (counterValueInt == 9999) {
counterValueInt = 0;
displayCounter();
resetCounter();
} else {
counterValueInt++;
} else {
if (counterValueInt == 0){
counterValueInt = 0;
displayCounter();
resetCounter();
} else {
counterValueInt--;
displayCounter();
if (keypad.getState() == PRESSED) {
if (counterValueStr.length() == 4) {
} else {
counterValueStr += key;
counterValueInt = counterValueStr.toInt();
displayCounter();
}
• Handles number input: If 4 digits are entered, it removes the first and adds the new.
if (key == '*') {
if (isCounterRunning) return;
isCounterRunning = true;
displayCounter();
if (key == '#') {
isCounterRunning = false;
displayCounter();
counterValueInt++;
isCountingUp = true;
displayCounter();
counterValueInt--;
isCountingUp = false;
displayCounter();
void displayCounter() {
8. Buzzer Alerts
• Sounds a buzzer alert when countdown reaches critical numbers (5, 4, 3, 2, 1, 0).
void resetCounter() {
counterValueInt = 0;
counterValueStr = "";
isCounterRunning = false;
isCountingUp = false;
isReset = true;
displayCounter();
delay(1000);
Summary
1. The code uses a 4x4 keypad to control a 4-digit counter, which is displayed using BCD (Binary-
Coded Decimal) outputs.
2. It defines the keypad layout, assigns row and column pins, and initializes the Keypad library for
detecting key presses.
3. The counter's value is stored as both an integer (counterValueInt) and a string (counterValueStr)
for display handling.
4. The setup() function configures the BCD output pins, the buzzer pin, and initializes the display.
5. The loop() function continuously checks for keypresses and updates the counter every second if
counting is active.
6. The keypad's keypadEvent() function handles key presses to set or modify the counter value,
start/stop counting, or change counting direction.
7. The displayCounter() function converts the counter value into BCD format and updates the
display accordingly.
8. The buzzer provides sound feedback when the counter reaches specific values, especially near
zero in countdown mode.
9. The resetCounter() function resets the counter, stops counting, and clears the display when
needed.
10. The program ensures smooth user interaction by implementing debounce timing and updating
the display in real time.