I cant trace out the error..

I made a program to glow the led when the button is press and the led will turned off when the button is released.

But when i press the button the led continued to glow until i stop the program.

Kindly help me out to trace the error in my program.

int a = 0;

void setup() {
pinMode(2, INPUT);
pinMode(3, OUTPUT);
}

void loop() {
a = digitalRead(2);
if (a == HIGH){
digitalWrite(3,HIGH);

}
else{
digitalWrite(3,LOW);

}
}

I also attached the proteus simulation circuit.

void loop() {
  a = digitalRead(2);
  digitalWrite(3, LOW);
  if  (a == LOW) {
    while (digitalRead(2) == LOW) {    //waiting for the button to be unpressed
      digitalWrite(3, HIGH);
    }
  }   
}

try this :slight_smile: This code should light the LED and the wait for the button to be unpressed to switch off the LED. And in the future use code tag (the </> sign) while you want to post your code. And Thanks!

PS It would be much simpler if you will use something like this:

#define Button 2
#define LED 3

int button;

And then you can use it in the code:

button = digitalRead(Button);
digitalWrite(LED, LOW);
a = digitalRead(2);
 if  (a == HIGH){
    digitalWrite(3,HIGH);
  
  }

Do you have a pull down resistor on the input or is it floating at an unknown, possibly HIGH voltage ?

Try

 pinMode(2, INPUT_PULLUP);

to activate the built in pull up resistor and reverse the logic of your test on the state of the input

But first, connect your pushbutton to GND instead of 5V.