In the INPUT block group, select the
on shake block and put it in the programming area. Click the word shake and see all the features that pop up:
You can trigger code to do a great number of things by selecting different versions of this block.
The following code uses the basic shake capability to build an alarm. You can set the sensitivity of the accelerometer in the initial
on start block with the
set accelerometer range block.
This is good for wearables where you want to blink lights and/or make sounds when you move like an alarm. Also this is good for making noise when a Circuit Playground Express is hung on a door or otherwise moved and it alarms.
on start, the accelerometer is set to be very sensitive at 1g, the volume maxed out and a variable
shaken set to indicate not shaken. The
on shake block will set the
shaken variable to
1 to indicate to the
forever loop that there was a shake. The
forever loop waits to see if the variable
shaken is set to 1 by the
on shake block.
This code also reads the accelerometer
strength value and if it changes more than a set value (currently
100), it will also indicate an alarm by setting
shaken to 1. The
on shake block was not being "sensitive enough" for an alarm, so some extra code reads the accelerometer
strength, compares it to a previous reading, and if it has changed by more than a value (currently
100) it also sets the
shaken = 1 alarm condition.
The code gives the programmer control over how sensitive to make it. Change
100 to a value that works for you. If you use MakeCode for Windows 10, you can see what values produce what types of readings to help you set the value of
shaken has been set to
1, the device shows all red NeoPixel LEDs and makes a high pitch beep. The way to reset this alarm is if Button A is pressed via
on button A click (you can make it harder to reset if you like). You might have to hold the Circuit Playground Express real still and press the button a couple times to get it to reset.