#include <Keypad.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(41, 53, 51, 49, 47, 45, 43);
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] = {52, 50, 48, 46}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {44, 42, 40, 38}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String inputBuffer = ""; // buffer to store input
float operand1 = 0;
float operand2 = 0;
char operatorSymbol = '\0';
void setup() {
pinMode(38, INPUT);
pinMode(40, INPUT);
pinMode(42, INPUT);
pinMode(44, INPUT);
pinMode(46, INPUT);
pinMode(48, INPUT);
pinMode(50, INPUT);
pinMode(52, INPUT);
pinMode(41, OUTPUT);
pinMode(43, OUTPUT);
pinMode(45, OUTPUT);
pinMode(47, OUTPUT);
pinMode(49, OUTPUT);
pinMode(51, OUTPUT);
pinMode(53, OUTPUT);
lcd.begin(16, 2);
lcd.print("Calculator");
delay(2000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
lcd.print(key);
if (isdigit(key)) {
// If it's a digit or '.', add it to the buffer
inputBuffer += key;
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
// If it's an operator, handle it accordingly
if (inputBuffer != "") {
operand1 = inputBuffer.toFloat();
operatorSymbol = key;
inputBuffer = "";
}
} else if (key == '=') {
// If it's '=', handle the calculation
if (inputBuffer != "") {
operand2 = inputBuffer.toFloat();
inputBuffer = "";
float result;
switch (operatorSymbol) {
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 zero");
delay(2000);
lcd.clear();
return;
}
break;
default:
result = 0;
}
lcd.clear();
lcd.print("Result: ");
lcd.setCursor(0, 1);
lcd.print(result);
delay(2000);
lcd.clear();
}
} else if (key == 'C') {
// If it's 'C', clear the buffer and the display
inputBuffer = "";
operand1 = 0;
operand2 = 0;
operatorSymbol = '\0';
lcd.clear();
}
}
}