#include <Wire.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
// Keypad configuration
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] = {13, 12, 11, 10};
byte colPins[COLS] = {7, 6, 5, 4};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// I2C LCD configuration
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust the I2C address if necessary
String inputString = "";
String operatorChar = "";
int firstNum = 0;
int secondNum = 0;
void setup() {
lcd.begin(16, 2);
delay(2000);
lcd.clear();
lcd.backlight();
}
void loop() {
char key = keypad.getKey();
if (key) {
// Handle number keys
if (key >= '0' && key <= '9') {
inputString += key;
lcd.print(key);
}
// Handle clear key
else if (key == 'C') {
inputString = "";
operatorChar = "";
firstNum = 0;
secondNum = 0;
lcd.clear();
}
// Handle operator keys
else if (key == '+' || key == '-' || key == '*' || key == '/') {
firstNum = inputString.toInt();
operatorChar = key;
inputString = "";
lcd.print(key);
}
// Handle equals key
else if (key == '=') {
secondNum = inputString.toInt();
int result = 0;
// Perform the calculation based on the operator
if (operatorChar == "+") {
result = firstNum + secondNum;
} else if (operatorChar == "-") {
result = firstNum - secondNum;
} else if (operatorChar == "*") {
result = firstNum * secondNum;
} else if (operatorChar == "/") {
result = firstNum / secondNum;
}
lcd.setCursor(0,1);
lcd.print(result);
// Reset variables for new calculations
inputString = "";
operatorChar = "";
firstNum = 0;
secondNum = 0;
}
}
}