Using an ultrasonic sensor with an Arduino

Arduino Uno tutorials

🕑 This lesson will take about 20 minutes

In this lesson, you will learn how to connect an ultrasonic sensor (HC-SR04) to an Arduino. An Ultrasonic Sensor is used to measure distance and can detect obstacles or nearby objects. 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 something or someone is in front of the sensor) and in an autonomous car (detecting and avoiding obstacles).

Required parts

For this project, you will need the following:

  • 1 x Arduino Uno microcontroller board

  • 1 x HC-SR04 Ultrasonic Sensor

  • 1 x Breadboard

  • 4 x Jumper wires (male-to-male)

Wiring schematic

The HC-SR04 has four pins:

  • VCC (this will connect to 5V on the Arduino)

  • TRIG (this we will connect to digital pin 12 on Arduino

  • ECHO (this will connect to digital pin 11 on Arduino

  • GND (this will connect to GND on Arduino)

We will connect these four pins on the HC-SR04 ultrasonic sensor to the Arduino board via a breadboard.

The code

Create a new sketch file using the Arduino IDE software and copy the following code to replace any existing code in your file. Save the file and upload the code to your Arduino Uno board. The following code will use the ultrasonic sensor to measure the distance between the sensor and an object in front of it. The distance measured will be stored in a variable called distance. The distance value will then be displayed in the serial monitor.

Once you have uploaded the code, keep the Arduino board connected to your computer and click Tools > Serial Monitor to display the readings from the ultrasonic sensor. Make sure you set the baud rate (in the dropdown box) to 9600 baud, otherwise you will see incorrect data displayed.