#include <Keypad.h>
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
// Define the keymap
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// Connect to the keypad rows and columns
byte rowPins[ROWS] = {32, 33, 25, 26}; // Connect to the row pins
byte colPins[COLS] = {16, 4, 0, 2}; // Connect to the column pins
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
int result = 0;
int currentNumber = 0;
char lastOp = '\0';
void setup() {
Serial.begin(115200);
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
int digit = key - '0';
currentNumber = currentNumber * 10 + digit;
Serial.print("Current Number: ");
Serial.println(currentNumber);
} else if (key == 'A' || key == 'B' || key == 'C' || key == 'D') {
if (lastOp != '\0') {
calculate();
} else {
result = currentNumber;
}
lastOp = key;
currentNumber = 0;
Serial.print("Operator: ");
Serial.println(lastOp);
} else if (key == '#') {
if (lastOp != '\0') {
calculate();
lastOp = '\0';
}
Serial.print("Final Result: ");
Serial.println(result);
// Reset for next calculation
result = 0;
currentNumber = 0;
lastOp = '\0';
} else if (key == '*') {
// Reset all variables
result = 0;
currentNumber = 0;
lastOp = '\0';
Serial.println("Resetting calculator...");
}
}
}
void calculate() {
switch (lastOp) {
case 'A': result += currentNumber; break;
case 'B': result -= currentNumber; break;
case 'C': result *= currentNumber; break;
case 'D': result /= currentNumber; break;
}
Serial.print("Result after operation: ");
Serial.println(result);
}