FOR…NEXT - BASIC Stamp Command Reference
Page 120 • BASIC Stamp Programming Manual 2.0b • www.parallaxinc.com
Reps VAR BYTE ' Counter for the FOR/NEXT loop.
StartVal VAR BYTE
EndVal VAR BYTE
StartVal = 1 ' Initialize StartVal to 1
EndVal = 3 ' Initialize EndVal to 3
FOR Reps = StartVal TO EndVal ' Repeat until Reps is not in range 1 to 3.
DEBUG DEC Reps,CR
IF Reps <> 3 THEN Done ' If Reps <> 3 then continue as normal
StartVal = 3 ' otherwise, swap StartVal and EndVal
EndVal = 1
Done:
NEXT
Here the loop starts with a range of 1 to 3. First, the DEBUG line prints the
value of Reps. Then the IF…THEN line makes a decision; if Reps is not
equal to 3, jump to the label "Done." If, however, Reps is equal to 3, the
two lines following IF…THEN swap the order of StartVal and EndVal,
making the range 3 to 1. The next time through the loop, Reps will be
decremented instead of incremented because StartVal is greater than
EndVal. The result is a display on the screen of the numbers 1, 2, 3, 2, 1.
The following example uses the value of Reps as the StepValue. This
creates a display of power's of 2 (1, 2, 4, 8, 16, 32, 64, etc):
Reps VAR WORD ' Counter for the loop.
FOR Reps = 1 TO 256 STEP Reps ' Each loop add current value of Reps
DEBUG DEC ? Reps ' Show reps in debug window.
NEXT
There is a potential bug that you should be careful to avoid. The BASIC
Stamp uses unsigned 16-bit integer math for any math operation it
performs, regardless of the size of values or variables. The maximum
value the BASIC Stamp can internally calculate is 65535 (the largest 16-bit
number). If you add 1 to 65535, you get 0 as the 16-bit register rolls over
(like a car’s odometer does when you exceed the maximum mileage it can
display). Similarly, if you subtract 1 from 0, you'll get 65535 as the 16-bit
register rolls under (a rollover in the opposite direction).
If you write a FOR...NEXT loop who's StepValue would cause the counter
variable to go past 65535, this rollover may cause the loop to execute more
times than you expect. Try the following example:
W
ATCH OUT FOR 16-BIT ROLLOVER,
OR VARIABLE RANGE, ERRORS.
NOTE: The increment/decrement
direction of the FOR…NEXT loop
cannot be changed on the BS1.
2
2
2
NOTE: For BS1's, change line 1 to
SYMBOL Reps = W0
and line 3 to