#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C display(0x27, 16, 2);
const byte rows = 4;
const byte columns = 4;
char keys[rows][columns] = {
{'1','2','3','+'}, {'4','5','6','-'}, {'7','8','9','*'}, {'C','0','=','/'}
};
byte keyPinRows[rows] = {7,6,5,4};
byte keyPinColumns[columns] = {3,2,1,0};
Keypad thisKeyPad = Keypad(makeKeymap(keys), keyPinRows, keyPinColumns, rows, columns);
char operation = 0;
String first = "";
String second = "";
double math(char operation, double first, double second)
{
switch(operation){
case '+':
return first + second;
break;
case '-':
return first - second;
break;
case '*':
return first * second;
break;
case '/':
return first / second;
break;
}
}
void process(char input)
{
if ('-' == input && second == "") {
second = "-";
display.print("-");
return;
}
switch(input){
case '+':
case '-':
case '*':
case '/':
if(!operation){
first = second;
second = "";
}
operation = input;
display.setCursor(0,1);
display.print(input);
display.setCursor(1,1);
return;
break;
case '=':
float left = first.toFloat();
float right = second.toFloat();
first = String(math(operation, left, right));
second = "";
display.clear();
display.setCursor(1,0);
display.print(first);
display.setCursor(0,1);
display.print(operation);
return;
break;
}
if(input != operation && second == "0"){
second = String(input);
} else if(input){
second += String(input);
}
display.print(input);
if(input == 'C'){
first="";
second="";
operation = 0;
display.clear();
display.setCursor(1,0);
}
}
void setup() {
display.init();
display.backlight();
display.setCursor(1,0);
}
void loop() {
char key = thisKeyPad.getKey();
if(key != NO_KEY){
process(key);
}
}