#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
const byte rows = 4;
const byte cols = 4;
char keys[rows][cols] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'.','0','=','/'}
};
byte rowPins[rows] = {0, 1, 2, 3};
byte colPins[cols] = {4, 5, 6, 7};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );
String last3 = "";
String last2 = "";
String last1 = "";
String current = "";
char operation = 0;
void updateCursor() {
if (millis() / 500 % 2 == 0 ) {
lcd.cursor();
} else {
lcd.noCursor();
}
}
double calc(char op, double in1, double in2) {
switch(op) {
case '+': return in1 + in2;
case '-': return in1 - in2;
case '*': return in1 * in2;
case '/': return in1 / in2;
}
}
void readInput(char key) {
if(!key) {
return;
}
if(key == '-' && current == "") {
current = '-';
lcd.print('-');
return;
}
switch(key) {
case '+':
case '-':
case '*':
case '/':
if(!operation) {
last3 = last2;
last2 = last1;
last1 = current;
current = "";
}
operation = key;
lcd.setCursor(0, 3);
lcd.print(key);
lcd.setCursor(current.length() + 1, 3);
return;
case '=':
last3 = last2;
last2 = last1;
float num1 = last1.toDouble();
float num2 = current.toDouble();
last1 = String(calc(operation, num1, num2));
current = "";
lcd.clear();
lcd.setCursor(1, 0);
lcd.print(last3);
lcd.setCursor(1, 1);
lcd.print(last2);
lcd.setCursor(1, 2);
lcd.print(last1);
lcd.setCursor(1, 3);
operation = 0;
return;
}
if(key == '.' && current.indexOf('.') >= 0) {
return;
}
if(key == '.' && current == "0") {
current = String(key);
} else if (key) {
current += String(key);
}
lcd.print(key);
}
void setup() {
lcd.init();
lcd.backlight();
lcd.cursor_on();
lcd.setCursor(1,2);
}
String input = "";
String input2 = "";
void loop() {
updateCursor();
readInput(keypad.getKey());
}