#include <Keypad.h> //include keypad library
#include <Wire.h> //include I2C library
#include <LiquidCrystal_I2C.h> //include liquidcrystal with i2c communication
LiquidCrystal_I2C lcd(0x27, 16, 2); //I2C address is 0x27,and the liquidcrystal with 16-column and 2-rows
const byte numRows = 4; //prototype row-number
const byte numCols = 4; //prototype column-number
String pad;
byte rowPins[numRows] = {2,3,4,5}; //prototype
byte colPins[numCols] = {6,7,8,9};
char keymap[numRows][numCols] =
{
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
//keymap the keypad and the prototype
Keypad keypad = Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);
int num1 = 0;
int num2 = 0;
char op;
String currentInput = "";
bool inputReady = true, initialPos = true, clear = false;
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight();
lcd.setCursor(0,0);
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key == '+' || key == '-' || key == '*' || key == '/') {
if (inputReady) {
num1 = currentInput.toInt();
currentInput = "";
lcd.setCursor(15,0);
lcd.print(key);
initialPos = false;
op = key;
}
} else if (key == '=') {
if (inputReady) {
num2 = currentInput.toInt();
int 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");
delay(2000);
}
break;
}
lcd.clear();
lcd.setCursor(0,0);
lcd.print(result); // Display result with 2 decimal places
num1 = result;
num2 = 0;
currentInput = "";
inputReady = false;
initialPos = true;
clear = true;
}
} else if (key == 'C') {
num1 = 0;
num2 = 0;
op = '\0';
currentInput = "";
lcd.clear();
initialPos = true;
} else {
if (clear){
lcd.clear();
clear = false;
}
if (initialPos){
lcd.setCursor(0,0);
currentInput += key;
lcd.print(currentInput);
inputReady = true;
}
else
{
lcd.setCursor(0,1);
currentInput += key;
lcd.print(currentInput);
inputReady = true;}
}
}
}