#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// Inisialisasi LCD dengan alamat I2C 0x27 dan ukuran 16x2
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Konfigurasi Keypad
const byte ROWS = 4; // Empat baris
const byte COLS = 4; // Empat kolom
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // Pin Arduino yang terhubung ke baris keypad
byte colPins[COLS] = {5, 4, 3, 2}; // Pin Arduino yang terhubung ke kolom keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String input = ""; // String untuk menyimpan input dari keypad
char operatorSymbol; // Variabel untuk menyimpan operator ('+', '-', '*', '/')
int num1 = 0, num2 = 0; // Variabel untuk menyimpan angka
void setup() {
lcd.begin(16,2); // Memulai LCD
lcd.backlight(); // Mengaktifkan lampu latar LCD
lcd.print("Calculator"); // Menampilkan pesan awal
delay(2000); // Tunggu 2 detik
lcd.clear(); // Bersihkan layar LCD
}
void loop() {
char key = keypad.getKey(); // Baca input dari keypad
if (key) {
if (key >= '0' && key <= '9') {
input += key; // Menambahkan angka yang ditekan ke input
lcd.setCursor(0, 0);
lcd.print(input); // Menampilkan input di LCD
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
num1 = input.toInt(); // Konversi input pertama ke integer
operatorSymbol = key; // Simpan operator
input = ""; // Reset input untuk angka kedua
lcd.clear();
lcd.print(num1); // Tampilkan angka pertama
lcd.print(operatorSymbol); // Tampilkan operator
} else if (key == '=') {
num2 = input.toInt(); // Konversi input kedua ke integer
int result = 0;
// Proses perhitungan berdasarkan operator
switch(operatorSymbol) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
lcd.clear();
lcd.print("Err: Div by 0"); // Error jika pembagian dengan 0
return;
}
break;
}
lcd.clear();
lcd.print("Result:");
lcd.setCursor(0, 1);
lcd.print(result); // Tampilkan hasil
input = ""; // Reset input
} else if (key == 'C') {
// Reset semua jika tombol 'C' ditekan
lcd.clear();
input = "";
num1 = 0;
num2 = 0;
operatorSymbol = '\0';
}
}
}