#include <Wire.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
// Inisialisasi LCD dengan alamat I2C (sesuaikan dengan modul Anda, biasanya 0x27 atau 0x3F)
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] = {5, 4, 3, 2}; // Pin yang terhubung ke baris keypad
byte colPins[COLS] = {9, 8, 7, 6}; // Pin yang terhubung ke kolom keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Variabel untuk menyimpan input dan hasil
String inputString = "";
float num1 = 0;
float num2 = 0;
char operatorChar = 0;
bool newCalculation = true;
void setup() {
lcd.init(); // Inisialisasi LCD
lcd.backlight(); // Mengaktifkan backlight LCD
lcd.setCursor(0, 0);
lcd.print("Masukkan Volume");
delay(2000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') { // Jika tombol angka ditekan
inputString += key;
lcd.setCursor(0, 0);
lcd.print(inputString);
}
else if (key == '+' || key == '-' || key == '*' || key == '/') { // Jika tombol operator ditekan
if (inputString.length() > 0) {
num1 = inputString.toFloat();
operatorChar = key;
inputString = "";
lcd.setCursor(0, 0);
lcd.print(num1);
lcd.print(operatorChar);
}
}
else if (key == '=') { // Jika tombol '=' ditekan
if (inputString.length() > 0 && operatorChar != 0) {
num2 = inputString.toFloat();
float result = calculate(num1, num2, operatorChar);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Hasil:");
lcd.setCursor(0, 1);
lcd.print(result);
newCalculation = true;
inputString = "";
operatorChar = 0;
delay(3000);
lcd.clear();
}
}
else if (key == 'C') { // Jika tombol 'C' ditekan
clearAll();
}
}
}
float calculate(float n1, float n2, char op) {
switch (op) {
case '+':
return n1 + n2;
case '-':
return n1 - n2;
case '*':
return n1 * n2;
case '/':
if (n2 != 0)
return n1 / n2;
else {
lcd.clear();
lcd.print("Error: Div 0");
delay(2000);
clearAll();
return 0;
}
default:
return 0;
}
}
void clearAll() {
inputString = "";
num1 = 0;
num2 = 0;
operatorChar = 0;
lcd.clear();
}