ควบคุม LED ด้วยปุ่มกดบน ESP32 (กดสลับเปิดปิด)
ทุกครั้งที่กดปุ่ม LED จะเปลี่ยนสถานะ ถ้าติดอยู่จะดับ ถ้าดับอยู่จะติด เป็นรูปแบบการสลับสถานะที่ใช้กันทั่วไป เราใช้การกรองสัญญาณเด้งของปุ่มกดเพื่อลดสัญญาณรบกวนจากหน้าสัมผัส ทำให้กด 1 ครั้งเปลี่ยนสถานะเพียง 1 ครั้ง

วิดีโอ
แผนผังวงจร

ซอร์สโค้ด
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// ESP32 LED Control with Pushbutton (Toggle)
4// ─────────────────────────────────────────
5// Each press of the button toggles the LED: on becomes off, off becomes
6// on. A 50 ms debounce makes sure one press gives exactly one toggle.
7//
8// Pins:
9// GPIO 5 -> Red LED (with a 220 ohm resistor)
10// GPIO 4 -> Button (other leg to GND)
11
12const int LED_PIN = 5; // LED output
13const int BUTTON_PIN = 4; // Button input
14
15bool ledState = false; // Is the LED on now
16bool lastButton = HIGH; // Previous button reading
17bool stableButton = HIGH; // Stable (debounced) button state
18unsigned long lastChange = 0; // Last time the reading changed (ms)
19const unsigned long DEBOUNCE = 50; // Debounce time (ms)
20
21void setup() {
22 pinMode(LED_PIN, OUTPUT);
23 pinMode(BUTTON_PIN, INPUT_PULLUP); // Reads HIGH when not pressed
24}
25
26void loop() {
27 bool buttonState = digitalRead(BUTTON_PIN);
28
29 // Restart the timer whenever the reading changes
30 if (buttonState != lastButton) lastChange = millis();
31
32 // A reading that stays the same for DEBOUNCE ms counts as stable. The LED toggles once, only when
33 // the stable state turns LOW (a new press).
34 if (millis() - lastChange > DEBOUNCE && buttonState != stableButton) {
35 stableButton = buttonState;
36 if (stableButton == LOW) {
37 ledState = !ledState;
38 digitalWrite(LED_PIN, ledState);
39 }
40 }
41 lastButton = buttonState;
42}
43
FAQ
ควรตั้งเวลากรองสัญญาณเด้งของปุ่มกดนานเท่าไร?
สำหรับปุ่มกดส่วนใหญ่ เวลา 20–50 ms ก็เพียงพอ ถ้าสั้นเกินไปจะยังตรวจจับสัญญาณเด้งอยู่ แต่ถ้านานเกินไปอาจพลาดการกดติดกันอย่างรวดเร็ว
ควรตรวจจับสถานะไหนเพื่อสลับเปิดปิด?
ตรวจจับเฉพาะจังหวะที่ปุ่ม "ถูกกด" ซึ่งเป็นการเปลี่ยนจาก HIGH เป็น LOW หากใช้ INPUT_PULLUP ให้เก็บสถานะก่อนหน้าของปุ่มไว้ในตัวแปร เพื่อไม่ให้ LED สลับสถานะซ้ำๆ ขณะกดปุ่มค้างไว้
ใช้ `delay()` กรองสัญญาณเด้งของปุ่มกดได้ไหม?
ใช้ได้กับโปรเจกต์ง่ายๆ แต่ delay() จะหยุดรอใน loop() ที่กำลังทำงาน ทำให้คำสั่งอื่นในลำดับเดียวกันล่าช้า ส่วนงานอื่นของ ESP32 ยังทำงานได้ การจับเวลาด้วย millis() จึงเหมาะกับการทำงานภายใน loop() โดยไม่ต้องหยุดรอ
ให้ LED จำสถานะล่าสุดหลังปิดแล้วเปิดเครื่องใหม่ได้ไหม?
ได้ บน ESP32 ใช้ไลบรารี Preferences บันทึกสถานะลงในหน่วยความจำที่เก็บข้อมูลได้แม้ไม่มีไฟเลี้ยง แล้วอ่านค่าตอนเริ่มทำงานได้ แม้ไฟดับแล้วกลับมา LED ก็จะเริ่มด้วยสถานะล่าสุด
