#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
/* Konfigurasi Display */
LiquidCrystal_I2C lcd(0x27, 16, 2); // Address I2C LCD: 0x27, Ukuran LCD: 16x2
/* Konfigurasi Keypad */
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);
/* Variable Global */
char operation = 0;
String memory = "";
String current = "";
/* Fungsi Menampilkan Splash Screen_Membuat fungsi showSplashScreen untuk menampilkan pesan selamat datang ("GoodArduinoCode") dan nama kalkulator pada LCD.*/
void showSplashScreen() {
lcd.init(); // Inisialisasi LCD I2C
lcd.backlight(); // Nyalakan backlight LCD
lcd.print("GoodArduinoCode");
lcd.setCursor(3, 1);
String message = "Kalkulator";
for (byte i = 0; i < message.length(); i++) {
lcd.print(message[i]);
delay(50);
}
delay(500);
}
/* Fungsi Update Kursor_Membuat fungsi updateCursor untuk mengatur kursor pada LCD agar berkedip. */
void updateCursor() {
if (millis() / 250 % 2 == 0) {
lcd.cursor();
} else {
lcd.noCursor();
}
}
void setup() {
Serial.begin(115200);
// Menampilkan splash screen dan mengatur tampilan awal LCD
showSplashScreen();
lcd.clear();
lcd.setCursor(1, 0);
}
/* Fungsi Kalkulasi_calculate: Fungsi untuk melakukan operasi kalkulasi berdasarkan operator yang dipilih. */
double calculate(char operation, double left, double right) {
switch (operation) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
}
}
/* Fungsi Proses Input_processInput: Fungsi untuk memproses input dari keypad, menangani operator, dan menampilkan hasil pada LCD. */
void processInput(char key) {
if ('-' == key && current == "") {
current = "-";
lcd.print("-");
return;
}
switch (key) {
case '+':
case '-':
case '*':
case '/':
if (!operation) {
memory = current;
current = "";
}
operation = key;
lcd.setCursor(0, 1);
lcd.print(key);
lcd.setCursor(current.length() + 1, 1);
return;
case '=':
float leftNum = memory.toDouble();
float rightNum = current.toDouble();
memory = String(calculate(operation, leftNum, rightNum));
current = "";
lcd.clear();
lcd.setCursor(1, 0);
lcd.print(memory);
lcd.setCursor(0, 1);
lcd.print(operation);
return;
}
if ('.' == key && current.indexOf('.') >= 0) {
return;
}
if ('.' != key && current == "0") {
current = String(key);
} else if (key) {
current += String(key);
}
lcd.print(key);
}
void loop() {
// Menangani input dari keypad dan menampilkan hasil di LCD
updateCursor();
char key = keypad.getKey();
if (key) {
processInput(key);
}
}