For statement problem

Right now I’m trying to flash an LED 5 times using a for statement. As I read my code below the LED should flash five times and then the condition should be met in the for statement and there should be no further flashing.
The problem is my LED just keeps flashing infinitely…

 int led = D7;
    
    void setup() {
        pinMode(led, OUTPUT);
        digitalWrite(led, LOW);
        delay(2000);
    }
    
    void loop() {
        
        for (int i=0; i<5; i++) {
            digitalWrite(led, HIGH);
            delay(1000);
            digitalWrite(led, LOW);
            delay(1000);
        }
    
    }

Hi @Owen,

The loop() function will be called repeatedly forever, if you want your flashing to stop, try setting a state outside the scope of the loop, e.g.:

   bool done = false;
   void loop() {
        if (done) { return; }
        for (int i=0; i<5; i++) {
            digitalWrite(led, HIGH);
            delay(1000);
            digitalWrite(led, LOW);
            delay(1000);
        }
        once = true;
    }

Your LED flashes 5 times, then the for loop exits, the Spark does some housekeeping, and then re-runs loop, which re-runs your for loop, your LED flashes 5 times…

If you make “i” a global variable then it should only flash the LED 5 times.

EDIT: Dave was quicker than me!

2 Likes

If you’re going to use the if statement anyhow, wouldn’t this work just as well? (I could be mistaken!)

int led = D7;
int i = 0;

void setup() {
    pinMode(led, OUTPUT);
    digitalWrite(led, LOW);
    delay(2000);
}
    

void loop() {

    if (i < 5) {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
	i++;
    }

}
2 Likes

It should be stated that this doesn't work because you've declared the i variable locally and are initializing it in the for() loop. So every time your loop() is run, the for() loop is run and the i variable was getting set to 0. If you create and initialize it globally, you won't have this problem.

If you just declared your i variable globally it would solve the problem, and then write your for() loop like this:
for ( ; i<5; i++) {

Also, int is a signed 32=bit integer which takes up 4 bytes of RAM. You can save 3 bytes of RAM by declaring it as uint8_t which only consumes 1 byte of RAM... as long as you don't exceed a count of 255.

2 Likes

Hi,
Would it also work if he moves the for loop to the setup()?
Thanks,
/N

1 Like

Yes it would :slight_smile: Good suggestion also.

1 Like