#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
const byte ROW_NUM = 4; //four rows
const byte COLUMN_NUM = 4; //four columns
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};
byte pin_rows[ROW_NUM] = {9, 8, 7, 6}; // connect to the row pinouts of the keypad
byte pin_column[COLUMN_NUM] = {5, 4, 3, 2}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the I2C address to 0x27 and 16x2 characters
float num1 = 0;
float num2 = 0;
char operation = '\0';
bool newInput = false;
void setup() {
lcd.begin(16, 2);
lcd.print("Arduino Calc");
delay(1000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key) {
processKey(key);
delay(200); // Debounce delay
}
}
void processKey(char key) {
if (isdigit(key) || key == '.') {
handleDigit(key);
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
handleOperation(key);
} else if (key == '=') {
handleEquals();
} else if (key == 'C') {
clearCalculator();
}
updateLCD();
}
void handleDigit(char digit) {
if (newInput) {
newInput = false;
lcd.clear();
}
lcd.print(digit);
if (operation == '\0') {
num1 = num1 * 10 + (digit - '0');
} else {
num2 = num2 * 10 + (digit - '0');
}
}
void handleOperation(char op) {
if (operation != '\0') {
handleEquals(); // Perform the previous operation if any
}
operation = op;
newInput = true;
}
void handleEquals() {
float result = 0;
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
lcd.clear();
lcd.print("Error: Div by 0");
delay(2000);
clearCalculator();
return;
}
break;
}
lcd.clear();
lcd.print(result);
clearCalculator();
}
void clearCalculator() {
num1 = 0;
num2 = 0;
operation = '\0';
newInput = false;
}
void updateLCD() {
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the second line
lcd.setCursor(0, 1);
lcd.print(num1);
if (operation != '\0') {
lcd.print(" ");
lcd.print(operation);
lcd.print(" ");
lcd.print(num2);
}
}