#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LCD setup (I2C address 0x27, 16x2 display)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Keypad setup
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
byte rowPins[ROWS] = {32, 33, 25, 26}; // R1,R2,R3,R4
byte colPins[COLS] = {27, 14, 12, 13}; // C1,C2,C3,C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Calculator variables
String num1 = "";
String num2 = "";
char op = 0;
bool secondNum = false;
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Calc Ready");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') { // number pressed
if (!secondNum) {
num1 += key;
lcd.clear();
lcd.print(num1);
} else {
num2 += key;
lcd.clear();
lcd.print(num1);
lcd.print(op);
lcd.print(num2);
}
}
else if (key == '+' || key == '-' || key == '*' || key == '/') {
if (num1 != "") {
op = key;
secondNum = true;
lcd.clear();
lcd.print(num1);
lcd.print(op);
}
}
else if (key == '=') {
if (num1 != "" && num2 != "" && op != 0) {
long n1 = num1.toInt();
long n2 = num2.toInt();
long result = 0;
if (op == '+') result = n1 + n2;
else if (op == '-') result = n1 - n2;
else if (op == '*') result = n1 * n2;
else if (op == '/' && n2 != 0) result = n1 / n2;
lcd.clear();
lcd.print("Result:");
lcd.setCursor(0, 1);
lcd.print(result);
// reset
num1 = "";
num2 = "";
op = 0;
secondNum = false;
}
}
else if (key == 'C') {
// clear everything
num1 = "";
num2 = "";
op = 0;
secondNum = false;
lcd.clear();
lcd.print("Cleared");
}
}
}