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.

  10. Tomi Engdahl says:

    Tiny Robot Shakes Head At You In Dissaproval

    If you don’t have enough things staring at you and shaking their head in frustration, [Sheerforce] has a neat project for you. It’s a small Arduino-powered robot that uses an ultrasonic distance finder to keep pointing towards the closest thing it can find. Generally, that would be you.

    When it finds something, it tries to track it by constantly rotating the distance finder slightly and retesting the distance, giving the impression of constantly shaking its head at you in disappointment.

    you should read [Sheerforce]’s code first: it’s a great example of documenting this for experimenters who want to build something

    Tiny Robot Shakes Head At You In Dissaproval

  11. Tomi Engdahl says:

    Garage Parking Sensor
    Ultrasonic parking sensor for garage mounting

    This gadget is ment as an alternative to the tennis-ball-meets-bumper type of parking aids.

  12. Tomi Engdahl says:

    HC-SR04 Isn’t the Same as Parallax PING))) But It Can Pretend to Be!

    “It’s only software!” A sentence that strikes terror in the heart of an embedded systems software developer. That sentence is often uttered when the software person finds a bug in the hardware and others assume it’s going to be easier for fix in software rather than spin a new hardware revision. No wonder software is always late.

    He wanted to use the less expensive HC-SR04 ultrasonic rangefinder in a prototype. Longer term he wanted to have the choice of either a Parallax PING or MaxBotix ultrasonic sensor for their better performance outdoors. His hardware hack of the SR04 made this a software problem which he also managed to solve!

    [Clint] was working with the Arduino library, based on the Parallax PING, which uses a single pin for trigger and echo. The HC-SR04 uses separate pins.

    modified the HC-SR04 sensor

    HC-SR04 Ping Sensor Hardware Mod

    If you intend to do your prototyping with the HC-SR04 module, you may find yourself having to write slightly customized code to drive the HC-SR04, which has one more pin compared to the Parallax ping sensor. This is because the HC-SR04 has separate pins for the trigger and echo function, where the Parallax module combines this functionality into one pin. For example, the Arduino “ping” example sensor sketch was written for the Parallax ping sensor and will not work “out-of-the-box” with the HC-SR04 as it only has provisions in the code for one signal pin.

    Well, there is a hardware hack you can perform on the HC-SR04 that will make if function virtually identical to the Parallax ping sensor. Simply connect a 10k ohm resistor across the ‘Trig’ and ‘Echo’ pin and remove the 10k pullup on the HC-SR04 attached to the ‘Trig’ pin

    This modification allows the ‘Echo’ pin to drive both the HC-SR04 ‘Trig’ pin and the Arduino ‘pingPin’ when it is in a high-impedance input mode during echo receive. Conversely it also allows the Arduino ‘pingPin’ to drive the HC-SR04 ‘Trig’ pin in output mode when triggering a pin

  13. Tomi Engdahl says:

    Bootstrapping Motion Input with Cheap Components

    Let’s get one thing straight: This device isn’t going to perform like a Leap controller. Sure the idea is the same. Wave your hands and control your PC. However, the Leap is a pretty sophisticated device and we are going to use a SONAR (or is it really SODAR?) device that costs a couple of bucks. On the plus side, it is very customizable, requires absolutely no software on the computer side, and is a good example of using SONAR and sending keyboard commands from an Arduino Leonardo to a PC. Along the way, I had to deal with the low quality of the sensor data and figure out how to extend the Arduino to send keys it doesn’t know about by default.

  14. Tomi Engdahl says:

    SRF01 Ultrasonic Sensor Teardown

    The SRF01 is a popular ultrasonic sensor used primarily for range finding applications. [Jaanus] discovered that they had a few flaws, including not working after being dropped. The faulty ones began to pile up, so he decided sensor_01to tear one apart and put his engineering skills to use.

    The SRF01 is unique in that it only uses a single transducer, unlike the SRF04, which uses two. Using only one transducer presents a problem when measuring very close distances.

    SRF01 teardown and reverse engineering

    I needed small ultrasonic sensors for a flying sensor. So I got the smallest one – SRF01. Quite nice unit, works down to 0 cm. There were some problems with it – Maximum detection frequency is only ~14 Hz and the resolution isn’t so great (1 cm).

    From component side: It has JST ZH series 3 pin connector for communication and power. Since the working voltage is 3.3 – 12 V it uses LP2980 3.3V voltage regulator to power all the components. The transducer used is 400PT from china/Multicomp. Received signal is amplified by MAX4232AKA dual 10MHz op-amp. Then it is fed to PIC24FJ16GA002 ADC.

  15. Tomi Engdahl says:

    El Cheapo Phased-Array Sonar

    Sonar is a great sensor to add to any small-scale robot project. And for a couple bucks, the ubiquitous HC-SR04 modules make it easy to do. If you’ve ever used these simple sonar units, though, you’ve doubtless noticed that you get back one piece of information only — the range to the closest object that the speaker is pointing at. It doesn’t have to be that way. [Graham Chow] built a simple phased-array using two SR04 modules, and it looks like he’s getting decent results.

    The hack starts out by pulling off the microcontroller and driving the board directly, a hack inspired by [Emil]’s work on reverse engineering the SR04s. Once [Graham] can control the sonar pings and read the results back, the fun begins.

    Spread Spectrum Phased Array Sonar

    Hacking two cheap HC-SR04 ultrasonic distance sensors and a launchpad to create a spread spectrum phased array Sonar.

  16. Tomi Engdahl says:

    Hacklet 91: Ultrasonic Projects

    Ultrasound refers to any audio signal above the range of human hearing. Generally that’s accepted as 20 kHz and up. Unlike electromagnetic signals, ultrasonics are still operating in a medium – generally the air around us. Plenty of animals take advantage of ultrasonics every day. So do hackers, makers, and engineers who have built thousands of projects based upon these high frequency signals. This weeks Hacklet is all about the best ultrasonic projects on!

  17. Tomi Engdahl says:

    Arduino Radar

    The project is very simple using only an ultrasonic sensor for detecting an object, a small servo motor used for rotating the sensor, an arduino board, and an algorithm for controlling the devices.

    Arduino Radar Project

  18. Tomi Engdahl says:

    Octosonar is 8X Better than Monosonar

    The HC-SR04 sonar modules are available for a mere pittance and, with some coaxing, can do a pretty decent job of helping your robot measure the distance to the nearest wall. But when sellers on eBay are shipping these things in ten-packs, why would you stop at mounting just one or two on your ‘bot? Octosonar is a hardware and Arduino software library that’ll get you up and running with up to eight sonar sensors in short order.

    HC-SR04 I2C Octopus “octosonar”

    The minimum setup to use this usefully requires

    a PCF8574 or PCF8574A IC
    two HC-SR04 sensors
    two NPN transistors and some resistors to make a NOR gate
    example sketch SonarI2Cv2

  19. Tomi Engdahl says:

    HC-SR04 I2C Octopus “octosonar”
    Connect 8 ultrasonic range sensors to an Arduino with I2C bus and one pin


Leave a Comment

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