Blink led with button

Hello everybody!
I am newbie on arduino. I am trying to set a scheme that allows me to push a button and do a led blinks.

I did it:

Code:

const int ledGreen = 2;
const int button =3;
int state=0;

void setup() {
  // put your setup code here, to run once:
 

  pinMode(ledGreen, OUTPUT);
  pinMode(button, INPUT);
  digitalWrite(ledGreen, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  
  state= digitalRead(button);
  if(state==1){
    digitalWrite(ledGreen, HIGH);
  }
  else{
    digitalWrite(ledGreen, LOW);
  }

}

But happened the opposite of what I expected, Led is always ON unless I push the button.
Could someone explain me why?

Look at your button's connection. The way you have it wired, pin 3 sees 5 volts when the button is not pressed. When you press the button, the pin is connected directly to ground, and the voltage the pin sees falls to zero. So your variable 'state' is LOW when the button is pressed and HIGH when released.

Hi,

You have confused between the HIGH and LOW of the pushbutton. Swap the condition on state variable.

Refer to : Arduino - Pushbutton

const int LEDout=12; //LED pin number 12 is our output
const int BUTTONin= 16; // A2 Pushbutton is our input
int val=0;

void setup()
{

pinMode(LEDout,OUTPUT);
pinMode(BUTTONin,INPUT);

}

void loop() {
val=digitalRead(BUTTONin);
if (val == HIGH) {
digitalWrite(LEDout,HIGH);}
else{
digitalWrite(LEDout,LOW);
}
}

Not sure @poddar_amrita why you posted that in a 2 1/2 year old thread.

  • Are you giving that code as a solution to the OP's (already answered) question? If so you should say which way your button's resistor is wired, since you didn't use the internal pullup
  • Or, are you asking a further question, if so what is it?

In either case, it's silly to just throw some code into a thread (even a current one, let alone such an old one) with no explanation....