What is a vibration sensor?
A vibration sensor is a device that reacts to sudden movements, impacts, or vibrations, but not to constant or progressive movements. In the event of detecting a vibration, it generates a digital signal, which stops at the end of the vibration.
The operating principle is very simple. The device has a cylinder with two contacts. One of the contacts is connected to a metal rod located in the center of the cylinder. Around it, the other contact is coiled around it in the form of a spring.
In the event of a vibration, the spring deforms due to the effect of inertia, establishing contact at various points with the fixed contact. In this way, an electrical connection is established between both contacts, which can be read with a microprocessor, as if it were a button, as we saw in Arduino digital inputs.
Price
SW-18020P vibration sensors are inexpensive devices. We can find 10 vibration sensors for €1 from international sellers on Ebay or AliExpress.
Electrical schematic
The electrical schematic we need is as follows.
Assembly schematic
While the assembly on a breadboard would be as follows.
Code Example
Below is an example code for reading the sensor. We read the state of the sensor through the digital input, using the internal Pull-Up resistor. On the other hand, we use the shakeTime value and the previous state variable to control the state change, and thus detect the vibration.
const int sensorPin = 2;
const int ledPin = 13;
int tiltSensorPreviousValue = 0;
int tiltSensorCurrentValue = 0;
long lastTimeMoved = 0;
int shakeTime = 50;
void setup() {
pinMode(sensorPin, INPUT);
digitalWrite(sensorPin, HIGH); //activamos la resistencia interna PULL UP
pinMode(ledPin, OUTPUT);
}
void loop() {
tiltSensorCurrentValue = digitalRead(sensorPin);
if (tiltSensorPreviousValue != tiltSensorCurrentValue) {
lastTimeMoved = millis();
tiltSensorPreviousValue = tiltSensorCurrentValue;
}
if (millis() - lastTimeMoved < shakeTime) {
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}
Download the code
All the code for this post is available for download on Github.