#include <LiquidCrystal.h>
#include <Keypad.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 4;
byte rowPins[KEYPAD_ROWS] = {5, 4, 3, 2};
byte colPins[KEYPAD_COLS] = {A3, A2, A1, A0};
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'.', '0', '=', '/'}
};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, KEYPAD_ROWS, KEYPAD_COLS);
double operand1 = 0;
double operand2 = 0;
char operation = '\0';
bool resultDisplayed = false;
void setup() {
Serial.begin(115200);
lcd.begin(16, 2);
showSplashScreen();
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
if (isdigit(key) || key == '.') {
handleDigitInput(key);
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
handleOperationInput(key);
} else if (key == '=') {
calculateResult();
}
}
}
void showSplashScreen() {
lcd.print("Arduino Calculator");
delay(2000);
lcd.clear();
}
void handleDigitInput(char key) {
if (resultDisplayed) {
lcd.clear();
resultDisplayed = false;
}
lcd.print(key);
if (operation == '\0') {
operand1 = (operand1 * 10) + (key - '0');
} else {
operand2 = (operand2 * 10) + (key - '0');
}
}
void handleOperationInput(char key) {
if (operation != '\0') {
calculateResult();
}
operation = key;
lcd.print(key);
}
void calculateResult() {
double result = 0;
switch (operation) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 != 0) {
result = operand1 / operand2;
} else {
lcd.clear();
lcd.print("Error: Division by 0");
delay(2000);
lcd.clear();
resetCalculator();
return;
}
break;
}
lcd.setCursor(0, 1);
lcd.print("=");
lcd.print(result);
operand1 = result;
operand2 = 0;
operation = '\0';
resultDisplayed = true;
}
void resetCalculator() {
operand1 = 0;
operand2 = 0;
operation = '\0';
resultDisplayed = false;
}