HC-SR04 (Ultrasonic Distance Sensor) Arduino Tutorial

by BusyBird15 in Circuits > Microcontrollers

533 Views, 3 Favorites, 0 Comments

HC-SR04 (Ultrasonic Distance Sensor) Arduino Tutorial

104_0067.JPG

The HC-SR04 Ultrasonic Distance module is a simple device to measure the distance between itself and another object using ultrasonic sounds bouncing off of the obstacle. This tutorial will demonstrate the use of the sensor without using any additional libraries. I made the code flexible so that it will be easy to adapt to any project.

Supplies

104_0065.JPG
  • HC-SR04 Ultrasonic Distance Sensor
  • An Arduino board (I'm using the Arduino Nano Every)
  • A breadboard (Any size will do)
  • 4 male-to-male jumper wires

Connections

HC-SR04-ultrasonic-distance-sensor-with-Arduino-wiring-diagram-schematic-tutorial-768x372.jpg

Connect the pins of the ultrasonic sensor as shown in the image. (Credit: MakerGuides.com)

VCC > 5v

Trig > digital 2

Echo > digital 3

GND > gnd

Code

Here is the code I used to test the sensor. You can download it from the end of this step.

const int trigger = 2;
const int echo = 3;


int getUltrasonicDistance(){
  // Function to retreive the distance reading of the ultrasonic sensor
  long duration;
  int distance;

  // Assure the trigger pin is LOW:
  digitalWrite(trigger, LOW);
  // Brief pause:
  delayMicroseconds(5);

  // Trigger the sensor by setting the trigger to HIGH:
  digitalWrite(trigger, HIGH);
  // Wait a moment before turning off the trigger:
  delayMicroseconds(10);
  // Turn off the trigger:
  digitalWrite(trigger, LOW);

  // Read the echo pin:
  duration = pulseIn(echo, HIGH);
  // Calculate the distance:
  distance = duration * 0.034 / 2;
  
  // Uncomment this line to return value in IN instead of CM:
  //distance = distance * 0.3937008

  // Return the distance read from the sensor:
  return distance;
}


void setup() {
  // Define inputs and outputs:
  pinMode(trigger, OUTPUT);
  pinMode(echo, INPUT);

  // Start the serial monitor:
  Serial.begin(9600);
}


void loop() {
  // Print the distance to the serial monitor:
  Serial.print("Distance: ");
  Serial.println(getUltrasonicDistance());

  // Wait one second before continuing:
  delay(1000);
}

Test and Results

104_0069.JPG
Screenshot 2023-09-10 17:18:51.png

Open the code and upload it to your Arduino board. Open the serial monitor and view the results. Place an object in front of the sensor. I have found this code to be accurate from 0-2 cm (0-1 in.). In your program you can easily call:

getUltrasonicDistance()

to get the sensor reading. Happy coding!