#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Inisialisasi LCD 16x2
long first = 0;
long second = 0;
double total = 0;
char customKey;
int cursor = 0;
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] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad customKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
lcd.init(); // Inisialisasi LCD
lcd.backlight(); // Nyalakan lampu latar LCD
}
void loop() {
customKey = customKeypad.getKey();
switch (customKey) {
case '0' ... '9':
lcd.setCursor(0, 0);
first = first * 10 + (customKey - '0');
lcd.print(first);
break;
case '+':
first = (total != 0 ? total : first);
cursor = String(first).length();
lcd.setCursor(cursor, 0);
lcd.print("+");
cursor = String(first).length() + 1;
second = SecondNumber(cursor);
total = first + second;
lcd.setCursor(0, 1);
lcd.print(total);
first = 0;
second = 0;
break;
case '-':
first = (total != 0 ? total : first);
cursor = String(first).length();
lcd.setCursor(cursor, 0);
lcd.print("-");
cursor = String(first).length() + 1;
second = SecondNumber(cursor);
total = first - second;
lcd.setCursor(0, 1);
lcd.print(total);
first = 0;
second = 0;
break;
case '*':
first = (total != 0 ? total : first);
cursor = String(first).length();
lcd.setCursor(cursor, 0);
lcd.print("*");
cursor = String(first).length() + 1;
second = SecondNumber(cursor);
total = first * second;
lcd.setCursor(0, 1);
lcd.print(total);
first = 0;
second = 0;
break;
case '/':
first = (total != 0 ? total : first);
cursor = String(first).length();
lcd.setCursor(cursor, 0);
lcd.print("/");
cursor = String(first).length() + 1;
second = SecondNumber(cursor);
lcd.setCursor(0, 1);
if (second == 0) {
lcd.print("Invalid");
} else {
total = (float)first / (float)second;
lcd.print(total);
}
first = 0;
second = 0;
break;
case 'C':
total = 0;
lcd.clear();
break;
}
}
long SecondNumber(int cursor) {
second = 0; // Reset nilai kedua
while (true) {
customKey = customKeypad.getKey();
if (customKey >= '0' && customKey <= '9') {
second = second * 10 + (customKey - '0');
lcd.setCursor(cursor, 0);
lcd.print(second);
}
if (customKey == '=') {
break; // Kembali setelah menekan '='
}
}
return second; // Kembalikan nilai kedua
}