#include <LiquidCrystal.h>
#include <Keypad.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
// Konfigurasi keypad
const byte Keypad_baris = 4;
const byte Keypad_kolom = 4;
byte barisPins[Keypad_baris] = {5, 4, 3, 2};
byte kolomPins[Keypad_kolom] = {A0, A1, A2, A3};
char keys[Keypad_baris][Keypad_kolom] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '.'},
{'*', '0', '/', '='}
};
// Inisialisasi objek Keypad
Keypad keypad = Keypad(makeKeymap(keys), barisPins, kolomPins, Keypad_baris, Keypad_kolom);
// Fungsi untuk menampilkan layar splash
void showSplashScreen() {
lcd.print("Pengujian Mikrokontroler");
lcd.setCursor(3, 1);
String message = "Kalkulator";
for (byte i = 0; i < message.length(); i++) {
lcd.print(message[i]);
delay(50);
}
delay(500);
}
// Fungsi untuk mengganti status kursor LCD
void updateCursor() {
if (millis() / 250 % 2 == 0 ) {
lcd.cursor();
} else {
lcd.noCursor();
}
}
// Fungsi setup() yang dijalankan sekali saat Arduino pertama kali dinyalakan
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
// Menampilkan layar splash
showSplashScreen();
lcd.clear();
lcd.cursor();
lcd.setCursor(1, 0);
}
// Variabel-variabel untuk mengelola input dan perhitungan
char operation = 0;
String memory = "";
String current = "";
bool decimalPoint = false;
// Fungsi untuk melakukan perhitungan matematika
double calculate(char operation, double left, double right) {
switch (operation) {
case '+': return left + right;
case '-': return left - right;
// Hanya menangani operasi - dan +
default: return 0;
}
}
// Fungsi untuk memproses input dari keypad
void processInput(char key) {
// Kasus khusus untuk input negatif
if ('-' == key && current == "") {
current = "-";
lcd.print("-");
return;
}
// Menangani operator matematika
switch (key) {
case '+':
case '-':
if (!operation) {
memory = current;
current = "";
}
operation = key;
lcd.setCursor(0, 1);
lcd.print(key);
lcd.setCursor(current.length() + 1, 1);
return;
// Menangani input '*' untuk menghapus hasil perhitungan
case '*':
memory = "";
current = "";
operation = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.setCursor(1, 0); // Atur kursor ke posisi awal
return;
// Menangani input '=' untuk menampilkan hasil perhitungan
case '=':
float leftNum = memory.toDouble();
float rightNum = current.toDouble();
memory = String(calculate(operation, leftNum, rightNum));
current = "";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(memory);
lcd.setCursor(0, 1);
return;
}
// Menangani input '.' dan '0'
if ('.' == key && current.indexOf('.') >= 0) {
return;
}
if ('.' != key && current == "0") {
current = String(key);
} else if (key) {
current += String(key);
}
lcd.print(key);
}
// Fungsi utama yang terus diulang
void loop() {
// Memperbarui kursor LCD
updateCursor();
// Membaca input dari keypad
char key = keypad.getKey();
if (key) {
// Memproses input
processInput(key);
}
}