#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};
byte rowsPins[ROWS] = {9, 8, 7, 6};
byte colsPins[COLS] = {5, 4, 3, 2};
Keypad myKeypad = Keypad(makeKeymap(keys), rowsPins, colsPins, ROWS, COLS);
boolean presentValue = false;
boolean final = false;
String num1, num2;
int answer;
char op;
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Calculator");
delay(2000);
lcd.clear();
}
void loop() {
char key = myKeypad.getKey();
if (key != NO_KEY && (key == '1' || key == '2' || key == '3' || key == '4' || key == '5' || key == '6' || key == '7' || key == '8' || key == '9' || key == '0')) {
if (!presentValue) {
num1 += key;
lcd.setCursor(15 - num1.length(), 0);
lcd.print(num1);
} else {
num2 += key;
lcd.setCursor(15 - num2.length(), 1);
lcd.print(num2);
}
} else if (!presentValue && key != NO_KEY && (key == '/' || key == '*' || key == '-' || key == '+')) {
presentValue = true;
op = key;
lcd.setCursor(15, 0);
lcd.print(op);
} else if (final && key != NO_KEY && key == 'A') {
if (num2.toInt() != 0 || op != '/') {
if (op == '+') {
answer = num1.toInt() + num2.toInt();
} else if (op == '-') {
answer = num1.toInt() - num2.toInt();
} else if (op == '*') {
answer = num1.toInt() * num2.toInt();
} else if (op == '/') {
answer = num1.toInt() / num2.toInt();
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(answer);
} else {
lcd.clear();
lcd.print("Error: Division by zero");
}
presentValue = false;
final = false;
num1 = "";
num2 = "";
answer = 0;
op = ' ';
} else if (key != NO_KEY && key == 'C') {
lcd.clear();
presentValue = false;
final = false;
num1 = "";
num2 = "";
answer = 0;
op = ' ';
}
}