Distance measuring using Ultrasonic sensor with the help of Library | Arduino Project
Measuring distance using Arduino and Ultrasonic sensor with the help of libraries. I am making this tutorial because I was searching for this type of tutorial in which only libraries are used to make the code simple and time saving but I was unable to find it. So, I am making my own tutorial.
I will try to make this tutorial easy, simple and fast.
Just follow the steps.
Material Required:
- Arduino IDE
- Arduino Board
- Ultrasonic Sensor (HC-SR04)
- wires
- bread board (if you are making as temporary project)
Schematic Diagram:
Connect your circuit according to this schematic diagram.
![]() |
Distance measuring using Ultrasonic sensor Library |
Library:
Firstly, open your Arduino IDE and install the library named as HC SR04 ultrasonic sensor by gamegine. I am using this library for specifically this tutorial.
Code:
#include <HCSR04.h>
HCSR04 hc(5, 6); // 5 is Trig, 6 is Echo
const int pin = 10; // for LED
void setup() {
pinMode(10, OUTPUT); // Output pin for LED
Serial.begin(9600); // Start the serial communication
}
// Code by FustoF
void loop() {
float distance = hc.dist();
Serial.print(hc.dist());
Serial.println(" cm");
delay(100); // 100ms
/*I am adding condition for LED,
You can add different conditions for your projects
when something is between 10 to 70 LED remain off
Otherwise it will turn on*/
if (distance < 10 || distance > 70) {
digitalWrite(pin, HIGH);
} else {
digitalWrite(pin, LOW);
}
}
0 Comments