Electronic – Arduino Code – simple if, else statement

arduinocmicrocontroller

Basically, I have two led lights connected to pin 2 (led 1) and pin 3 (led 2), and I want led 2 to light up every time led 1 lights up, and turn off every time led 1 turns off.

My code:

int led1=2;
int led2=3;

void setup()
{
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
}

void loop()
{
    if (digitalRead(led1 == HIGH))
    {
        digitalWrite(led2, HIGH);
    }
    else
    {
        digitalWrite(led2, LOW); //This line won't work.
    } 
    digitalWrite(led1, HIGH);
    delay(5000);
    digitalWrite(led1, LOW);
    delay(3000);
}

So after I upload this code, led 2 lights up whenever led 1 lights up, but led 2 wont turn off when led 1 turns off.

Best Answer

With the if() statement fixed as mentioned in another answer, it still won't work because you turn led1 on, then off at the end of the loop, so when the program gets back to the top of the loop, led1 is always off.

To get the effect you want, you need to do the if/else both after turning led1 on, and after turning led1 off.