Connect a Raspberry Pi to a KY-031 Knock Sensor

In this article, we connect an KY-031 Knock Sensor to a Raspberry Pi 4

When the KY-031 sensor is subjected to a knock or vibration, the two output pins are short-circuited.

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 Knock Sensor is connected
GPIO_PIN = 24
GPIO.setup (GPIO_PIN, GPIO.IN) 
   
print ("Knock Sensor test [press CTRL+C to exit the test]")
   
#  This output function is executed when a signal is detected
def outputFunction(null) :
    print("Knock Sensor 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

Tap the sensor

>>> %Run -c $EDITOR_CONTENT
Knock Sensor test [press CTRL+C to exit the test]
Knock Sensor triggered
Knock Sensor triggered

Links

https://github.com/getelectronics/PIBits/tree/master/Sensor%20Kit/KY-031%20KNOCK%20SENSOR

 

 

Related posts

Connect a Raspberry Pi to a KY-034 7 color flashing LED

Connect a Raspberry Pi to a KY-029 Dual Color LED

TLV493D magnetic sensor and Raspberry Pi 4 python example

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More