Arduino and ultrasound distance sensor

I bought some time ago HC-SR04 Ultrasonic Sensor Distance Measuring Module to play with ultrasound distance measurements with Arduino Duemilanove 2009 Atmega 328P SCM Board.


The working principle of the HC-SR04 Ultrasonic Sensor Distance Measuring Module when the module get trigger “start” pulse, it sends eight 40khz square wave pulses and automatically detect whether receive the returning pulse signal. If there is signals returning, through outputting high level and the time of high level continuing is the time of that from the ultrasonic transmitting to receiving. So the pulse length tells the time of flight from sensor to measured distance and back. The HC-SR04 Ultrasonic Sensor Distance Measuring Module was wired to Arduino board with Male to Female DuPont Breadboard Jumper Wires (pretty useful accessory for prototyping with Arduino).


Arduino programming environment contains Ping example made for an ultrasonic range finder from Parallax. It detects the distance of the closest object in front of the sensor (from 2 cm up to 3m). It works by sending out a burst of ultrasound and listening for the echo when it bounces off of an object. The Arduino board sends a short pulse to trigger the detection, then listens for a pulse on the same pin using the pulseIn() function. The duration of this second pulse is equal to the time taken by the ultrasound to travel to the object and back to the sensor. Using the speed of sound, this time can be converted to distance.

The HC-SR04 Ultrasonic Sensor Distance Measuring Module has a little bit different interface, because it had separate pins for trigger and echo. This means that I needed to modify the example source code (was not too hard).

Here is my modified code (over 90% based on Ping example that comes with Arduino IDE 1.0.5):

/* Ping))) Sensor

This sketch reads a PING))) ultrasonic rangefinder and returns the
distance to the closest object in range. To do this, it sends a pulse
to the sensor to initiate a reading, then listens for a pulse
to return. The length of the returning pulse is proportional to
the distance of the object from the sensor.

The circuit:
* +V connection of the PING))) attached to +5V
* GND connection of the PING))) attached to ground
* Trigger connection of the PING))) attached to digital pin 7
* Echo connection of the PING))) attached to digital pin 8

created 3 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
by Tomi Engdahl

This example code is in the public domain.


// this constant won't change. It's the pin number
// of the sensor's output:
const int pingTrigPin = 7;
const int pingEchoPin = 8;

void setup() {
// initialize serial communication:

void loop()
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;

// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingTrigPin, OUTPUT);
digitalWrite(pingTrigPin, LOW);
digitalWrite(pingTrigPin, HIGH);
digitalWrite(pingTrigPin, LOW);

// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(pingEchoPin, INPUT);
duration = pulseIn(pingEchoPin, HIGH);

// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);

// Serial.print("in, ");
Serial.print(", ");
// Serial.print("cm");


long microsecondsToInches(long microseconds)
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See:
return microseconds / 74 / 2;

long microsecondsToCentimeters(long microseconds)
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;

This code outputs lines with two numbers (inches and centimeters) separated by comma. The communications speed is 9600 bps. Everything worked well with TeraTerm. The output was two numbers per line separated with comma outputted at 9600 baud rare. The numbers tell the distance in inches and centimeters.

Now time to try to get some graphs. This could be down in many ways, for example using Processing like in Graph example, Realtime Plot of Arduino Serial Data Using Python, Graphing with Excel or use application specifically made for this like SerialChart.

SerialChart is an open source application for charting data sent via RS-232 port in real time. I had used the software earlier successfully, read the documentation and checked SerialChart Tutorial, but for some reason I could not get data from Arduino that was mapped to COM11. I finally found that I had the same issue issue that was mentioned at Serial chart says that the com port is busy when its not page:

This a problem that comes from the qt serial library. So I will not be fixing that but as a workaround I want to let you know that you’re not stuck with high-numbered ports that Windows assigns , you can change them to something lower than 10, for example COM7 , COM5

I configured Arduino USB serial port number to COM2 and now SerialChart worked well.

SerialChart configuration I used:


background_color = white

grid_h_origin = 100
grid_h_step = 10
grid_h_color = #EEE
grid_h_origin_color = #CCC

grid_v_origin = 0
grid_v_step = 10
grid_v_color = #EEE
grid_v_origin_color = transparent




Here is the output I got with SerialChart program:


Now I can visually see what the sensor senses and also see the numeric values.


  1. fastest way to get pregnant says:
    I pay a quick visit each day a few sites and information sites to read posts, but this web site offers feature based writing.
  2. Tomi Engdahl says:
    Ultrasonic shoe sensors help the visually impaired

    Denver Dias, as part of his undergraduate studies, set out to create a new interface to help with environmental awareness for those who cannot see.

    His concept was to move the obstacle detection out of the hands of the person. He is accomplishing this by mounting an array of ultrasonic sensors around some tennis shoes. The concept behind this prototype is that any obstacle will be detected and a physical notice will be given to the wearer in real time.

  3. Cleo Pizzella says:
    Have read a number of using the articles in your site today, and I really like your style of running a blog.
  4. Halloween hacking ideas « Tomi Engdahl’s ePanorama blog says:
    [...] Here is one really scary looking lantern. Fire Breathing Jack-O-Lantern of Death page tells about a very dangerous Halloween effect hack. This isn’t a new idea but it is a very unique and simple implementation based on re-purposing existing commercial products controlled with Arduino + ultrasound distance sensor. [...]
  5. Tomi Engdahl says:
    Home Heating Hacking Part 1 or How to Measure an Oil Tank

    Unless I go out to the tank regularly and check it with a dipstick, I have no idea how fast or slow we are using up the tank.

    There is really only one product already on the market that is similar to what I want: The Rocket. It is $120, only reads in 10% increments and just displays on the receiver. Without hacking the wireless protocol that is being used, there is no way to do automatic data logging and a 60 gallon granularity is not optimal for the analysis I want to be able to do.

    Ultrasonic sensors – there are a lot of different ultrasonic sensors. There are expensive industrial models and cheap ones that are often used in hobby robotics. After looking at several different sensors, I picked up a Maxbotix EZ4 (more on these later).

    I started out with the EZ4 sensor mentioned above. This sensor is versatile and simple to use. It has circuitry onboard that does most of the work and communicates the results as an analog voltage, PWM or RS232 signal. The down side of this sensor is that it only offers 1-inch resolution which is about 15 gallons in the middle of the tank, but something that works is better than nothing and I can swap it out later.

  6. Tomi Engdahl says:
    Good Vibrations: Giving the HC-SR04 a Brain Transplant

    [Emil] got his hands on a dozen HC-SR04 ultrasonic sensors, but wasn’t too happy with their performance. Rather than give up, he reverse engineered the sensor and built an improved version.

    [Emil] reverse engineered the schematic of the HC-SR04 and found some interesting design decisions.

    A mask programmed microcontroller manages the entire unit, commanding the ultrasonic transmitter to send 40Khz pulses, and listening for returns on the receive side of the system.

    [Emil] solved these problems by creating his own PCB with an ATtiny24 and a 12MHz crystal

    Making a better HC-SR04 Echo Locator

  7. ajin says:
    dear friends,
    can i detect an object at a particular distance, means i want an output high when 5 cm distance is reached, what changes have to made in this program please help me.
    • Tomi Engdahl says:
      You just need to write a suitable Arduino software to detect the distance you want.
      Use Arduino to measure the distance, and then compare the result to your reference distance that that should be reached.
      When the distance is reached do whatever needs to be done (for example turn output pin on/off, send message to PC etc..)
  8. Johnd194 says:
    Really wonderful information can be found on web blog.
  9. Tomi Engdahl says:
    A Virtual Touchscreen (3D Ultrasonic Radar)

    Producing items onto a screen simply by touching the air is a marvelous thing. One way to accomplish this involves four HC-SR04 ultrasonic sensor units that transmit data through an Arduino into a Linux computer. The end result is a virtual touchscreen that can made at home.


Leave a Comment

Your email address will not be published. Required fields are marked *