FOR Variable = StartVal TO EndVal {STEP {-}StepVal}
    { EXIT }

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.

  • Variable  a byte or word variable used as a loop counter.
  • StartVal  is a constant or variable that sets the starting value of the counter.
  • EndVal  is a constant or a variable that sets the ending value of the counter.
  • StepVal  is a constant or a variable which by counter is incremented or (when negative) decremented during each iteration of the loop.

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:

  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

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.

Related instructions: DO...LOOP and EXIT