Using an Ultrasonic sensor with Arduino

This short tutorial introduces HC-SR04 Ultrasonic sensor. It is assumed you have installed the Arduino IDE and have some basic understanding of using electronics and wiring a breadboard. If you want to learn more or if anything is unclear, check out this extensive tutorial. Although in this example we use a display, you can also do without it.

To use this sensor, you can connect it to power (GND and VCC, this must be 5V) and connect the Trig and Echo pins to pin 4 and 5 of the Arduino:

(click the image to enlarge it)

You can mount the sensor directly onto a breadboard:

Download example sketch

To test this sensor, you can use this example sketch: ultrasonic_sensor_with_display.ino. If you do not use a display, you can use this one: ultrasonic_sensor_HC-SR04_newping.ino. Open the sketch in the Arduino IDE. The sketch uses the Newping library, which you must install before you use this sketch. In the Arduino IDE, select Tools > Manage Libraries, then search for “Newping” and install the library.

Check the sketch

Before you upload the example sketch to the Arduino, verify the lines with #define TRIGGER_PIN and #define ECHO_PIN are set with the correct pins (4 and 5):

#define TRIGGER_PIN  4  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     5  // Arduino pin tied to echo pin on the ultrasonic sensor.

Next, hook up the Arduino to your computer with the USB cable. Configure the Arduino IDE to use the correct setting for the type of Arduino you use: under the Tools menu, check the board settings:

The Port can be any active Port (eg. COM1-12). After you have connected the USB cable and the Arduino has power, there should be one option you can select here. Also make sure you have selected the ‘Old Bootloader’ version at “Processor”.

Upload the sketch

Run the sketch (press the Upload button Upload button ). The display should show the distance as read by the sensor. If you do not use a display, you can see the distance in the serial monitor, which you can start via the Serial monitor icon in the top right corner.

Now find the line of code which looks like:

unsigned int distance = sonar.convert_cm(sonar.ping_median(5));

This is the line which reads the distance value from the sensor and assigns it to the variable distance. It uses the method ping_median(5), which will do 5 readings in a short time and takes the median of the five readings and returns that value. This will improve the accuracy of the readings.

More information