go_away

Author Topic: While loops  (Read 825 times)

0 Members and 1 Guest are viewing this topic.

Offline UnicornKingTopic starter

  • Beginner
  • *
  • Posts: 6
  • Helpful? 0
While loops
« on: October 11, 2009, 12:34:22 AM »
i was wondering if the while loop can be used to allow a program to have sort of a state of conciousness. meaning i want to be able to control a couple servos each with a button and not have to restart the program each time i do somthing( i'm using the axon micro controller) . How would my logic be structured? and in some sample code i see the while loops condition being the constant integer 1. what does this do?

Offline waltr

  • Supreme Robot
  • *****
  • Posts: 1,938
  • Helpful? 98
Re: While loops
« Reply #1 on: October 11, 2009, 08:25:45 AM »
The code:

while (1)
{
    ....
    other code
    ....
}

loops forever executing the 'other code' again and again.

this could be written:

a = 1
while (a)
{
    ....
    other code
    ....
    if buttonpushed {
        a = 0
    }
}
some other code

would exit the while loop when the button is pushed and execute the 'some other code'.
or this could be written as:

while (NOT buttonpushed )
{
    ....
    other code
    ....
}
some other code


Which would do the same thing as using the 'if buttonpushed' statement.

You would need the 'some other code' after the while loop to do something and not allow the code to execute undefined memory locations.

the 'some other code' could be:

StopMotors()
GOTO init

Note: code syntax is generic for purpose of showing logic.

Offline Kirk

  • Jr. Member
  • **
  • Posts: 44
  • Helpful? 2
Re: While loops
« Reply #2 on: October 12, 2009, 06:46:36 AM »
This is a very basic AND very important question.  Most computer programs have a start and an end. Almost all microcontroller programs should never quit.  So the idea is to loop forever.  There are several ways to do this.  Atmel (the maker of the chip on the Axon) recommends the following

Code: [Select]
main{
  // set up functions
  for(;;){
  // loop forever
}
Of course the while loop works fine.  It just takes a tiny bit more memory.

Kirk

PS.
 to understand the test structures of C, you should get a good C book.  I like the book C by example.  Also the Arduino web site has good references on all the control structures of C (but often some bad practices in the examples)

while will continue until the test in () evaluates to zero.  Zero is considered false. anything else is considered true.
The following all do the same thing
Code: [Select]
char a = 1;
while (a != 0) {
// do stuff the long way
}

char a = 1;
while (a) {
// do stuff but still waste some RAM
}

while (1) {
// do stuff
}




 


Get Your Ad Here