BASIC stamp manual v2.2
FOR…NEXT – BASIC Stamp Command Reference
Page 194 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
All the arguments in the FOR…NEXT command can be constants,
variables or expressions on all BS2 models. This leads to some interesting
uses. For example, if you make the StartValue and EndValue a variable,
and change their values within the loop, you'll change the behavior of the
loop itself. Try the following:
{' $PBASIC 2.5}
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 for 1 to 3
DEBUG DEC reps, CR
IF (reps = 3) THEN ' if reps =3, swap startVal/endVal
startVal = 3 ' otherwise continue loop
endVal = 1
ENDIF
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 equal to
3, then swap the order of startVal and endVal, otherwise continue the loop
execution. The next time through the loop (after startVal and endVal have
been swapped), 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
WATCH OUT FOR 16-BIT ROLLOVER, OR
VARIABLE RANGE
, ERRORS.
U
SING VARIABLES AS ARGUMENTS.
NOTE: For BS1's, change line 1 to
SYMBOL reps = W0
and line 3 to
DEBUG reps
NOTE: The increment/decrement
direction of the FOR…NEXT loop
cannot be changed on the BS1.
1
1
All
2