We can use the same approach for detecting shake as discussed in the Arduino section. See that section for a more complete discussion.

Here's a simple demonstration that will play a tone when shake is detected:

```# Circuit Playground Express Shake Detect
#
# Author: Carter Nelson
import time
import math

# Total acceleration threshold
ROLL_THRESHOLD = 30

# Loop forever
while True:
# Compute total acceleration
X = 0
Y = 0
Z = 0
for i in range(10):
x, y, z = cpx.acceleration
X = X + x
Y = Y + y
Z = Z + z
time.sleep(0.001)
X = X / 10
Y = Y / 10
Z = Z / 10

total_accel = math.sqrt(X*X + Y*Y + Z*Z)

# Play sound if rolling
if total_accel > ROLL_THRESHOLD:
cpx.play_tone(800, 1)```

Play around with different values of ROLL_THRESHOLD. If it's too low, the detect is too sensitive. If it's too high, you'll break your arm trying to get it to beep. The value of 30 in the above sketch seemed to work OK for me.

## Or Just Use The Library

The shake detect approach above is so useful that it was added to the CircuitPython library for Circuit Playground Express. Under the hood, it's doing the exact same thing. But now the code becomes as simple as:

```# Circuit Playground Express Shake Detect Using Library
#
# Author: Carter Nelson

# Loop forever
while True:
# Play sound if rolling
if cpx.shake():
cpx.play_tone(800, 1)```

Running that should work just like the first example. But now the code is much more readable. Sweet.

This guide was first published on Dec 16, 2016. It was last updated on Dec 16, 2016.