The Adafruit Circuit Playground Express comes equipped with an analog light sensor, but it can be used for much more than just sensing light or darkness! The light sensor has a similar spectral response to the human eye. Its connected to analog pin A8 and will return a value between 0 and 1023. A normal indoor light level reading is about 300, with higher numbers being brighter.
With a light sensor you can obviously read ambient light, but did you know you could also use it to sense color or to measure your heartbeat? For this tutorial, we will use the light sensor and the buttons to make a color matching ring of NeoPixels!
To use a light sensor to read color you just need a NeoPixel near the light sensor. Lucky for us there is one already there on the Circuit Playground Express! When we see something that’s blue, its because it is reflecting blue light back at us from the full spectrum. If we light up our pixel near the light sensor each primary color and take a reading from each, we can calculate how much of each color was reflected and duplicate it on the NeoPixels. It's not a perfect system, as our NeoPixel cannot create true primary colors, and our NeoPixel ring won’t be able to perfectly duplicate every color we try to match. Lighter colors will tend to look a little washed out and curve toward white, however, we can expect to accurately replicate at least 12 colors! Just hold the object that you want to color match very close to the sensor! Press button B to take a reading, Press Button A to clear the NeoPixel ring!
The Code
Making a color matching program with MakeCode is simple, there is a block specifically made to read color. We just need to add a little code to command it on and off, so we don’t get a color sensing feedback loop.
Let’s take a look.
For this sketch, we won’t be using a forever loop. We will instead be using the input loops of “on button A/B click”. Even though it doesn’t mention any loops, this is still a loop function as the program looks for this input continuously while the board is powered, when the input condition is met then whatever is inside the block is executed. A press from button B will activate the pixel nearest the light sensor and take readings, then set all pixels to that color. Button A will clear the lights, so you can take another reading. If you try to color match while the color wheel is still on, then you will have bad readings.
If you want to learn more about the Adafruit Circuit Playground Express, check out our Circuit Playground Tutorials page! We have a tutorial for every sensor on the board, in both MakeCode and CircuitPython! Don’t forget you can even program the Circuit Playground Express with Arduino!