// Dimas Atha Putra
// 230605110052
// Kalkulator two-term sederhana.
//
// A untuk tambah
// B untuk kurang
// C untuk kali
// D untuk bagi
// # untuk evaluasi
// * untuk reset
//
// Jika membuat ekspresi baru setelah evaluasi, baris jawaban akan berkedip,
// menandakan bahwa jawaban yang ada di baris itu adalah hasil evaluasi
// ekspresi sebelumnya, dan bukan yang sedang diketik. Dapat dikatakan juga:
// kalkulator sedang menunggu evaluasi
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
LiquidCrystal_I2C lcd(0x27, 16, 2);
String expression = "";
String ans = "";
String num1 = "";
String num2 = "";
String output = "Ans: 0";
boolean calculated = false;
boolean waiting = true;
int operand = 0;
int type = 0;
int prev_type = 0;
int terms = 0;
int clock = 0;
void setup(){
lcd.init();
lcd.backlight();
Serial.begin(9600);
lcd.setCursor(0, 1);
lcd.print(output);
}
void loop(){
char key = keypad.getKey();
clock++;
if (waiting) {
lcd.setCursor(0, 1);
if ((clock / 20) % 2 == 0) {
lcd.print("Ans: ");
} else {
lcd.print(output);
}
}
if (key){
String k = "";
switch (key) {
case 'A': k = " + "; prev_type = type; type = 1; operand = 1; break;
case 'B': k = " - "; prev_type = type; type = 1; operand = 2; break;
case 'C': k = " * "; prev_type = type; type = 1; operand = 3; break;
case 'D': k = " / "; prev_type = type; type = 1; operand = 4; break;
default: k = key; prev_type = type; type = 0; break;
}
if (key != '#' && key != '*') {
if (terms > 2 && type == 0) {terms = 2;}
else if (prev_type != type) {
terms++;
}
if (terms == 0 && type == 0) {num1 += k;}
if (terms >= 1 && type == 0) {num2 += k;}
if (terms <= 2) {
if (calculated) {
expression = "";
lcd.setCursor(0, 0);
lcd.print(" ");
calculated = false;
waiting = true;
}
expression += key != '*' ? k : "";
lcd.setCursor(0, 0);
String spaces = "";
for (int i = 0; i < (16 - expression.length()); i++) {
spaces += " ";
}
lcd.print(spaces);
lcd.print(expression);
}
} else if (key != '*') {
terms = 0;
ans = "";
switch (operand) {
case 1: ans += num1.toInt() + num2.toInt(); break;
case 2: ans += num1.toInt() - num2.toInt(); break;
case 3: ans += num1.toInt() * num2.toInt(); break;
case 4: ans += num1.toDouble() / num2.toDouble(); break;
}
num1 = "";
num2 = "";
int ans_len = ans.length();
String spaces = "";
for (int i = 0; i < (12 - ans_len); i++) {
spaces += " ";
}
output = ("Ans:") + spaces + ans;
lcd.setCursor(0, 1);
lcd.print(output);
calculated = true;
waiting = false;
} else {
lcd.clear();
terms = 0;
num1 = "";
num2 = "";
expression = "";
lcd.setCursor(0, 1);
lcd.print("Ans: 0");
}
}
}