#include <Keypad.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
const int rows = 4;
const int cols = 4;
char keys[rows][cols] =
{
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', 'E', '/'}
};
byte rowPins[rows] = {0, 1, 2, 3};
byte colPins[cols] = {4, 5, 6, 7};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);
long num1 = 0;
long num2 = 0;
double res = 0;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Basic Calculator");
lcd.setCursor(0, 1);
lcd.print("By Rahul Verma");
delay(2000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if(key >= '0' && key <= '9') {
num1 = num1 * 10 + (key - '0');
lcd.print(key);
}
else if(key == '+' || key == '-' || key == '*' || key == '/') {
lcd.print(key);
num2 = secondNumber();
if(key == '+') {
res = num1 + num2;
}
else if(key == '-') {
res = num1 - num2;
}
else if(key == '*') {
res = num1 * num2;
}
else if(key == '/') {
res = (float)num1 / (float)num2;
}
lcd.setCursor(0, 1);
lcd.print(res);
}
else if(key == 'C'){
lcd.clear();
num1 = num2 = res = 0;
}
}
long secondNumber() {
while(true) {
char key = keypad.getKey();
if(key >= '0' && key <= '9') {
num2 = num2 * 10 + (key - '0');
lcd.print(key);
}
if(key == 'E'){
lcd.print('=');
break;
}
}
return num2;
}