#include <LiquidCrystal.h>
// กำหนดขาเชื่อมต่อ LCD
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int buttonPin = 7; // ขาปุ่ม
const int potPin = A0; // ขา potentiometer
int buttonState = 0;
int lastButtonState = 0;
int mode = 0; // 0 = หน้าจอเริ่มต้น, 1 = time, 2 = volt
unsigned long startMillis = 0;
void setup() {
lcd.begin(16, 2);
pinMode(buttonPin, INPUT);
// เริ่มต้นด้วยข้อความ "Press Button" กลางแถวที่ 1
lcd.setCursor(2, 1); // ช่องที่ 2 ของแถวที่ 1 (เริ่มที่ 0)
lcd.print("Press Button");
}
void loop() {
buttonState = digitalRead(buttonPin);
// ตรวจจับการกดปุ่ม
if (buttonState == HIGH && lastButtonState == LOW) {
mode++;
if (mode > 2) mode = 1;
lcd.clear();
delay(200); // ป้องกันการเด้งของปุ่ม
if (mode == 1) {
startMillis = millis(); // เริ่มนับเวลาเมื่อเข้าโหมด time
}
}
lastButtonState = buttonState;
if (mode == 1) {
// โหมด time: แสดง time in second ตรงกลางแถว 0, นับ 0-3 กลางแถว 1
lcd.setCursor(1, 0); // ปรับให้อยู่กลางแถว 0
lcd.print("time in second");
unsigned long elapsed = millis() - startMillis;
int seconds = elapsed / 1000;
if (seconds <= 3) {
lcd.setCursor(7, 1); // กลางแถว 1 (ช่องที่ 7)
lcd.print(" ");
lcd.print(seconds);
lcd.print(" ");
}
}
else if (mode == 2) {
// โหมด volt: แสดง Volt measure ตรงกลางแถว 0, ค่า Volt กลางแถว 1
lcd.setCursor(2, 0); // กลางแถว 0
lcd.print("Volt measure");
int analogValue = analogRead(potPin);
float voltage = analogValue * (5.0 / 1023.0);
lcd.setCursor(5, 1); // กลางแถว 1
lcd.print(voltage, 2);
lcd.print(" V ");
}
}