Using an ultrasonic sensor with Arduino

In this tutorial, you will learn how to connect an ultrasonic sensor (HC-SR04) to an Arduino. An Ultrasonic Sensor is used to measure distance. It emits ultrasound at 40,000 Hz (40kHz) which travels through the air and bounces off obstacles in its path back to the ultrasonic sensor module. The travel time of the ultrasound is then used to calculate the distance between the ultrasonic sensor and the obstacle. The HC-SR04 sensor can detect obstacles between approximately 2 to 450cm range.

Ultrasonic sensors can be used in a range of Arduino projects, for example, sensor lights (turning on a light when movement is detected) and in an autonomous car (detecting and avoiding obstacles).

For this project, you will need the following:

  • Arduino Uno microcontroller board
  • Breadboard
  • HC-SR04 Ultrasonic Sensor
  • Jumper wires (male-to-male)

Wiring schematic

The HC-SR04 has four pins:

  • VCC (which will connect to 5V on the Arduino)
  • TRIG (which we will connect to digital pin 12 on Arduino
  • ECHO (which we will connect to digital pin 11 on Arduino
  • GND (which will connect to GND on Arduino)


The code

Here is the code:

// HC-SR04 Ultrasonic sensor range test

#define echoPin 11 // attach pin D11 on Arduino to ECHO pin on ultrasonic sensor
#define trigPin 12 // attach pin D12 on Arduino to TRIG pin on ultrasonic sensor

long duration; // duration of sound wave travel
int distance; // distance measured

void setup() {
  pinMode(trigPin, OUTPUT); // set trigPin as OUTPUT
  pinMode(echoPin, INPUT); // set echoPin as INPUT
  Serial.begin(9600); //Start serial communication at 9600 baud rate

void loop() {
  // clear trigPin condition
  digitalWrite(trigPin, LOW);
  // Sets trigPin to HIGH for 10 microseconds
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  // Read the echoPin and return the travel time of sound wave in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculate distance travelled
  distance = (duration - 10 ) * 0.034 / 2; // Speed of sound wave divided by 2 (out and back)
  // Subtract 10 from duration because of earlier 10 microsecond delay
  // Display the distance measured in cm in the serial monitor
  Serial.print("Distance: ");
  Serial.println(" cm");

Upload the code to the Arduino. In the Arduino IDE, click Tools > Serial Monitor and set the baud rate (in the dropdown box) to 9600 baud to view the ultrasonic sensor readings received from the Arduino when it is connected via USB to the computer.