#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);
const byte row = 4;
const byte col = 4;
//definsikan keymap
char keys[row][col] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', 'x'},
{'C', '0', '=', '/'}
};
byte PinBaris[row] = {13, 12, 14, 27 };
byte PinKolom[col] = {26, 25, 33, 32 };
Keypad myKeypad = Keypad(makeKeymap(keys), PinBaris, PinKolom, row, col );
boolean valOnePresent = false;
boolean final = false;
String num1, num2;
long ans;
char op;
void setup(){
lcd.init(); // inialisasi lcd
lcd.backlight(); //nyalakan baclight
lcd.setCursor(2,0);
lcd.print("Calculator!");
delay(1000);
lcd.clear(); //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 (valOnePresent != true){
num1 = num1 + key;
int numLength = num1.length();
lcd.setCursor(0, 0);//print operator
lcd.print(num1);
}
else {
num2 = num2 + key;
int numLength = num2.length();
lcd.setCursor(0, 1);
lcd.print(num2);
final = true;
}
}
else if (valOnePresent == false && key != NO_KEY && (key
== '/' || key == 'x' || key == '-' || key == '+')){
if (valOnePresent == false){
valOnePresent = true;
op = key;
lcd.setCursor(5,0);
lcd.print(op);
}
}
else if (final == true && key != NO_KEY && key == '='){
if (op == '+'){
ans = num1.toInt() + num2.toInt();
}
else if (op == '-'){
ans = num1.toInt() - num2.toInt();
}
else if (op == 'x'){
ans = num1.toInt() * num2.toInt();
}
else if (op == '/'){
ans = num1.toInt() / num2.toInt();
}
lcd.clear();
lcd.setCursor(0,0);
lcd.autoscroll();
lcd.print(ans);
lcd.noAutoscroll();
}
else if (key != NO_KEY && key == 'C'){
lcd.clear();
valOnePresent = false;
final = false;
num1 = "";
num2 = "";
ans = 0;
op = ' ';
}
}