Measuring distance using Arduino is one of the most useful beginner projects. In this tutorial, you’ll learn how to use the SR04M-2 ultrasonic sensor to measure distance accurately for real-world applications. The SR04M-2 is a waterproof ultrasonic sensor that measures distance by sending sound waves and receiving the echo.
![]() |
| A step-by-step guide to measure distance using a waterproof ultrasonic sensor and Arduino. |
⚙️ Key Features
- Waterproof probe
- Range: 20cm to 400cm
- Operating voltage: 5V
- Stable and accurate readings
๐ Wiring Diagram & Connections
![]() |
| How to connect the sensor to Arduino. |
๐ป Arduino Code
![]() |
| Program to read and display distance. |
Install the NewPing library before uploading the code. Click HERE to download code.
๐ฅ Library Installation
- Open Arduino IDE
- Go to Sketch → Include Library → Manage Libraries
- Search “NewPing”
- Click Install
๐ Code
#include <newping.h>
#define TRIGGER_PIN 3
#define ECHO_PIN 2
#define MAX_DISTANCE 400
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float tempval1;
float tempval2 = 60;
int finalval;
unsigned long lastPingTime = 0;
unsigned long pingInterval = 50;
void setup() {
Serial.begin(57600);
}
void loop() {
unsigned long currentTime = millis();
if ((currentTime - lastPingTime >= pingInterval)) {
unsigned int distance = sonar.ping_cm();
if (distance > 0) {
tempval1 = distance;
float diff = abs(tempval1 - tempval2);
if (diff > 2) {
if (diff > 30) {
tempval2 = (tempval1 * 0.7) + (tempval2 * 0.3);
} else {
tempval2 = (tempval1 * 0.4) + (tempval2 * 0.6);
}
finalval = tempval2;
Serial.print("Ping: ");
Serial.print(finalval);
Serial.println("cm");
}
}
lastPingTime = currentTime;
}
}
๐งช Testing the Sensor
![]() |
| Checking real-time distance readings. |
- Open Serial Monitor
- Set baud rate to 57600
- Move an object closer and farther
⚙️ How It Works
The sensor sends ultrasonic waves and calculates distance based on the time taken for the echo to return. The code also smooths readings to reduce noise.
๐ Applications
- Water level monitoring
- Parking systems
- Obstacle detection robots
- Smart irrigation
✅ Conclusion
You’ve learned how to connect, code, and test the SR04M-2 ultrasonic sensor with Arduino. This is a great starting point for many automation projects. If this helped you, please like ๐ and share ๐ this tutorial.



