A simple library for the HC-SR04 ultrasonic distance sensor. It measures the time between the sensor's trigger and echo pins. The library is designed to be used with the Arduino IDE. Compitable with most Arduino and ESP boards.
- Open the Arduino IDE
- Go to
Sketch > Include Library > Manage Libraries...
- Search for
DistanceSensor
- Click on the library and click
Install
- Download the library from the Releases page.
- Open the Arduino IDE
- Go to
Sketch > Include Library > Add .ZIP Library...
- Select the downloaded file
- Download the library from the Releases page.
- Unzip the file
- Go to
Documents/Arduino/libraries
- Copy contents of the zip file to
Documents/Arduino/libraries
#include <DistanceSensor.h>
// Define pins
const int echoPin = 12;
const int trigPin = 13;
// Start the sensor
DistanceSensor sensor(trigPin, echoPin);
void setup () {
// Start serial port
Serial.begin(115200);
}
void loop () {
// Get distance in cm
int distance = sensor.getCM();
// Write values to serial port
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
// Wait a bit
delay(500);
}
Original library from Afstandssensor authors.
I just translated it to English and added some examples.