#include <LiquidCrystal.h>
#include <Keypad.h>
// Inisialisasi objek LCD dan Keypad
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);
const int ROW_NUM = 4; // Jumlah baris keypad
const int COLUMN_NUM = 4; // Jumlah kolom keypad
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3','C'},
{'4','5','6','+'},
{'7','8','9','-'},
{' ','0',' ','='}
};
byte pin_rows[ROW_NUM] = {5, 4, 3, 2};
byte pin_column[COLUMN_NUM] = {A3, A2, A1, A0};
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
// Variabel untuk menyimpan operand dan operator
String operand1 = "";
String operand2 = "";
char oper = ' ';
bool newCalculation = true; // Perhitungan baru
void setup() {
lcd.begin(16, 2); // Inisialisasi LCD 16x2
lcd.print("Kalkulator");
delay(1000);
lcd.clear(); // Membersihkan layar LCD
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
// Fungsi input tombol kalkulator
handleCalculator(key);
}
}
void clearCalculator() { // Menghapus semua variabel
operand1 = "";
operand2 = "";
oper = ' ';
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Cleared");
delay(500);
lcd.clear();
}
void setOperator(char op) {
if (newCalculation) {
lcd.clear();
newCalculation = false;
}
if (operand1 != "") {
oper = op;
lcd.print(op);
}
}
void appendOperand(char digit) {
if (newCalculation) {
lcd.clear();
newCalculation = false;
}
if (oper == ' ') {
operand1 += digit;
} else {
operand2 += digit;
}
lcd.print(digit);
}
// Melakukan Perhitungan Angka yang di inputkan
void performCalculation() {
if (operand1 != "" && operand2 != "" && oper != ' ') {
// Konversi String (operand) ke Integer dan Hasilnya disimpan dalam variabel num
int num1 = operand1.toInt();
int num2 = operand2.toInt();
int result = 0;
if (oper == '+') {
result = num1 + num2;
} else if (oper == '-') {
result = num1 - num2;
}
lcd.clear();
lcd.print("= ");
lcd.setCursor(2, 0);
lcd.print(result);
// Reset variabel untuk kalkulasi selanjutnya
newCalculation = true;
operand1 = String(result);
operand2 = "";
oper = ' ';
}
}
// Fungsi untuk menangani input tombol kalkulator
void handleCalculator(char key) {
if (key == 'C') {
clearCalculator();
} else if (key == '=') {
performCalculation();
} else if (key == '+' || key == '-') {
setOperator(key);
} else {
appendOperand(key);
}
}