#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 4;
byte rowPins[KEYPAD_ROWS] = {5, 4, 3, 2};
byte colPins[KEYPAD_COLS] = {A3, A2, A1, A0};
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'.', '0', '=', '/'}
};
Keypad keypad = Keypad(makeKeymap(keys),
rowPins,
colPins,
KEYPAD_ROWS,
KEYPAD_COLS);
String txt;
float mem;
char op;
void setup() {
Serial.begin(9600);
LCD.init();
LCD.backlight();
txt = "0";
LCD.print(txt);
mem = 0;
op = 'x';
}
String clean_str(String txt_in) {
boolean proc = true;
while(proc) {
proc = false;
if(txt_in.length() > 1)
if(txt_in.charAt(0) == '0') {
proc = true;
txt_in = txt_in.substring(1);
}
}
if((txt_in.length()>0) && (txt_in.charAt(0)=='.'))
txt_in = "0" + txt_in;
if(txt_in.indexOf("..") >= 0) {
txt_in = "0";
op = 'x';
mem = 0;
}
return txt_in;
}
void loop() {
// put your main code here, to run repeatedly:
char key = keypad.getKey();
if ((key >= '0' && key <= '9') ||
key == '.') {
txt = txt + key;
txt = clean_str(txt);
LCD.setCursor(0, 0);
LCD.print(" ");
LCD.setCursor(0, 0);
LCD.print(txt);
} else if(key == '+' || key == '-' || key == '*' || key == '/' || key == '='){
if(op == 'x') {
mem = txt.toFloat();
op = key;
txt = "0";
if(key == '=') {
op = 'x';
mem = 0;
}
}
else if (op == '+' || op == '-' || op == '*' || op == '/'){
float v = txt.toFloat();
if(op == '+')
mem = mem + v;
else if (op == '-')
mem = mem - v;
else if (op == '*')
mem = mem * v;
else if (op == '/')
mem = mem / v;
LCD.setCursor(0, 0);
LCD.print(String(mem));
op = key;
if(key == '=') {
mem = 0;
op = 'x';
}
}
txt = "0";
}
Serial.println(String(mem)+"---"+op+"---"+txt);
}