Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
Lesson 24: Vibration Sensor Module (SW-420)
In this lesson, you’ll learn how to detect vibrations using an ESP32 Development Board and a Vibration Sensor (SW-420). We’ll cover reading digital output from the sensor and using conditional statements to display messages on the serial monitor. When the sensor detects vibration, it will display “Detected vibration…”; otherwise, it will output “…”. This project provides a practical way to grasp digital inputs and serial communication, making it ideal for electronics and programming beginners.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
|---|---|---|
Universal Maker Sensor Kit |
94 |
You can also buy them separately from the links below.
Component Introduction |
Purchase Link |
|---|---|
ESP32 & Development Board (ESP32 Board) |
|
Wiring
Code
Code Analysis
The first line of code is a constant integer declaration for the vibration sensor pin. We use digital pin 25 to read the output from the vibration sensor.
const int sensorPin = 25;
In the
setup()function, we initialize the serial communication at a baud rate of 9600 to print readings from the vibration sensor to the serial monitor. We also set the vibration sensor pin as an input.void setup() { Serial.begin(9600); // Start serial communication at 9600 baud rate pinMode(sensorPin, INPUT); // Set the sensorPin as an input pin }
The
loop()function is where we continuously check for any vibrations detected by the sensor. If the sensor detects a vibration, it prints “Detected vibration…” to the serial monitor. If no vibration is detected, it prints “…”. The loop repeats every 100 milliseconds.void loop() { if (digitalRead(sensorPin)) { // Check if there is any vibration detected by the sensor Serial.println("Detected vibration..."); // Print "Detected vibration..." if vibration detected } else { Serial.println("..."); // Print "..." otherwise } // Add a delay to avoid flooding the serial monitor delay(100); }