8 years, 8 months ago.

for loop not working.

Hi,

Working from Bert van Dam's book, I'm trying to establish a FOR-loop.

However, it doesn't seem to work.

I've tried echoing the FOR variable content to pc.printf() but all I get is the value at which the loop is supposed to stop.

I also incorporated 2 leds: LED1 should blink for every time the loop is run LED2 should blink for every time the loop restarts.

#include "mbed.h"

Serial pc(USBTX, USBRX);
DigitalOut myled1(LED1);
DigitalOut myled2(LED2);

int main()
{
    int h;
    while(1)
    {
        h = 0;
        myled2 = 1;
        wait( .2);
        myled2 = 0;
        wait( .2);
        for( h = 0; h < 10; h++ );
        {
            pc.printf(" %i \r\n", h);
            myled1 = 1;
            wait( .2);
            myled1 = 0;
            wait( .2);
        }       /// endfor
    }       /// endwhile
}       /// endmain

After adding the 2 leds and the blink routines, pc.printf only outputs 10. Also I only get alternately blinking LEDs, so I suppose FOR-loop is only running once

where am I going wrong? device is a LPC1768

Kind regards, marout

2 Answers

8 years, 8 months ago.

That took me a few checks before I saw it: After your for loop you have a semicolon (;), the for statement is one of those where you should (generally) not put it, since that ends the statement right there instead of including the actual code to run in the for loop. Effectively what you wrote is equivalent to:

for (h = 0; h < 10; h++) 
  {
  }



//And then completely unrelated to that loop
pc.printf(" %i \r\n", h);
myled1 = 1;
wait( .2);
myled1 = 0;
wait( .2);

Edit: Stupid Wim :(

Accepted Answer

Thanks Mr Huiskamp and Mr Olieman.

That surely was a "D'oh!"-moment.... :)

posted by Marout Yasuo Sluijter-Borms 28 Mar 2016
8 years, 8 months ago.

Remove the ; at the end of the

for (h=0;h <10;h++)

That effectively means you have an empty loop that runs 10 times and the printf only shows the end value of h.

See rely to Mr Olieman's answer.

However; it puzzles me that the compiler did not complain about the curly brackets around what was supposed to be the loop operations (flashing led1).

posted by Marout Yasuo Sluijter-Borms 28 Mar 2016

c allows curly brackets around blocks of code, what you had was perfectly valid and so the compiler didn't complain.

About the only time I can think of that you would use this is if you wanted to define a local variable that is only visible for part of a function. The original c standard only allowed variables to be defined at the start of the block of code, the brackets allowed a way to define blocks of code within each other.

posted by Andy A 29 Mar 2016