# Circuit Playground Express – Light Sequence

In this tutorial, we will create a light sequence that will make the built in LEDs turn red one at a time when we press the ‘A’ button.  When we press the ‘A’ button again, the LEDs will turn blue in reverse order.  This will require a Circuit Playground Express, and some basic coding.

#### Materials #### Light Them Up – One at a Time

There are 10 LEDs.  They are numbered from 0 to 9.  When we press the ‘A’ button, we want LED 0 to light up, then pause, then LED 1 to light up, and so on.  This will require a ‘for’ loop.

Index is an iteration variable.  It looks at the list of numbers 0 through 9. In the first pass through this loop index will be 0.  It will set LED 0 to red, and then pause.  On the next pass index will be 1.  It will set LED 1 to red and then pause.  It will do that until index is 9, and all of the lights are on. #### Turn Them to Blue – One at a Time in Reverse

We are going to turn them blue, but we want to go in reverse order.  So instead of starting at LED 0, we will start at LED 9 and go in reverse.  This will also require a ‘for’ loop.

To make it go in reverse, we will use a little math.  Using the command ‘Set Pixel at’ we insert an equation that gives us the value of 9-index.  So in our first pass through the loop, index will be 0.  So LED (9-0) is LED 9.  It will be turned blue, and the pause.  In our next pass, index will be 1.  Then LED (9-1) is LED 8.  This goes until we are at our LED 0. #### Variables

We want to press ‘A’ once to make the LEDs go red.  When we press ‘A’ again, they should blue.  To make this happen, we are going to need some variables.  We are going to create a variable called ‘forward’ and give it the initial value of ‘true’. #### Make it Conditional

This takes the two parts we made earlier, and works with the ‘forward’ variable.  Lets see what happens when we push ‘A’.

We are using an ‘if’ statement.  So on our first pass through, ‘if forward’ is really ‘if true’.  In this case, it will go through and make all the lights red.  After it does that it skips ‘else’ and goes to the bottom, where it is told set ‘forward’ to ‘not forward’.  That means ‘forward’ becomes ‘not true’ or ‘false’.

On the next ‘A’ click, ‘forward’ is false, so we skip ‘if’ and go to ‘else’ and run the code that changes our lights to blue.  When that is done it sets ‘forward’ to ‘not forward’.  That means ‘forward’ becomes ‘not false’ or ‘true’.

This repeats and we can hit ‘A’ all day long. The code is embedded below.  I have made one change here.  I took out the number ‘9’ and used a variable called ‘lights’.  It has the value of ‘9’, but if I ever want to have just half of the LEDs light up, I only need to change the value of ‘lights’.