I have a simple project I'm using to work with "if/else" statement for the first time. I'm using a ELEGOO UNO R3 and the project consist of two LEDs. The goal is to have LED(w) flash on and off consecutively with a 500 millisecond delay. Meanwhile, the "if/else" statement should be counting the cycles and setting the LED(r) to HIGH once LED(w) becomes equal to five on/off cycles. The circuit and sketch actually work, however the LED(r) is turning on on the sixth on/off cycle, instead of the fifth. I feel like I'm overlooking something very simple here. Here is the sketch. Thanks for your help!
int w = 2;
int r = 4;
int t = 500;
int c = 0 ;
void setup() {
pinMode (w, OUTPUT);
pinMode (r, OUTPUT);
Serial.begin(9600);
}
void loop() {
Serial.print(c);
digitalWrite (w, HIGH);
delay (t);
digitalWrite (w, LOW);
delay (t);
c = (c + 1);
if (c == 5) {
digitalWrite (r, HIGH);
}
else (r, LOW);
}
Keep on trying and exploring code and new things. You learn along the way. Please make the text layout look good. Use always the same style, with the same indents, spacing, and so on. That will help to see what a sketch is doing.
1). As @gcjr pointed out you are missing the digitalWrite statement
2). You are only checking counter AFTER you have blinked for the 5th time... so it actually comes on at the start of the 6th cycle. Move the c = c+1 and the if statement to the top of loop it should work as expected.
That would work... but it's not a great solution IMHO... you are setting a variable to turn on LED 2 out of sync with LED 1. c no longer has a consistent value during the loop cycle. So if for example you were to add further code that also relied on "c" then you now need to be aware of that.