#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// Initialize the LCD with the address of the I2C chip
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define the keypad
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};
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
// Create the Keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String input = ""; // String to store user input
float num1 = 0;
float num2 = 0;
char op;
void setup() {
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Calculator:");
}
void loop() {
char key = keypad.getKey(); // Read the keypad
if (key) { // If a key is pressed
if (key == 'C') { // Clear input
input = "";
} else if (key == '=') { // Calculate result
lcd.clear();
lcd.setCursor(0,0);
lcd.print(input);
lcd.setCursor(0,1);
lcd.print("=");
calculateResult();
delay(2000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Calculator:");
} else { // Append pressed key to input
input += key;
}
lcd.setCursor(0,1);
lcd.print(input);
}
}
void calculateResult() {
int pos = input.indexOfAny("+-*/"); // Find operator position
if (pos != -1) {
num1 = input.substring(0, pos).toFloat(); // Extract first number
op = input[pos]; // Extract operator
num2 = input.substring(pos + 1).toFloat(); // Extract second number
float result = 0;
switch(op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
lcd.setCursor(0,1);
lcd.print("Error: Div by 0");
return;
}
break;
}
lcd.setCursor(0,1);
lcd.print(result);
}
}