Specifications
BASIC Stamp II
Page 262 • BASIC Stamp Programming Manual 1.8 • Parallax, Inc.
If you want For...Next to count by some amount other than 1, you can
specify a stepVal. For example, change the previous example to count
down by 3:
reps var nib ' Counter for the FOR/NEXT loop.
FOR reps = 10 to 1 STEP 3 ' Repeat with reps = 10, 7...1.
debug dec ? reps ' Each rep, show values of reps.
NEXT
Note that even though you are counting down, stepVal is still positive.
For...Next takes its cue from the relationship between start and end, not
the sign of stepVal. In fact, although PBASIC2 won’t squawk if you use
a negative entry for stepVal, its positive-integer math treats these values
as large positive numbers. For example, –1 in two’s complement is
65535. So the following code executes only once:
reps var word ' Counter for the FOR/NEXT loop.
FOR reps = 1 to 10 STEP -1 ' Actually FOR reps = 1 to 10 step 65535
debug dec ? reps ' Executes only once.
NEXT
This brings up a good point: the instructions inside a For...Next loop
always execute once, no matter what start, end and stepVal values are
assigned.
There is a potential bug that you should be careful to avoid. PBASIC
uses unsigned 16-bit integer math to increment/decrement the counter
variable and compare it to the stop value. The maximum value a 16-bit
variable can hold is 65535. 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).
If you write a For...Next loop whose step value is larger than the
difference between the stop value and 65535, this rollover will cause the
loop to execute more times than you expect. Try the following example:
reps var word ' Counter for the loop.
FOR reps = 0 to 65500 STEP 3000 ' Each loop add 3000.
debug dec ? reps ' Show reps in debug window.
NEXT ' Again until reps>65500.
The value of reps increases by 3000 each trip through the loop. As it
approaches the stop value, an interesting thing happens: 57000, 60000,
63000, 464, 3464... It passes the stop value and keeps going. That’s
because the result of the calculation 63000 + 3000 exceeds the maximum










