Parallax BASIC Stamp 2e Programming Manual page 122

Table of Contents

Advertisement

FOR...NEXT - BASIC Stamp Command Reference
Reps
VAR
BYTE
StartVal
VAR
BYTE
EndVal
VAR
BYTE
StartVal = 1
EndVal = 3
FOR Reps = StartVal TO EndVal
DEBUG DEC Reps,CR
IF Reps <> 3 THEN Done
StartVal = 3
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
FOR Reps = 1 TO 256 STEP Reps
DEBUG DEC ? Reps
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:
Page 120 • BASIC Stamp Programming Manual 2.0b • www.parallaxinc.com
' Counter for the FOR/NEXT loop.
' Initialize StartVal to 1
' Initialize EndVal to 3
' Repeat until Reps is not in range 1 to 3.
' If Reps <> 3 then continue as normal
' otherwise, swap StartVal and EndVal
' Counter for the loop.
' Each loop add current value of Reps
' Show reps in debug window.
2
2
2
2
e
sx
p
NOTE: The increment/decrement
direction of the FOR...NEXT loop
cannot be changed on the BS1.
NOTE: For BS1's, change line 1 to
SYMBOL Reps = W0
and line 3 to
DEBUG Reps
W
16-
ATCH OUT FOR
BIT ROLLOVER
,
OR VARIABLE RANGE
ERRORS
1
1
,
.

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the BASIC Stamp 2e and is the answer not in the manual?

Table of Contents