BASIC stamp manual v2.2
FOR…NEXT – BASIC Stamp Command Reference
Page 192 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Quick Facts
BS1 All BS2 Models
Max. Nested Loops
8 16
To Decrement
Counter Variable
Set StartValue > EndValue and
enter negative StepValue*
Set StartValue > EndValue
Counter Comparison
Exit loop if Counter exceeds
EndValue
Exit loop if Counter outside range
set by StartValue to EndValue
Related Commands
None DO...LOOP and EXIT
Table 5.25: FOR...NEXT Quick
Facts.
*NOTE: For the BS1, direction (increment or decrement) cannot be changed at run-time.
Explanation
FOR...NEXT loops let your program execute a series of instructions for a
specified number of repetitions (called iterations). By default, each time
through the loop, the Counter variable is incremented by 1. It will continue
to loop until the value of Counter is outside of the range set by StartValue
and EndValue. Also, FOR…NEXT loops always execute at least once. The
simplest form is shown here:
reps VAR Nib ' counter for the FOR/NEXT loop
FOR reps = 1 TO 3 ' repeat with reps = 1, 2, 3
DEBUG "*" ' put * on screen for each repetition
NEXT
In the above code, the FOR command sets reps = 1. Then the DEBUG line
(within the FOR…NEXT loop) is executed; printing an asterisk (*) on the
screen. When the BASIC Stamp sees the NEXT command, it goes back to
the previous FOR command, adds 1 to reps and compares the result to the
range set by StartValue and EndValue. If reps is still within range, it
executes the code in the loop again. Each time the FOR...NEXT loop
executes, the value of reps is updated (incremented by 1) and the code
within the loop (the DEBUG line) is executed; printing another asterisk on
the screen. This code will run through the loop three times; setting reps to
1, 2 and 3, and printing three asterisks on the screen. After the third loop,
again the BASIC Stamp goes back up to the FOR command, adds 1 to reps
and compares the result (4 in this case) to the range. Since the range is 1 to
3 and the value is 4 (outside the range) the FOR…NEXT loop is done and
the BASIC Stamp will jump down to the first line of code following the
NEXT command.
You can view the changing values of reps by including the reps variable in
a DEBUG command within the loop:
NOTE: Replace the first line with
SYMBOL reps = B0
on the BS1.
S
IMPLEST FORM OF FOR...NEXT.
P
ROCESSING A FOR…NEXT LOOP.
NOTE: On the BS1, the loop will
continue until Counter has gone
p
ast EndValu
e
.
1
1