Home SensorsKit Arduino and KY-002 vibration sensor

Arduino and KY-002 vibration sensor

by shedboy71

In this article, we connect an KY-002 vibration sensor to an Arduino Uno

The KY-002 is a shock and vibration sensor. It outputs a high-level signal when a shock is detected.

Parts Required

You can connect to the module using dupont style jumper wire.

This should work with other Arduino board – I have tried an Uno and Mega

Name   Link
Arduino Uno
37 in one sensor kit
Connecting cables

 

Schematic/Connection

ARDUINO SENSOR
Pin 10 Signal
5 V +V
GND GND

Code Example

The following code example will switch the onboard LED the Arduino when a shock/vibration is detected

int Led = 13; // define the LED Pin
int shockPin = 3 // define the sensor Pin 
int shockVal;

void setup () 
{
    pinMode (Led, OUTPUT); // LED pin as output  
    pinMode (shockPin, INPUT); // input from KY-002 
} 

void loop () 
{
    shockVal = digitalRead (shockPin); // read the value from KY-002
    if (shockVal == HIGH ) 
    {
        digitalWrite(Led, LOW);
    } 
    else 
    {
        digitalWrite (Led, HIGH);
    }
}

A slight variation on the theme

int shockPin = 10; // sensor connected to pin 10
int shockVal = HIGH;
boolean bAlarm = false;
unsigned long lastShockTime;
int shockAlarmTime = 250; // Number of milli seconds to keep the shock alarm high

void setup ()
{
  Serial.begin(9600);  
  pinMode (shockPin, INPUT)
}

void loop ()
{
  shockVal = digitalRead (shockPin) ; // read the value from the sensor
  
  if (shockVal == LOW)
  {
    lastShockTime = millis();
    if (!bAlarm)
    {
      Serial.println("Shock detected");
      bAlarm = true;
    }
  }
  else
  {
    if( (millis()-lastShockTime) > shockAlarmTime  &&  bAlarm)
    {
      Serial.println("No Shock detected");
      bAlarm = false;
    }
  }
}

 

Serial Monitor Output

N/A

Links

https://github.com/getelectronics/ArduinoCode/tree/main/37%20Sensor%20Kit/KY-002_VIBRATION_SWITCH

 

 

You may also like

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