Missing something in my "if" condition code

Hi, all.

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); 

}


did you mean

   else
       digitalWrite (r, LOW);
1 Like

There are many solutions, more than a dozen, and this is one in the Wokwi simulator: https://wokwi.com/projects/342283355404894803
Click on the Start button to see what it does.

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.

2 problems...

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.

3). The code indentation is bonkers.

1 Like

Welcome to the forum
Ctrl T for automatic code formatting
Well done for using code tags

Or initialise c to 1 not 0 where you declare it.

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.

Yes, I was just pointing out that computers count from zero but most people start from 1 and that can cause problems until you get used to it.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.