The Circuit Playground Express and Bluefruit accelerometer can detect other types of input actions besides taps. One of those inputs is shake. You have the ability to shake your board to tell it to do something. Let's give it a try!

Add the following code to your code.py. Remember, if you need help with this, check here.

"""This example prints to the serial console when the Circuit Playground is shaken."""
from adafruit_circuitplayground import cp

while True:
    if cp.shake():
        print("Shake detected!")

Open the serial console and give the board a good shake. Shake detected!

Let's look at the code. First we import cp.

Inside our loop, we check to see if the board has been shaken with if cp.shake():. If the board is shaken, we print to the serial console, Shake detected!

Notice that there are parentheses after cp.shake. These are necessary for shake detection to work properly. Without them, your code will run, but it won't work properly. Make sure you include them!

Shake It Up A Little

Let's use shaking the board to turn on the red LED. Add the following code to your code.py.

"""This example flashes the little red LED when the Circuit Playground is shaken."""
from adafruit_circuitplayground import cp

while True:
    if cp.shake(shake_threshold=20):
        print("Shake detected!")
        cp.red_led = True
    else:
        cp.red_led = False

Shake the board. Red LED!

Let's look at the code. First we import cp.

Inside our loop, we check to see if the board has been shaken. However, we've added something to this line, shake_threshold=20. Sometimes you may find that the board doesn't respond to your shaking, or it responds too easily. You have the option to change the threshold to make it harder or easier to shake the board. The default threshold is 30. Decreasing the threshold makes it easier to have a shake detected. Increasing the threshold makes it harder to have a shake detected. The minimum value allowed is 10. 10 is the value when the board is not moving. So if you set the threshold to less than 10, the code will constantly return a shake detected even if the board is not moving. Set the threshold to any whole number above 10 to change the threshold to fit your needs.

In this case, we've included if cp.shake(shake_threshold=20): which lowers the threshold, making it easier to shake the board. If a shake over the threshold of 20 is detected, we print Shake Detected! and we turn on the red LED. Otherwise, we turn off the red LED with our else block.

Try changing the threshold to 40 and see what happens. Be aware, if you set the threshold too high, the shake will never be detected. Play around with it to find out what works best for you!

This guide was first published on Jun 05, 2018. It was last updated on Jun 05, 2018. This page (Shake) was last updated on Feb 20, 2020.