//calculator program
#include <LiquidCrystal.h>
#include <Keypad.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
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] = {7, 6, 5, 4}; // Rows 0 to 3
byte colPins[COLS] = {3, 2, 1, 0}; // Columns 0 to 3
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
int operand1 = 0;
int operand2 = 0;
char operation;
bool calculating = false;
void setup() {
lcd.begin(16, 2);
lcd.print("Calculator:");
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
if (key == 'C') {
clearCalculator();
} else if (key >= '0' && key <= '9') {
if (!calculating) {
operand1 = operand1 * 10 + (key - '0');
lcd.setCursor(0, 1);
lcd.print(operand1);
} else {
operand2 = operand2 * 10 + (key - '0');
lcd.setCursor(8, 1);
lcd.print(operand2);
}
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
operation = key;
lcd.setCursor(7, 1);
lcd.print(operation);
calculating = true;
} else if (key == '=') {
float 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: Div by 0");
delay(2000);
clearCalculator();
break;
}
break;
}
lcd.setCursor(0, 1);
lcd.clear();
lcd.print(result);
delay(5000);
clearCalculator();
}
}
}
void clearCalculator() {
operand1 = 0;
operand2 = 0;
operation = ' ';
calculating = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Calculator:");
}