5: BASIC Stamp Command Reference – FOR…NEXT
BASIC Stamp Programming Manual 2.0c
•
www.parallaxinc.com
•
Page 121
Reps VAR WORD ' Counter for the loop.
FOR Reps = 0 TO 65535 STEP 3000 ' Each loop add 3000.
DEBUG DEC ? Reps ' Show reps in debug window.
NEXT
The value of reps increases by 3000 each trip through the loop. As it
approaches the EndValue, an interesting thing happens; Reps is: 57000,
60000, 63000, 464, 3464... It passes the EndValue, rolls over and keeps
going. That’s because the result of the calculation 63000 + 3000 exceeds the
maximum capacity of a 16-bit number and then rolls over to 464. When
the result of 464 is tested against the range (“Is Reps > 0 and is Reps <
65500?”) it passes the test and the loop continues.
A similar symptom can be seen in a program who's EndValue is mistakenly
set higher than what the counter variable can hold. The example below
uses a byte-sized variable, but the EndValue is set to a number greater than
what will fit in a byte:
SYMBOL Reps = B0 ' Counter for the loop.
FOR Reps = 0 TO 300 ' Each loop add 1.
DEBUG Reps ' Show reps in debug window.
NEXT
-- or --
Reps VAR BYTE ' Counter for the loop.
FOR Reps = 0 TO 300 ' Each loop add 1.
DEBUG DEC ? Reps ' Show reps in debug window.
NEXT
Here, Reps is a byte variable; which can only hold the number range 0 to
255. The EndValue is set to 300, however; greater than 255. This code will
loop endlessly because when Reps is 255 and the FOR…NEXT loop adds 1,
Reps becomes 0 (bytes will rollover after 255 just like words will rollover
after 65535). The result, 0, is compared against the range (0 – 255) and it is
found to be within the range, so the FOR…NEXT loop continues.
It's important to realize that on the BS2, BS2e, BS2sx and BS2p, the test is
against the entire range, not just the EndValue. The code below is a slight
modification of the previous example (the StartValue is 10 instead of 0) and
will not loop endlessly.
1
NOTE: On the BS1, the loop will
continue until Counter has gone
past EndValue. The rollover error
will still occur if the BS1 cannot
determine if Counter went past
EndValue.
2
e
2
sx
2
p
2
1
NOTE: For BS1's, change line 1 to
SYMBOL Reps = W0
and line 3 to
DEBUG Reps
1
Summary of Contents for BASIC Stamp 1
Page 1: ...BASIC Stamp Programming Manual Version 2 0c...
Page 34: ...Quick Start Guide Page 32 BASIC Stamp Programming Manual 2 0b www parallaxinc com...
Page 340: ...ASCII Chart Page 338 BASIC Stamp Programming Manual 2 0b www parallaxinc com...
Page 342: ...Reserved Words Page 340 BASIC Stamp Programming Manual 2 0b www parallaxinc com...
Page 346: ...Conversion Formatters Page 344 BASIC Stamp Programming Manual 2 0b www parallaxinc com...