First, let's get a little organized. We'll take all the light-effects code we just wrote and move it into a function. A function is basically a container that holds on to your code for you, and keeps it safe and out of your way. We can give it a name and then just call the name when we want the code to run.
Click the ADVANCED tab and find FUNCTIONS. In this tab, make a new function. I called mine
dragonLights. The new code block will appear in your workspace. Drag everything that was inside the
forever loop into this new function. Move it out of the way.
Now we've got space inside the
forever loop to work on the switch. Remember how we made a switch variable back in step one? It's time to put that to use. We'll tell MakeCode to run the
dragonLights code if
switch is set to
true, or to turn all the lights off if it's set to
Head to the LOGIC tab and drag a conditional statement into your blissfully empty
forever loop. Add a comparison block, and then drag in the
switch variable from the VARIABLES tab. Make it read
if switch = true then.
Then, from the ADVANCED > FUNCTIONS tab, drag call function
dragonLights into the first slot in the conditional loop.
To make the lights turn off if
switch <> true, we'll need three lines of code since we have three different sets of LEDs.
set all pixels to red from the LIGHT tab and set it to
black. This will turn off the lights on the face of the Circuit Playground (the egg lights).
strip clear and a
strand clear into this block from the NEOPIXEL tab.
That should do it! All three sets of lights will now go off if
switch is NOT set to true.
The last thing we need to do is to build a way to toggle the
switch variable. From the INPUT tab, drag an instance of
on button A click into your workspace. Change
button A to
pin 4, since that's where we're going to solder on the capacitive touch switch.
Now build the switch code as shown. It's easiest to copy/paste the conditional block from the
forever loop to start, delete the code that's in there, then add
set switch from the VARIABLES tab.
You'll need to mess with the
- buttons in the
else section to get it to read
else if instead of
Now, each time pin 4 is touched, the switch variable will toggle between true and false. If it's true, the lights will come on and if it's false, they'll go off.
Download your code and test it out. You don't need to have anything wired to pin A4 just yet -- it should work simply by touching the pad.
If you're having trouble getting the code to download, head over to the Circuit Playground Express Intro Guide for help.