Using a Tilt ball switch as a vibration sensor

Connected to a Microcontroller this low cost ball switch can not only function as a simple on-off switch, but you can use it as a sophisticated tilt, shake and vibration sensor.
We will be using Raspberry Pi Pico for this experiment with CircuitPython, however you can use MicroPython or any other Microcontroller. Logic is what matters here.
How it works
We will use one GPIO pin as a digital output pin, we will connect this output pin to another GPIO pin which we will define as a digital input pin through the tilt ball switch.
With some code we will be able to detect high and low state on the input pin, and with some simple conditions we can work out if it's a simple tilt or a vibration.
What you need
- Raspberry Pi Pico or compatible board with CircuitPython installed
- A tilt ball switch
- Breadboard and 2 jumper wires
Wiring
Connect your board's GP0 pin to one leg of your tilt switch and GP1 pin to the other leg. It does not matter which pin goes to which side.

The code
Make sure that you have CircuitPython is installed on your board before running this code. Place this code in code.py and save it to Pi Pico.
import time
import board
# Helper print to see whats available on the connected board
print(dir(board))
# We will use digital input and output for our sensor code
from digitalio import DigitalInOut, Direction, Pull
gp2 = DigitalInOut(board.GP0)
gp2.direction = Direction.OUTPUT
gp2.value = 1
gp3 = DigitalInOut(board.GP1)
gp3.direction = Direction.INPUT
gp3.pull = Pull.DOWN
# We use this to reduce the number of events to 1
# Remove this from here and within the if conditions to see the difference
tiltDetected = False
tiltDetectedAt = 0
# Adapt these to calibrate sensitivity
ACTION_INTERVAL = 0.5
TIME_OUT = 0.1
while True:
if gp3.value == False and tiltDetected == False:
if time.monotonic() - tiltDetectedAt < ACTION_INTERVAL:
# Shake / Vibration detected
print("¯\_(ツ)_/¯")
else:
print("Tilt detected!")
tiltDetected = True
tiltDetectedAt = time.monotonic()
elif gp3.value == True and tiltDetected == True:
if time.monotonic() - tiltDetectedAt < ACTION_INTERVAL:
# Shake / Vibration detected
print("¯\_(ツ)_/¯")
else:
print("Reset!")
tiltDetected = False
time.sleep(TIME_OUT)
That's it! run the code.
Your sensor is now ready. Tilt, shake or vibrate the ball switch you should now be able to sense whats happening.

You can adjust the sensitivity of your new sensor by adjusting TIME_OUT and the ACTION_INTERVAL
# Adapt these to calibrate sensitivity
ACTION_INTERVAL = 0.5
TIME_OUT = 0.1
If you have any questions or suggestions, please leave a message. We try to reply within a day.