In this article, we connect an KY-020 Tilt switch to a Raspberry Pi 4
When the KY-020 Tilt switch depending on the inclination, a switch closes the input pins briefly. This happens due to the fact that a ball inside the switch short-circuits the contacts, depending on the position.
We will use Python for the example
The sensor looks like this
Parts Required
You can connect to the module using dupont style jumper wire. There is no reason this device will not work with any Raspberry Pi hardware that you have – in this example a Raspberry Pi 4 but you can use a Zero if you want a lower cost solution
Name | Link | |
Raspberry Pi 4 | ||
37 in one sensor kit | ||
Connecting cables |
Schematic/Connection
Pico | SENSOR |
---|---|
Pin 18 | S |
3.3V | middle pin |
GND | – |
Code Examples
Basic example in thonny, running on the Raspberry Pi
import RPi. GPIO as GPIO import time GPIO.setmode (GPIO.BCM) # Here the input pin to which the tilt switch is connected GPIO_PIN = 24 GPIO.setup (GPIO_PIN, GPIO.IN) print ("tilt switch test [press CTRL+C to exit the test]") # This output function is executed when a signal is detected def outputFunction(null) : print("tilt switch triggered") # When a signal is detected (falling signal edge), the output function is triggered GPIO.add_event_detect(GPIO_PIN, GPIO.FALLING, callback= outputFunction , bouncetime=100) # Main loop try: while True: time.sleep (1) except KeyboardInterrupt: GPIO.cleanup ()
REPL Output
Tilt the switch
>>> %Run -c $EDITOR_CONTENT
tilt switch test [press CTRL+C to exit the test]
tilt switch triggered
tilt switch triggered
tilt switch triggered
tilt switch triggered
Links
https://github.com/getelectronics/PIBits/tree/master/Sensor%20Kit/KY-020%20Tilt%20switch