
वीडियो
सर्किट डायग्राम

सोर्स कोड
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
FAQ
डिबाउंसिंग क्या है और यह क्यों ज़रूरी है?
मैकेनिकल बटन दबाने पर वह कुछ मिलीसेकंड के अंदर कई बार खुलता और बंद होता है (बाउंसिंग)। Arduino इसे कई बार दबाना समझ सकता है और LED किसी बेतरतीब स्थिति में रह जाता है। डिबाउंसिंग स्थिति बदलने के बाद थोड़ी देर (जैसे 50 ms) रुककर इस उछाल को नज़रअंदाज़ करता है।
कभी LED नहीं बदलता या दो बार बदल जाता है, ऐसा क्यों?
आम तौर पर डिबाउंसिंग नहीं होता या बहुत छोटा होता है। इसके अलावा आपको सिर्फ़ बटन के "दबने" का पल पकड़ना है (पिछली स्थिति: LOW, नई स्थिति: HIGH); अगर बटन दबाए रखने पर हर साइकिल में स्थिति बदलती है, तो LED टिमटिमाएगा और किसी बेतरतीब स्थिति में रह जाएगा।
स्टेट वेरिएबल किस काम आता है?
यह याद रखता है कि LED चालू है या बंद। हर सही दबाव पर वेरिएबल उल्टा कर दिया जाता है (ledStatus = !ledStatus) और LED उसी के हिसाब से सेट होता है।
क्या कई बटनों से अलग-अलग LED कंट्रोल किए जा सकते हैं?
हाँ, हर बटन के लिए अलग पिन, अलग पिछली स्थिति और अलग LED स्टेट वेरिएबल रखना काफ़ी है। अगर बहुत सारे बटन इस्तेमाल कर रहे हैं, तो ऐरे और millis() पर आधारित डिबाउंसिंग कोड ज़्यादा व्यवस्थित रहेगा।
