For loop problem

Thread Starter

raw_653

Joined Feb 3, 2012
10
//sbit

//variables
int i=1 ;
//module

void flash (){
for (i=1; i<=128; i*=2);
{
portc =i;
delay_ms(1000);
}

}
//main
void main() {
Trisc=0;
portc=i;


//while
while (1)
{ flash ();
}

}


i was trying to make a loop to turn LEDs on in a sequence yet there is no output
any solutions ??

thanks )
 

hexreader

Joined Apr 16, 2011
581
Which processor chip are you using?

If it is an 8 bit device, then variable i should be declared as an unsigned char.

If it is 16 bit device then int should work (though unsigned int would be more logical)
 

hexreader

Joined Apr 16, 2011
581
The semicolon ends the for loop.

Without the semicolon, the block of code in braces becomes part of the for loop.

That is how C syntax is.
 

codehead

Joined Nov 28, 2011
57
I removed only the semi-colon at the end and it works
thanks a lot
why didn`t it work before ??
hexreader fixed it for you, but it's a good idea to stop and understand what you asked the compiler to do:

Rich (BB code):
for (i=1; i<=128; i*=2);
{
portc =i;
delay_ms(1000);
}
In the first line, you told it to start with i=1, then double it repeatedly as long as it was less than or equal to 128. On the final doubling, it hits 256 and that statement terminates.

Then you have a block of code that says to assign i (now 256) to portc, and delay for a second.

Note that there are times that you really do want a semi-colon after the "for" construct; in that case, everything's happening between the parenthesis. That's pretty rare though, and most people use a while statement in those cases, so a semi-colon after the closing parenthesis is extremely rare.
 
Top