FOR ... NEXT | Example |
FOR Variable = StartVal TO EndVal {STEP {-}StepVal} Function
Statement(s)
{ EXIT }
NEXT
Create a repeating loop that executes the program lines between FOR and
NEXT, incrementing or decrementing ByteVar according to
StepVal until the value of ByteVar reaches or passes the
EndVal.
Explanation
FOR...NEXT loops let your program execute a series of instructions for a
specified number of repetitions. By default, each time through
the loop, Variable is incremented by 1. It will continue to loop until
the value of the Variable reaches or exceeds EndVal. Also,
FOR...NEXT loops always execute at least once. The simplest form is shown
here:
Blink_LED: FOR idx = 1 TO 10 ' blink 10 times HIGH LED ' light the LED PAUSE 200 ' wait 0.2 secs LOW LED ' extinguish the LED PAUSE 300 ' wait 0.3 secs NEXT
In this simple example, the FOR instruction initializes idx to 1. Then the HIGH, PAUSE, LOW, and PAUSE instructions are executed. At NEXT, idx is checked to see if it is less than 10. If it is, idx will be incremented by 1 and the loop instructions run again. When idx is equal to 10 the loop terminates and the program continues at the instruction that follows NEXT.
Note that when using word variables for StartVal or EndVal, Variable must be a word variable as well. If a Variable is a byte, and a word constant is used for either StartVal or EndVal, the constant value(s) will be truncated to eight bits.