For loop problem

Discussion in 'Programmer's Corner' started by raw_653, Feb 3, 2012.

  1. raw_653

    Thread Starter New Member

    Feb 3, 2012
    10
    0
    //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 )
     
  2. hexreader

    Active Member

    Apr 16, 2011
    250
    82
    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)
     
  3. raw_653

    Thread Starter New Member

    Feb 3, 2012
    10
    0
    I am using PIC16F877A
     
  4. hexreader

    Active Member

    Apr 16, 2011
    250
    82
    Then i should be unsigned char.

    Also you should remove the semi-colon at the end of the line of your "for" statement
     
    raw_653 likes this.
  5. raw_653

    Thread Starter New Member

    Feb 3, 2012
    10
    0
    I removed only the semi-colon at the end and it works
    thanks a lot
    why didn`t it work before ??
     
  6. hexreader

    Active Member

    Apr 16, 2011
    250
    82
    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.
     
  7. raw_653

    Thread Starter New Member

    Feb 3, 2012
    10
    0
    i see
    thanks :)
     
  8. codehead

    Member

    Nov 28, 2011
    56
    11
    hexreader fixed it for you, but it's a good idea to stop and understand what you asked the compiler to do:

    Code ( (Unknown Language)):
    1.  
    2. for (i=1; i<=128; i*=2);
    3. {
    4. portc =i;
    5. delay_ms(1000);
    6. }
    7.  
    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.
     
    raw_653 likes this.
Loading...