In this article, we connect a KY-020 Tilt switch to a Raspberry Pi Pico, any Rp2040 type board will be suitable. We actually tested this with a Cytron Maker Pi Pico
We will use Micropython for these examples but of course you can use the Arduino IDE as well if you have Raspberry Pi Pico support enabled
The sensor looks like this
Parts Required
You can connect to the module using dupont style jumper wire.
Name | Link | |
Raspberry Pi Pico | ||
37 in one sensor kit | ||
Connecting cables |
Schematic/Connection
Pico | SENSOR |
---|---|
GPIO28 | S |
3v3 | Middle pin |
GND | – |
Code Examples
Basic example
from machine import Pin, Timer # Initialization of GPIO 28 as input sensor = Pin(28, Pin.IN, Pin.PULL_DOWN) # Create timer timer = Timer() # Set counter to 0 counter = 0 def tilt(timer): global counter counter = counter + 1 print("Tilt detected") print(counter) # Function: debounce def debounce(pin): # Debounce function: Set timer timer.init(mode=Timer.ONE_SHOT, period=100, callback=tilt) # Interrupt while True: sensor.irq(trigger=Pin.IRQ_FALLING, handler=debounce)
REPL Output
Move the switch around
>>> %Run -c $EDITOR_CONTENT
Tilt detected
1
Tilt detected
2
Tilt detected
3
Tilt detected
4
Tilt detected
5
Links
https://github.com/getelectronics/rp2040learning/tree/main/Sensor%20Kit/KY-020_Tilt_Switch