#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; // Connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal_I2C lcd(0x27, 16, 2);
String input = "";
char operation = 0;
float num1, num2, result;
void setup() {
lcd.begin(16, 2);
lcd.print("Calculator Ready");
delay(2000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') { // If key is a number
input += key;
lcd.setCursor(0, 0);
lcd.print(input);
}
else if (key == 'A' || key == 'B' || key == 'C' || key == 'D') { // If key is an operator
if (input.length() > 0) {
num1 = input.toFloat();
input = "";
operation = key;
lcd.setCursor(0, 1);
lcd.print(key);
}
}
else if (key == '#') { // Equals key
if (input.length() > 0) {
num2 = input.toFloat();
switch (operation) {
case 'A': result = num1 + num2; break;
case 'B': result = num1 - num2; break;
case 'C': result = num1 * num2; break;
case 'D': result = num2 != 0 ? num1 / num2 : 0; break; // Avoid division by zero
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Result: ");
lcd.print(result);
delay(3000);
input = "";
lcd.clear();
}
}
else if (key == '*') { // Clear key
input = "";
operation = 0;
lcd.clear();
}
}
}