Repeate code a set number of times (Urgent)

Is there a way to make this look more neat and tidy, in place of this mess?

//Tree short led blinks

digitalWrite (LED_RED, HIGH);
delay(500);
digitalWrite (LED_RED, LOW);
delay(500);
digitalWrite (LED_RED, HIGH);
delay(500);
digitalWrite (LED_RED, LOW);
delay(500);
digitalWrite (LED_RED, HIGH);
delay(500);
digitalWrite (LED_RED, LOW);

yes.
method 1:

for(int i = 0; i < number of repeated things; i++)
{

if(i%2)
digitalWrite (LED_RED, HIGH);
else
digitalWrite (LED_RED, LOW);

delay(500);

}

if low and high are set up in a friendly way (maybe they are the constants 1 and zero?) you can eliminate the condition.
method 2:

for(int i = 0; i < number of repeated things; i++)
{
digitalWrite (LED_RED, i%2);
delay(500);
}

or you can double down:

method 3

for(int i = 0; i < number of repeated things/2; i++)
{
digitalWrite (LED_RED, HIGH);
delay(500);
digitalWrite (LED_RED, LOW);
delay(500);
}

if you didnt have the delay, and needed this to be as fast as it could be, the way you have could also be the best way, this is called 'unrolling' a loop and is sometimes the best approach if the number of iterations is small and the need for performance is important.
Last edited on

1
2
3
4
5
6
for (int i = 0; i < 3; i++) {
  digitalWrite (LED_RED, HIGH);
  delay(500);
  digitalWrite (LED_RED, LOW);
  delay(500);
}
It worked! Thank you so much for taking time to answer this silly question!

I was still writing updates and you are already done, so you may want to look at the 3 methods I gave just for future reference. I personally prefer method 2 if its doable with your high/low values (unclear).
I think I may look at them all, and in the doing trying to understand when to use them. The life of a newbie is good isn't it? You write your problem here, and "poof" you learned something new. Thx btw!
Topic archived. No new replies allowed.