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.
8 Discussions
1 year ago
can i use one push button for start and end.. like smart shopping trolly i want that i give only one push button for shopping start and for shopping end..so can i do this by using ur code??
Question 1 year ago on Step 1
how could i replace the button with a remote? so that i can press a button from across the room to turn the led on?
Question 2 years ago
This worked just as you explained. How can I make the LED blink when i turn it on. I am trying to achieve different blinking speeds, but for now would love to know how to make the led blink when i press the button to turn it on. Any help would be greatly appreciated. Thanks for this tutorial!
Ron
Question 2 years ago on Step 1
Try using a photoelectric diode. When the room gets dark, the led will automatically turn on, and when the room gets bright, it'll turn off.
4 years ago
Thanks for your feedback
Reply 4 years ago
amazing! I wanna learn code but I really like hardware I'm like geeking out right now, just found this site. OMG so cool!
Reply 4 years ago
I also learned about arduino and robotics from instructables...it is best.
4 years ago
Good intro Arduino tutorial.