Introduction: On Off LED With 1 Button
I am not good at English...But I will try my best.
Many guys(including me :) try to on and off a LED with 1 push button. But due to some logical error in the IDE, it can not be happened. Sometimes, the LED comes to life when the button is pressed; but immediately becomes off when the button is released. I tried a lot and at last made a solution. In this instructable, you will be able to switch on the LED when the button is pressed once, and switch it off when the button is pressed twice. I will try my best to wxplain the code. Best Of Luck.
Step 1: Components
Arduino Uno
LED
330ohm Resistor
Simple push button
10k Resistor
Jumper wires
Step 2: Wiring
Make the connection as below:
LED + to 330ohm Resistor to Arduino pin 3
LED - to GND
Button(pole1) to Arduino 5v
Button(pole2) to Arduino pin 2
Now ground the button through a 10k Resistor.
Step 3: Coding
Copy the below Code or Download the ino file:
/*
* Programmed by: Md. Mehrab Haque
* Dhaka, Bangladesh.
* Phone: +8801795415378 */
int stateNow = 0;
int stateBefore = 0;
int i = 0;
int j = 0;
void setup() {
pinMode (2, INPUT);
pinMode (3, OUTPUT);
}
void loop() {
stateNow = digitalRead(2);
if (stateNow != stateBefore) {
if (stateNow==HIGH and i==0) {
digitalWrite (3, HIGH);
j=1;
}
else if (stateNow==LOW and j==1) {
i=1;
}
else if (stateNow==HIGH and i==1) {
digitalWrite (3, LOW);
j=0;
}
else if (stateNow==LOW and j==0) {
i=0;
}
}
stateBefore=stateNow;
}
Attachments
Step 4: Upload the Code and Have Fun !!!
If you can not understand any line of the code, then please comment.....I will solve it in no time.