#include <Keypad.h>
const byte ROWS = 4;
const byte COLS = 4;
char customKeymap[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad customKeypad = Keypad(makeKeymap(customKeymap), rowPins, colPins, ROWS, COLS);
String input = "";
float num1 = 0;
float num2 = 0;
char op;
void setup() {
Serial.begin(9600);
}
void loop() {
char key = customKeypad.getKey(); // Rename the Keypad object
if (key) {
if (key == 'C') {
input = "";
num1 = 0;
num2 = 0;
op = 0;
Serial.println("Cleared");
} else if (key == '=') {
if (input.length() > 0 && op != 0) {
num2 = input.toFloat();
float result = calculate(num1, num2, op);
Serial.print(num1);
Serial.print(" ");
Serial.print(op);
Serial.print(" ");
Serial.print(num2);
Serial.print(" = ");
Serial.println(result);
num1 = result;
input = String(result);
op = 0;
}
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
if (input.length() > 0 && op == 0) {
num1 = input.toFloat();
input = "";
op = key;
}
} else {
input += key;
}
}
}
float calculate(float a, float b, char operation) {
switch (operation) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0) {
return a / b;
} else {
Serial.println("Division by zero!");
return 0;
}
}
return 0;
}