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.

Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

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;

}

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.

Be the First to Share

    Recommendations

    • Made with Math Contest

      Made with Math Contest
    • Multi-Discipline Contest

      Multi-Discipline Contest
    • Robotics Contest

      Robotics Contest

    6 Discussions

    0
    None
    amason101070

    Question 9 months 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

    0
    None
    Anwarul Bashir

    Question 11 months 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.

    0
    None
    Young genius Md Mehrab Haque

    Reply 3 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!