An advanced and easy-to-use ultrasonic sensor library for HC-SR04 and similar modules.
- Distance Measurement: Get highly accurate readings in Centimeters (cm) and Inches (in).
- Object Detection: Easily check if objects are within a specific threshold, or further away.
- Motion Detection: Automatically detect if an object has moved relative to the sensor, or if it is approaching/receding.
- Speed Calculation: Calculate the velocity of an object (cm/s) as it approaches or moves away.
- Averaging Filter: Smooth out noisy data by taking multiple rapid readings and returning the mean.
- Radar Support: Output data formatted for radar screens and Processing interfaces.
- Download this repository as a
.zipfile. - Open the Arduino IDE.
- Go to Sketch -> Include Library -> Add .ZIP Library....
- Select the downloaded
.zipfile. - Include the library in your code using
#include <UltrasonicX.h>.
Initializes the library with the pins connected to the sensor.
- trigPin: The digital pin used for the trigger signal.
- echoPin: The digital pin used to receive the echo signal.
Configures the trigPin as OUTPUT and echoPin as INPUT. This must be called within your setup() function.
Calculates the current distance to an object in centimeters based on a speed of sound of ~0.0343 cm/us.
- Returns: Distance as a
float.
Calculates the current distance to an object in inches (1 cm = 0.393701 inches).
- Returns: Distance as a
float.
Takes multiple readings (defaulting to 5) and returns the mathematical mean to filter out electrical or environmental noise.
- samples: Number of readings to average.
- Returns: Smoothed distance in cm.
Checks if the sensor is providing a valid reading (greater than 0 distance).
- Returns:
trueif the reading is valid.
Checks if an object is currently closer than the specified threshold.
- threshold: The distance limit in cm.
- Returns:
trueif an object is detected within range.
An alias for isObjectDetected.
Checks if an object is currently farther than the specified threshold.
- threshold: The distance limit in cm.
- Returns:
trueif an object is farther than the specified limit.
Compares the current distance reading to the previous one. It returns true if the distance has changed by more than the threshold since the last time this function was called.
- threshold: Sensitivity in cm. Default is 2.0cm.
- Returns:
trueif movement is detected.
Compares the current distance reading to the previous one. It returns true if the object moved closer by more than the threshold since the last time this function was called.
- threshold: Sensitivity in cm. Default is 2.0cm.
- Returns:
trueif the object is approaching.
Compares the current distance reading to the previous one. It returns true if the object moved farther by more than the threshold since the last time this function was called.
- threshold: Sensitivity in cm. Default is 2.0cm.
- Returns:
trueif the object is receding.
Calculates the velocity of an object relative to the sensor based on the change in distance over time.
- Returns: Speed in cm/s. A positive value indicates the object is moving away; a negative value indicates it is approaching.
Sends a 10µs pulse and returns the raw travel time of the sound wave.
- Returns: Time in microseconds; returns
0if no echo is received (out of range).
Formats the reading for applications like Processing to build a radar screen.
- angle: The current angle of the servo motor holding the sensor.
- Returns: A
Stringformatted as"angle,distance."
#include <UltrasonicX.h>
// Initialize sensor on Trigger Pin 9 and Echo Pin 10
UltrasonicX sonar(9, 10);
void setup() {
Serial.begin(9600);
sonar.begin();
}
void loop() {
// Get distance in cm
Serial.print("Distance: ");
Serial.print(sonar.getDistanceCM());
Serial.println(" cm");
// Check for motion (5cm threshold)
if (sonar.isMotionDetected(5.0)) {
Serial.println("Motion detected!");
}
// Check if reading is valid
if (sonar.isValidReading()) {
if (sonar.isApproaching(2.0)) {
Serial.println("Object is approaching!");
} else if (sonar.isReceding(2.0)) {
Serial.println("Object is moving away!");
}
} else {
Serial.println("Reading invalid or out of range.");
}
delay(500);
}#include <UltrasonicX.h>
#include <Servo.h>
UltrasonicX sonar(9, 10);
Servo myServo;
void setup() {
Serial.begin(9600);
sonar.begin();
myServo.attach(11); // Attach servo to pin 11
}
void loop() {
// Sweep servo from 15 to 165 degrees
for(int i = 15; i <= 165; i++) {
myServo.write(i);
delay(30);
// Print data formatted for Processing radar sketch
Serial.print(sonar.getRadarData(i));
}
// Sweep servo back from 165 to 15 degrees
for(int i = 165; i >= 15; i--) {
myServo.write(i);
delay(30);
Serial.print(sonar.getRadarData(i));
}
}