#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the LCD address and dimensions (change if needed)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define the keypad layout
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] = {2, 3, 4, 5};
byte colPins[COLS] = {6, 7, 8, 9};
// Create the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int resetButtonPin = 10; // Pin for the reset button
String inputString = "";
char operatorChar;
float num1, num2, result;
bool resetFlag = false;
void setup() {
pinMode(resetButtonPin, INPUT_PULLUP); // Set the reset button pin as input with internal pull-up
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.setCursor(0, 0);
lcd.print("Calculator");
delay(2000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
// Check if the reset button is pressed
if (digitalRead(resetButtonPin) == LOW) {
resetCalculator();
}
if (key) {
if (key >= '0' && key <= '9') {
inputString += key;
lcd.print(key);
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
num1 = inputString.toFloat();
operatorChar = key;
inputString = "";
lcd.print(key);
} else if (key == '=') {
num2 = inputString.toFloat();
inputString = "";
switch (operatorChar) {
case '+':
result = num2 + num1;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
lcd.clear();
lcd.print("Error: Div0");
return;
}
break;
}
lcd.clear();
lcd.print(result);
} else if (key == 'C') {
inputString = "";
lcd.clear();
}
}
}
void resetCalculator() {
inputString = "";
num1 = num2 = result = 0;
operatorChar = '\0';
lcd.clear();
lcd.print("Calculator");
delay(1000);
lcd.clear();
}