#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // กำหนดที่อยู่ I2C และขนาดของ LCD
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
byte rowPins[ROWS] = {13, 12, 14, 27}; // ขา GPIO สำหรับ Row
byte colPins[COLS] = {16, 17, 18, 19}; // ขา GPIO สำหรับ Column
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String input1 = "";
String input2 = "";
char operation = '\0';
bool isSecondInput = false;
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Calculator");
delay(2000);
lcd.clear();
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
if (isSecondInput) {
input2 += key;
} else {
input1 += key;
}
lcd.setCursor(0, 0);
lcd.print(input1 + " " + operation + " " + input2);
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
if (!isSecondInput && input1 != "") {
operation = key;
isSecondInput = true;
}
lcd.setCursor(0, 0);
lcd.print(input1 + " " + operation);
} else if (key == '=') {
if (input1 != "" && input2 != "" && operation != '\0') {
float num1 = input1.toFloat();
float num2 = input2.toFloat();
float result = 0.0;
switch (operation) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if (num2 != 0) result = num1 / num2;
else lcd.print("Err: Div by 0");
break;
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Result: ");
lcd.setCursor(0, 1);
lcd.print(result);
// เคลียร์ค่าทั้งหมด
input1 = "";
input2 = "";
operation = '\0';
isSecondInput = false;
delay(3000); // แสดงผลลัพธ์ 3 วินาที
lcd.clear();
}
} else if (key == 'C') { // เคลียร์ค่าทั้งหมดเมื่อกดปุ่ม C
input1 = "";
input2 = "";
operation = '\0';
isSecondInput = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Cleared");
delay(1000);
lcd.clear();
}
}
}