Shop OBEX P1 Docs P2 Docs Learn Events
nested loops in c-Propeller — Parallax Forums

nested loops in c-Propeller

gregmazarakisgregmazarakis Posts: 15
edited 2014-07-08 06:41 in Propeller 1
Can anyone help me with a nested while loop that blocks mij propeller chip?
/*
Test_Een_Stappenmotor

Herhalingen via while loop

Version 0.94 for use with SimpleIDE 9.40 and its Simple Libraries

*/

#include "simpletools.h" // Include simpletools
int I=20;
int m=0;
int r;
int main() // de main functie
{
while(1)
{
print("r = %d\n", r);
high(1);
while(m<2) //Aantal herhalingen
{
high(2);
for(int n = 1; n <= I; n++) // Count to ten
{
high(0); // Zet de pulsuitgang op 0
pause(300);
low(0); // Zet de pulsuitgang op 1
pause(300); // 0.5 s between reps
print("Stap = %d\n", n);
}
low(2);
low(1);
high(0);
print("aantal = %d\n", m+1);
pause(500);
m++;
}
}
}

Comments

  • Heater.Heater. Posts: 21,230
    edited 2014-07-07 11:50
    When m gets to 2 the "while(m<2)" can never do anything again so the "while(1)" just loops around and around doing nothing much.
  • gregmazarakisgregmazarakis Posts: 15
    edited 2014-07-08 03:54
    Hi Heater,
    Thanks very mutch for your prompt reply.
    I understand now what happened, but is there a better way to have nested "while's"?

    regards
    Greg
  • Heater.Heater. Posts: 21,230
    edited 2014-07-08 04:32
    "A better way?" - I have not looked to hard at your code or know what it is supposed to be doing. But your loops look fairly normal. It all depends what the problem is.

    I will say something about your for loop:

    When just using for loops for counting iterations it is common practice to count from zero and check for less than the maximum count. It's a bit less confusing for readers that way. Unless there really is a reason for wanting to start at 1 or some other value.

    Also if any values in your code are actually constants it is better to define them with "#define" rather than using a variable, again that makes life easier for the reader as he now knows these are supposed to be fixed values that will not change at run time.
    #define MAX_ITERATIONS 10
    
    for (int i = 0; i < MAX_ITERATIONS; i++)
    {
        // Bla bla
    }
    

    In general people like to see longer meaningful names for variables rather than just single character "m", "n". That makes the code easier for readers to understand and helps you when you are searching for names in an editor.
  • gregmazarakisgregmazarakis Posts: 15
    edited 2014-07-08 06:41
    Thanks very mutch it works perfectly.
Sign In or Register to comment.