Electorials Electronics
Published © GPL3+

Project 002: Arduino HC-SR04 Ultrasonic Sensor Project

A beginner to mid-level project utilising an inexpensive ultrasonic sensor, an Arduino and some intermediate code language.

BeginnerProtip12 minutes4,032
Project 002: Arduino HC-SR04 Ultrasonic Sensor Project

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
You could use any other Arduino board as well. The Keyestudio Uno is used in this example.
×1
USB-A to B Cable
USB-A to B Cable
Depends on the Arduino.
×1
Jumper wires (generic)
Jumper wires (generic)
4 Male to Male Jumper Wires.
×4
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Breadboard (generic)
Breadboard (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Circuit Diagram

Schematics

Code

Arduino HC-SR04 Ultrasonic Sensor Project Code

C/C++
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
  
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
  
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
  distance = duration/58.2;
  if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
    Serial.println("Can't read");
    digitalWrite(LEDPin, HIGH);
}
else {
  
/* Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
  Serial.println(distance);
  digitalWrite(LEDPin, LOW);
}
//Delay 50ms before next reading.
delay(50);
}

Credits

Electorials Electronics

Electorials Electronics

85 projects • 63 followers
I'm an electronic hobbyist interested in anything, from Arduino to drones. I plan to educate people with the content on my website.

Comments