#include <Keypad.h>
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'.', '0', '=', '/'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String input = "";
int num1 = 0;
int num2 = 0;
char operand = ' ';
void setup() {
Serial.begin(9600);
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
input += key;
} else if (key == '.' && input.indexOf('.') == -1) {
input += key;
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
num1 = input.toInt();
operand = key;
input = "";
} else if (key == '=') {
num2 = input.toInt();
int result = calculate(num1, operand, num2);
Serial.print(num1);
Serial.print(" ");
Serial.print(operand);
Serial.print(" ");
Serial.print(num2);
Serial.print(" = ");
Serial.println(result);
num1 = result;
input = "";
}
}
}
int calculate(int a, char op, int b) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0) {
return a / b;
} else {
Serial.println("Error: Division by 0");
return 0; // Return 0 in case of division by zero
}
default:
return 0;
}
}