1

I'm completely new to this world, so probably my question would sound noobish, but here it is:

I'm trying to make a led blinking just for 5 times by calling a "for" cycle inside void loop(). The confirmation of the successful cycle would come from the Serial Monitor which will print "let's star over", and at the end of each blinking cycle, it will print the text "cycle done".

The point is that my code doesn't work, the led remain switched ON and the serial monitor blank. What is wrong with it?

int ledred = 3;
int count = 5;

void setup() {
  digitalWrite(ledred, LOW);
  pinMode(ledred, OUTPUT);

}

void loop() {


    blinkingred(ledred, count);
    Serial.println("let's start over")

}

void blinkingred(int ledred, int count) 
{       
  for(byte i=0; i == count; i++)
  {
        digitalWrite(ledred, HIGH);
        delay(1000);
        digitalWrite(ledred, LOW);
        delay(1000);
        Serial.println("Cycle done !");
  }
}
1

There's two things wrong with your sketch - one fatal and one that is more confusing for humans.

First the fatal problem:

for(byte i=0; i == count; i++)

That for loop is never going to do anything. The way it is written it will loop only while i is equal to count (0 == 5) which it never will. Instead you need to loop while i is less than count:

for(byte i=0; i < count; i++)

The second issue is that you have named your function parameter variables the same as your global variables. While this is syntactically valid (the local variables will override the global ones) it is incredibly confusing for people to follow what is what and should be avoided at all costs.

-1

the simplest would be to unroll your loop and repeat the code 5 times.

  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);

hard to get that wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.