At the heart of every Adafruit Circuit Playground Express lies a three-axis accelerometer. This allows us to write programs that take the orientation of the board into account. We can detect orientation and acceleration on any axis. With MakeCode there are two different ways to interface with the accelerometer, events and live data. We can look for specific gesture events like a shake, freefall, tilt, or specific G or acceleration. We can also read live data which returns the immediate acceleration for a given direction in milli-g (1/1000 of gravity).
If the board is sitting on a table:
- the X-axis is aligned horizontally from left to right. If you tilt left, X is negative, tilt right X is positive.
- the Y-axis is aligned vertically from bottom to top. If you tilt forward, Y is positive, tilt backward Y is negative.
- the Z-axis is perpendicular to the board and pointing down. At rest, Z is aligned with earth gravity.
For this tutorial, we will create a sketch that changes the lights based on the orientation of the Circuit Playground Express.
The Code
The logic of this program is a single if/else bracket with four fields. To add additional fields we click the “+” symbol at the bottom of the if/else bracket We start by adding a >= comparator in the if statement, then drag in the acceleration input into the comparator and set the comparison value to 500. Since 1000mg is one Earth gravity, tilting the Circuit Playground Express 45 degrees will return approximately one-half gravity or 500mg. We created a comparator for each direction of both the x and y-axis. Keep in mind that on a single axis, one tilt direction will be positive and the other direction negative. We finish our if/else by putting clear in the else bracket to turn the lights off when the board is not tilted.
Now you're ready to get out there and create using the accelerometers on your Adafruit Circuit Playground Express! This is a great sensor that you can incorporate into many projects, and there is a lot of potential for wearables and mobile projects. If you want to learn more about how to use the Adafruit Circuit Playground Express check out our Circuit Playground Tutorials! We have a tutorial for every piece of onboard hardware on the board, in both MakeCode and CircuitPython!