#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};
byte rowPins[ROWS] = {13, 12, 14, 27};
byte colPins[COLS] = {26, 25, 33, 32};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int blueLED = 4;
const int greenLED = 2;
String input = "";
int result = 0;
char currentOp;
int num1 = 0;
int num2 = 0;
bool waitingForSecondNumber = false;
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Emil & Nathan");
delay(2500);
lcd.clear();
pinMode(blueLED, OUTPUT);
pinMode(greenLED, OUTPUT);
digitalWrite(blueLED, LOW);
digitalWrite(greenLED, LOW);
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
input += key;
lcd.setCursor(0, 1);
lcd.print(input);
}
else if (key == '+' || key == '-' || key == '*' || key == '/') {
if (input != "") {
num1 = input.toInt();
input = "";
currentOp = key;
waitingForSecondNumber = true;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Op: ");
lcd.print(currentOp);
}
}
else if (key == '=') {
if (waitingForSecondNumber && input != "") {
num2 = input.toInt();
input = "";
result = calculate(num1, num2, currentOp);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Hasil: ");
lcd.setCursor(0, 1);
lcd.print(result);
if (result % 2 == 0) {
digitalWrite(blueLED, HIGH);
digitalWrite(greenLED, LOW);
} else {
digitalWrite(greenLED, HIGH);
digitalWrite(blueLED, LOW);
}
num1 = 0;
num2 = 0;
waitingForSecondNumber = false;
}
}
else if (key == 'C') {
input = "";
lcd.clear();
digitalWrite(blueLED, LOW);
digitalWrite(greenLED, LOW);
}
}
}
int calculate(int a, int b, char op) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return b != 0 ? a / b : 0;
default: return 0;
}
}