The GBALib_UltrasonicSensor
library provides an easy-to-use interface for the HC-SR04 ultrasonic sensor. It allows Arduino users to measure distances in centimeters with both single and averaged readings for improved stability.
- Measure distance in centimeters using the HC-SR04 ultrasonic sensor.
- Perform single or multiple averaged readings to reduce noise and get more stable results.
- Simple and intuitive API.
The library is included in the Arduino Library Manager. You can install it either by using the Library Manager or manually by following the steps below.
- Download or clone this repository.
- Copy the folder containing this library into your Arduino libraries directory. Typically:
Documents/Arduino/libraries/
- Restart your Arduino IDE if it’s open.
- In your sketch, include the library using:
#include "GBALib_UltrasonicSensor.h"
UltrasonicSensor(int triggerPin, int echoPin);
- triggerPin: The pin connected to the sensor's trigger signal.
- echoPin: The pin connected to the sensor's echo signal.
- Reads the distance in centimeters.
- Returns: Distance in centimeters.
- Reads the distance
n
times and returns the average distance in centimeters. - n: Number of readings to average.
- Returns: Average distance in centimeters.
Here’s a simple example to get started:
#include "GBALib_UltrasonicSensor.h"
UltrasonicSensor sensor(2, 3); // Trigger pin: 2, Echo pin: 3
void setup() {
Serial.begin(9600);
}
void loop() {
int distance = sensor.readDistance(); // Get single distance reading
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait before the next reading
}
#include "GBALib_UltrasonicSensor.h"
UltrasonicSensor sensor(2, 3); // Trigger pin: 2, Echo pin: 3
void setup() {
Serial.begin(9600);
}
void loop() {
int distance = sensor.readDistance(5); // Get the average of 5 readings
Serial.print("Stable Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait before the next reading
}
- Ensure that the sensor is properly connected to the specified pins.
- Add a small delay between consecutive readings to ensure accurate results (e.g., 50ms in the loop).
This library is released under the GNU License. See the LICENSE file for more information.
Created by Graziano Blasilli, 2024.