#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// LCD setup
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] = {2, 4, 5, 0}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {25, 26, 27, 32}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
float num1 = 0;
float num2 = 0;
char operation = ' ';
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(2,0);
lcd.print(" Calculator!");
delay(5000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
lcd.print(key);
if (operation == ' ') {
num1 = num1 * 10 + (key - '0');
} else {
num2 = num2 * 10 + (key - '0');
}
} else if (key == 'C') {
lcd.clear();
num1 = 0;
num2 = 0;
operation = ' ';
} else if (key == '=' && operation != ' ') {
float result = 0;
switch (operation) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if (num2 != 0) result = num1 / num2;
else lcd.print("Err"); // Handle division by zero
break;
}
lcd.print(" = ");
lcd.print(result);
num1 = result; // Allow chaining operations
num2 = 0;
operation = ' ';
} else {
operation = key; // Save the operation
lcd.print(" ");
lcd.print(operation);
}
}
}