If the sensor is exposed to a knock/shock, the two output pins are short-circuited.

Pin assignment

Code example Arduino

Connection assignment Arduino

Arduino Sensor
Pin 10 Signal
5V +V
Mass 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.3V [Pin 1 ] +V
Mass [ Pin 6 ] GND

This is a similar example program with the difference that here no LED is brought to light but something is output in the console when a signal is detected.

#  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.py

Code example Micro:Bit

Pin assignment Micro : Bit:

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

This is a MakeCode example for Micro: Bit which essentially does the same as the examples of the other two variants. However, this example is closer to the Raspberry Pi example than the Arduino example.

Sample program download

microbit-KY-031.zip