#include <Keypad.h>
#include <LiquidCrystal.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] = {A0, A1, A2, A3};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
String input = "";
float num1 = 0;
float num2 = 0;
char operand = ' ';
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.print("Calculator");
delay(1000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
input += key;
lcd.print(key);
} else if (key == '.' && input.indexOf('.') == -1) {
input += key;
lcd.print(key);
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
num1 = input.toFloat();
operand = key;
input = "";
lcd.print(key);
} else if (key == '=') {
num2 = input.toFloat();
float result = calculate(num1, operand, num2);
lcd.clear();
lcd.print(result);
delay(2000);
lcd.clear();
num1 = result;
input = "";
}
}
}
float calculate(float a, char op, float b) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0) {
return a / b;
} else {
lcd.clear();
lcd.print("Error: Division by 0");
delay(2000);
lcd.clear();
return 0;
}
default:
return 0;
}
}