why digitalRead not working?

goal: wait 2s, turn led on, wait 2s, turn led off, repeat..

but my led just turns on after 2s and stays on.

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



void loop()
{
  delay(2000);
  if(digitalRead(2)==HIGH)
  {
    digitalWrite(2,LOW);
  }
  
  if(digitalRead(2)==LOW)
  {
    digitalWrite(2,HIGH);
  }
  
}

what's wrong?

After you write it LOW the second condition is then run and finds it low so sends it high again. all within microseconds.

To fix your code make the second if an else if, or simpler altogether use

void loop()
{
  digitalWrite(2,!digitalRead(2));
  delay(2000);
}

goal: wait 2s, turn led on, wait 2s, turn led off, repeat..

So why do you need to read anything?

why digitalRead not working?

digitalRead is working. The Arduino would not be very popular if it didn't.

Try this

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

void loop() {
delay(2000); // wait for 2 seconds
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000); // wait for 2 seconds
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
}

Isn't there an example sketch that does that?

[quote author=Nick Gammon link=msg=2082269 date=1423423784]
Isn't there an example sketch that does that?
[/quote]It's almost like the blink example but much more sophisticated, because the delay is 2 seconds. :wink:

The next step should be to figure out how to do this without the

delay(2000)

in it.

I know! Let's call it "Blink Without Delay"! :smiley: