DO…LOOP

BS2 icon BS2e icon BS2sx icon BS2p icon BS2pe icon BS2px icon {PBASIC 2.5}

DO...LOOP Example

 

 

 

Syntax:

DO { WHILE | UNTIL condition(s) }
     Statement(s)
   LOOP { WHILE | UNTIL condition(s) }

Function

Create a repeating loop that executes the program lines between DO and LOOP, optionally testing before or after the loop statements

Quick Facts

  BS2 Family
Maximum nested loops 16
WHILE Condition evaluation Run loop if Condition evaluates as True (1)
UNTIL Condition evaluation Terminate loop if Condition evaluates as True (1)
Related Commands

EXIT, FOR…NEXT

Explanation

DO...LOOP loops let your program execute a series of instructions indefinitely, or until a specified condition terminates the loop. The simplest form is shown here:

Error_Message:
  DO
    DEBUG "Error...", CR
    PAUSE 2000
  LOOP

In this example the error message will be printed on the DEBUG screen every two seconds until the BASIC Stamp is reset. Simple DO...LOOP loops can be terminated with EXIT. For example:

Error_Message:
  DO
    DEBUG "Error...", CR
    PAUSE 1000
    IF (AckPin = 0) THEN EXIT                   ' wait for user button press
  LOOP
  GOTO Initialize                               ' re-initialize system

In this case the loop will continue until the pin named AckPin is pulled low, then the loop will terminate and continue at the line GOTO Initialize.

More often than not, you will want to test some condition to determine whether the loop code should run or continue to run. A loop that tests the condition before running loop code is constructed like this:

reps    VAR     Nib

Print_Stars:
  DO WHILE (reps < 3)                           ' test before loop statements
    DEBUG "*"
    reps = reps + 1
  LOOP

In this program the loop code DEBUG "*" will not run unless the WHILE condition evaluates as True. Another way to write the loop is like this:

reps    VAR     Nib

Print_Stars:
  DO
    DEBUG "*"
    reps = reps + 1
  LOOP UNTIL (reps >= 3)                        ' test after loop statements

The difference is that with this loop, the loop statements will always run at least once before the condition is tested and will continue to as long as the UNTIL condition evaluates as False.

Note that WHILE (loop runs while True) and UNTIL (loop runs until True) tests can be interchanged, but are generally used as illustrated above.

Go to Welcome page

BASIC Stamp Help Version 2.5.4

Copyright © Parallax Inc.

8/8/2012