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

Pin assignment

Code example Arduino

Connection assignment Arduino

Arduino Sensor
Pin 10 Signal
5 V +V
Ground GND
Arduino Sensor
Pin 13 LED+
GND LED

This is an example program that makes an LED light up when a signal is detected on the sensor. For example, the modules KY-011, KY-016 or KY-029 can be used as LEDs.

int Led  =  13;// Declaration of the LED output spin
int Sensor  =  10;  // Declaration of sensor input spin
int  val ;  //  Temporary  Variable
   
void setup  ( )
{
  pinMode (Led, OUTPUT)   ;  // Initialization output spin
  pinMode (Sensor, INPUT)   ;  //  Initialization Sensorpin
}
   
void loop  ( )
{
  val  =  digitalRead (sensor)   ;  //  The current signal on the sensor is read
   
  if (val  = =  HIGH )  //  If a signal has been detected, the LED is switched on.
  {
    digitalWrite (Led, LOW);
  }
  else
  {
    digitalWrite (Led, HIGH);
  }
}

Sample program Download

KY031-Arduino.zip

Code example Raspberry Pi

Connection assignment Raspberry Pi

Raspberry Pi Sensor
GPIO 24 [Pin 18] Signal
3.3 V [Pin 1 ] +V
Ground [ Pin 6 ] GND
#  Required modules are imported and set up
import RPi. GPIO  as  GPIO
import time
   
GPIO.setmode (GPIO.BCM) 
   
# Here the input pin to which the sensor is connected is declared.  In addition, the PullUP resistor is activated at the input
GPIO_PIN = 24
GPIO.setup (GPIO_PIN, GPIO.IN) 
   
print ("Sensor test [press CTRL+C to exit the test]")
   
#  This output function is executed when a signal is detected
def outputFunction(null) :
    print("Signal detected")
   
#  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 program loop
try:
    while True:
        time.sleep (1) 
   
# Clean up after the program is finished
except KeyboardInterrupt:
    GPIO.cleanup ()

Sample program download

KY031-RPi.zip

To start with the command:

sudo python3 KY031-RPi.py

Code example Micro:Bit

Pin assignment Micro : Bit:

Micro: Bit Sensor
Pin 1 Signal
3 V +V
Ground GND

Sample program download

microbit-KY-031.zip