#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
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] = { 13, 12, 11, 10 };
byte colPins[COLS] = { 9, 8, 7, 6 };
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String num1 = "";
String num2 = "";
char operatorChar = 0;
boolean isSecondNum = false;
void setup() {
lcd.init();
lcd.backlight();
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
if (!isSecondNum) {
num1 += key;
lcd.setCursor(0, 0);
lcd.print(num1);
} else {
num2 += key;
lcd.setCursor(0, 0);
lcd.print(num1 + operatorChar + num2);
}
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
if (!isSecondNum && num1.length() > 0) {
operatorChar = key;
isSecondNum = true;
lcd.setCursor(0, 0);
lcd.print(num1 + operatorChar);
}
} else if (key == '#') {
if (num1.length() > 0 && num2.length() > 0) {
float number1 = num1.toFloat();
float number2 = num2.toFloat();
float result = 0;
switch (operatorChar) {
case '+': result = number1 + number2; break;
case '-': result = number1 - number2; break;
case '*': result = number1 * number2; break;
case '/': result = number1 / number2; break;
}
lcd.setCursor(0, 1);
lcd.print(result);
delay(900);
resetCalculator();
}
} else if (key == '*') {
resetCalculator();
}
}
}
void resetCalculator() {
num1 = "";
num2 = "";
operatorChar = 0;
isSecondNum = false;
lcd.clear();
lcd.setCursor(0, 0);
}