# For loop help.

Status
Not open for further replies.

#### be80be

##### Well-Known Member
I did this last night the first for loop works the second one doesn't.
I can't for the life of me figure it out.
Code:
 PWM1_Initialize();
while (1)
{
uint16_t dutycycle;
{
__delay_ms (500);
}

{
}
}

Last edited:

#### be80be

##### Well-Known Member
If I just do this loop it just sits here full on
Code:
while (1)
{
uint16_t dutycycle;

{
}
}

#### Nigel Goodwin

##### Super Moderator
Your variable test is wrong - you're testing for it been greater than 0x3ff, and it never is as it starts at that, and then decreases.

#### be80be

##### Well-Known Member
I kind of was thinking that but I tried the => it didn't work too. I'm going to test for less
thanks this c stuff is not that easy i looked up for loops nothing in xc8 about going less
lust ++ lol

Last edited:

#### Pommie

##### Well-Known Member
Assuming you want the loop to go from 0 to 0x3ff then your for loop should be,
Code:
    for(load=0;load<0x400;load++){
To go backwards is a little tricky with unsigned integers as you can't test for -1. So a test for above 0x400 will detect when it's gone negative.
Code:
    for(load=0x3ff;load<0x400;load--){
The above loop will terminate when load is 0xffff and therefore no longer less than 0x400.

Hope that makes sense.

Mike.
Edit, it would make the code much more readable to test for not equal to oxffff;
Code:
    for(load=0x3ff;load!=0xffff;load--){

Last edited:

#### be80be

##### Well-Known Member
Yep the 0 test don't seem to work and the arduino type test don't work with xc8 no errors just don't do nothing.
>= didn't work Im going to try it your way mike thanks

#### be80be

##### Well-Known Member
I'm i was just testing the load be from
0 to 1023 from the adc

#### Beau Schwabe

##### Active Member
Shouldn't the second one just read ...

Code:
      for (load = 0x03FF; load > 0; load--)
{
}

#### Pommie

##### Well-Known Member
Shouldn't the second one just read ...

Code:
      for (load = 0x03FF; load > 0; load--)
{
}
That will only execute from 0x3ff down to 1 - not 0 as required.

Mike.

#### Pommie

##### Well-Known Member
For anyone struggling with for loops in C,

Try going to https://www.onlinegdb.com/
and copy this into the page,
Code:
#include <stdio.h>
#include <stdint.h>

int main(){
uint16_t i,j;
for (i = 0x03FF; i != 0xffff; i--){
j=i;
}
printf("Value of i is %d (0x%x) and j is %d (0x%x)",i,i,j,j);
return 0;
}
Because the test (i!=0xffff) is done after the decrement the value of J is zero and i is 0xffff.
You can set breakpoints at various points and see whats happening.
Happy playing.

Mike.

Last edited:

#### be80be

##### Well-Known Member
Mike thats a great site I been looking for just a way to do that writing files and testing with C on linux works but that is easy put code and see what happens cool Thinks Mike

Status
Not open for further replies.