Skip to content

blasilli/GBALib_UltrasonicSensor

Repository files navigation

GBALib_UltrasonicSensor

Arduino Logo

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.

Features

  • 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.

Installation

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.

  1. Download or clone this repository.
  2. Copy the folder containing this library into your Arduino libraries directory. Typically:
    Documents/Arduino/libraries/
    
  3. Restart your Arduino IDE if it’s open.
  4. In your sketch, include the library using:
    #include "GBALib_UltrasonicSensor.h"

API Reference

Constructor

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.

Methods

int readDistance();

  • Reads the distance in centimeters.
  • Returns: Distance in centimeters.

int readDistance(int n);

  • Reads the distance n times and returns the average distance in centimeters.
  • n: Number of readings to average.
  • Returns: Average distance in centimeters.

Example

Here’s a simple example to get started:

Single Distance 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();  // Get single distance reading
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(500);  // Wait before the next reading
}

Averaged Distance 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
}

Notes

  • 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).

License

This library is released under the GNU License. See the LICENSE file for more information.

Author

Created by Graziano Blasilli, 2024.

About

HC-SR04 Ultrasonic Sensor library

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages