#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// กำหนดที่อยู่ I2C ของจอ LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
// กำหนดขาปุ่มที่ใช้
const int button1Pin = 2; // ปุ่มที่ 1
const int button2Pin = 3; // ปุ่มที่ 2
const int button3Pin = 4; // ปุ่มที่ 3
int button1State = 0; // ตัวแปรเก็บสถานะของปุ่มที่ 1
int button2State = 0; // ตัวแปรเก็บสถานะของปุ่มที่ 2
int button3State = 0; // ตัวแปรเก็บสถานะของปุ่มที่ 3
int count = 0; // ตัวแปรเก็บตัวเลขที่จะแสดงบน LCD
void setup() {
lcd.begin(16, 2); // เริ่มต้นการทำงานของจอ LCD ขนาด 16x2
lcd.backlight(); // เปิดไฟพื้นหลังของจอ LCD
// กำหนดขาปุ่มเป็นอินพุต
pinMode(button1Pin, INPUT);
pinMode(button2Pin, INPUT);
pinMode(button3Pin, INPUT);
}
void loop() {
// อ่านสถานะของปุ่ม
button1State = digitalRead(button1Pin);
button2State = digitalRead(button2Pin);
button3State = digitalRead(button3Pin);
// ตรวจสอบการกดปุ่มที่ 1 (เปิดโปรแกรม)
if (button1State == HIGH) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Starting..."); // แสดงข้อความ "Starting..."
delay(1000); // หน่วงเวลา 1 วินาที
lcd.clear(); // ล้างหน้าจอ
lcd.setCursor(0, 0); // ตั้งตำแหน่งที่จะแสดงข้อความใหม่
lcd.print("Count: 0 CM"); // แสดงค่าเริ่มต้นเป็น "Count: 0 CM"
}
// ตรวจสอบการกดปุ่มที่ 2 (เพิ่มตัวเลข)
if (button2State == HIGH) {
count++; // เพิ่มตัวเลขขึ้นทีละ 1
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Count: ");
lcd.print(count); // แสดงตัวเลข
lcd.print(" CM"); // แสดงหน่วย "CM"
delay(300); // หน่วงเวลาเพื่อหลีกเลี่ยงการอ่านค่าหลายครั้งจากการกดปุ่มนานเกินไป
}
// ตรวจสอบการกดปุ่มที่ 3 (ลดตัวเลข)
if (button3State == HIGH) {
count--; // ลดตัวเลขลงทีละ 1
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Count: ");
lcd.print(count); // แสดงตัวเลข
lcd.print(" CM"); // แสดงหน่วย "CM"
delay(300); // หน่วงเวลาเพื่อหลีกเลี่ยงการอ่านค่าหลายครั้งจากการกดปุ่มนานเกินไป
}
}