Tugma bilan LED-ni yoqib-o‘chirish (On/Off)

Video
Elektr sxemasi

Manba kodi
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// Toggle an LED with a Button (On/Off)
4// ─────────────────────────────────────────
5// Each button press toggles the LED once (on/off). The code only catches
6// the moment of the press (LOW -> HIGH); holding the button does not make
7// the LED blink. The 50 ms wait ignores button bounce.
8//
9// Pins:
10// D13 -> Button, other leg to 5V
11// D13 -> 10k resistor to GND (pull-down)
12// D7 -> LED (with a 330 ohm resistor)
13
14int ledState = 0; // LED state: 0 = off, 1 = on
15int lastButton = 0; // Previous button reading
16
17void setup() {
18 pinMode(13, INPUT); // Button input (external pull-down)
19 pinMode(7, OUTPUT); // LED output
20}
21
22void loop() {
23 int button = digitalRead(13); // Read the button
24 if (button != lastButton) { // Button state changed
25 if (button == 1) { // Only at the press (LOW -> HIGH)
26 ledState = !ledState; // Flip the state
27 digitalWrite(7, ledState);
28 }
29 delay(50); // Short wait to skip the bounce
30 lastButton = button; // Store this reading
31 }
32}
33
Ko‘p so‘raladigan savollar
Debounce nima va u nega kerak?
Mexanik tugma bosilganda bir necha millisekund ichida bir necha marta ulanib-uziladi (sakrash, bouncing). Arduino buni bir necha bosish deb tushunishi mumkin va LED tasodifiy holatda qoladi. Debounce holat o‘zgargandan keyin qisqa vaqt (masalan, 50 ms) kutib, bu sakrashni e’tiborsiz qoldiradi.
Ba’zan LED o‘zgarmaydi yoki ikki marta o‘zgaradi. Nega?
Odatda debounce yo‘q yoki juda qisqa bo‘ladi. Bundan tashqari, faqat tugma «bosilgan» paytni aniqlash kerak (oldingi holat: LOW, yangi holat: HIGH); tugma bosib turilganda holat har siklda o‘zgarsa, LED miltillaydi va tasodifiy holatda qoladi.
Holat o‘zgaruvchisi nima uchun kerak?
U LED yoniq yoki o‘chiq ekanini eslab turadi. Har bir haqiqiy bosishda o‘zgaruvchi teskarisiga aylantiriladi (ledStatus = !ledStatus) va LED shunga qarab sozlanadi.
Bir nechta tugma bilan turli LED-larni boshqarsam bo‘ladimi?
Ha, har bir tugma uchun alohida pin, alohida oldingi holat va alohida LED holati o‘zgaruvchisini saqlash kifoya. Tugmalar ko‘p bo‘lsa, massivlar va millis() asosidagi debounce kodi tartibliroq bo‘ladi.
