25 Make the LEDs turn on in sequence and turn off in sequence

Open the script named strobe3.m; the script causes the LEDs to turn on in sequence and then turn off in sequence as shown in the following video:

https://youtu.be/8ZqsWwQ-Ie8

strobe3.m has 9 lines of MATLAB code:

onIndex = 0;
setOn = true;

while true
    setLEDandWait(onIndex, setOn, 1);
    onIndex = nextIndex(onIndex);
    if onIndex == 0
        setOn = ~setOn;
    end
end

On the first line, onIndex is the index of the LED that should be turned on or off; it is set to 0 indicating that the LED controlled by digital output 0 should be the first LED to be turned on or off.

On the second line, setOn is a variable that controls whether an LED should be turned on or off. If setOn is true then the LED should be turned on. If setOn is false then the LED should be turned off. setOn is a logical or boolean variable; we will study logical values later in the course.

On the third line, there is a while loop. A while loop runs the statements between the lines between while and end as long as the condition after the keyword while is true. In this example, the while loop runs forever. The statements between the lines starting with while and end are called the body of the loop.

The body of the loop turns the LED controlled by the digital output numbered onIndex on or off according to the value of setOn and then sets onIndex to the index of the next LED to be controlled. When onIndex becomes equal to 0 the variable setOn is flipped to its opposite value (from true to false or from false to true). Because the loop runs forever, the script causes the LEDs to turn on in sequence then turn off in sequence forever.

Run the script by typing:

strobe3

into the MATLAB Command Window and pressing enter. Verify that the LEDs continuously turn on in sequence and turn off in sequence.

To stop the script, hold down the Ctrl button and press the key c (Ctrl-c).