This line:
if (digitalRead(led1 == HIGH))
Is incorrect. This should be:
if (digitalRead(led1) == HIGH)
Because you want to check the return value of digitalRead()
. However, this doesn't cause the problem.
You can see the real problem when you try to think as the microcontroller. It does these steps (I start at digitalWrite(led1, HIGH)
):
- Set LED1 high
- Wait
- Set LED1 low
- Wait
- Check:
- If LED1 is high, set LED2 high
- If LED1 is low, set LED2 low
- Go to 1.
When 5 is executed, the value of LED1 is always low. 5.2 will always be executed, 5.1 never. If you want to achieve this programmatically, you could use something like this:
void loop() {
digitalWrite(led1, HIGH);
digitalWrite(led2, HIGH);
delay(5000);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
delay(3000);
}
If you want to do this with an if, you can either do something like this:
void calcLed2() {
if (digitalRead(led1) == HIGH) {
digitalWrite(led2, HIGH);
} else {
digitalWrite(led2, LOW);
}
}
void loop() {
digitalWrite(led1, HIGH);
calcLed2();
delay(5000);
digitalWrite(led1, LOW);
delay(3000);
}
Or put the if loop in the loop()
(i.e. without a function call).
It would also be good practice if you set the initial state of the machine in your setup()
. For example, set both LEDs high or both LEDs low. If you don't do this, it will work, but might give unexpected results in the first few seconds.