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

  20. Tomi Engdahl says:

    #40 Ultrasonic Distance Sensors Arduino Tutorial and Comparison for HC-SR04, HY-SRF05, US-015

    In this video I test three ultrasonic sensors for distance accuracy and opening angle. I also show how to use them in one pin and two pin configurations and I introduce a three sensor set-up for autonomous robots.

  21. Tomi Engdahl says:

    Measuring Air Flow with Ultrasonic Sensors

    Measuring air flow in an HVAC duct can be a tricky business. Paddle wheel and turbine flow meters introduce not only resistance but maintenance issue due to accumulated dust and debris. Being able to measure ducted airflow cheaply and non-intrusively, like with this ultrasonic flow meter, could be a big deal for DIY projects and the trades in general.

    The principle behind the sensor [ItMightBeWorse] is working on is nothing new. He discovered a paper from 2015 that describes the method that measures the change in time-of-flight of an ultrasonic pulse across a moving stream of air in a duct

    [ItMightBeWorse] is using readily available HC-SR04 sensor boards and has already done a proof-of-concept build.

    Building homemade ultrasonic air flow measurement device.

  22. Tomi Engdahl says:

    SonicScape (Binaural Vision Glasses for the Blind)

    Wearable vision technology for the visually impaired using ultrasonic sensors and a binaural soundscape environment

    The urban environment is a very difficult place to navigate and orientate yourself through, especially if you are a visually impaired person trying to live your life. That is why I have tried to come up with a technological solution that will help blind people know of their surrounding obstacles in an unknown environment without the help of a walking stick or a guide dog. Further from having a basic Arduino integrated system through the help of a pair of ultrasonic sensors (HC-SR-04) connected through bluetooth (HC-05, HC-06) , I want to also add some sort of GPS or RFID mapping system to the portable device which will allow the blind user to track themselves of where they are currently through a voice-activated agent. It will allow for family or relatives of the blind user to also track them of where they are through an app on their smartphone. That is what I am trying to achieve by the end of this project.

  23. Tomi Engdahl says:

    #40 Ultrasonic Distance Sensors Arduino Tutorial and Comparison for HC-SR04, HY-SRF05, US-015

    In this video I test three ultrasonic sensors for distance accuracy and opening angle. I also show how to use them in one pin and two pin configurations and I introduce a three sensor set-up for autonomous robots. I use an Arduino Leonardo to transfer the results to Excel.

    #9 Arduino Data Logger with Direct Input to Excel

  24. Tomi Engdahl says:

    How about replacing ultrasound with Laser?

    Shooting laser to measure distance

    I show you how to measure distance with this laser distance sensor. With the help of the Adafruit library is this I2C sensor an easy-to-use item.
    It’s emitting a laser beam of 940nm and is also known as Time-of-flight sensor
    Project page:

  25. Tomi Engdahl says:

    SonicDisc: A 360° Ultrasonic Scanner

    Who said autonomous driving was only for the premium car manufacturers? SonicDisc enables you to autonomously park like a pro for $10.

  26. Tomi Engdahl says:

    Hackaday Prize Entry: Sonic Glasses

    For his entry into the Assistive Technology part of the Prize, [Pawit] is building binaural glasses for the blind. It’s difficult to navigate unknown environments without a sense of sight, and these SonicScape glasses turn cheap distance sensors into head-mounted sonar.

    The glasses are built around a pair of ultrasonic distance sensors (the HC-SR-04, if you’re curious), mounted in a convenient 3D-printed enclosure that looks sufficiently like a pair of glasses to not draw too many glares.

    SonicScape (Binaural Sensor Glasses for the Blind)

    Obstacle detection glasses for the visually impaired using ultrasonic sensors and a binaural soundscape environment

  27. Abhay Kalmegh says:

    Thanks for sharing..can you please tell me how to connect hcsr-04 with raspberry pi b+ modal.

  28. Tomi Engdahl says:

    Ultrasonic Array Gets Range Data Fast and Cheap

    How’s your parallel parking? It’s a scenario that many drivers dread to the point of avoidance. But this 360° ultrasonic sensor will put even the most skilled driver to shame, at least those who pilot tiny remote-controlled cars.

    SonicDisc: A 360° ultrasonic scanner

    For some years now, I have been on a never-ending quest to discover the cheapest way for a miniature vehicle to position itself. One that performs decently that is. My latest idea involved the, less-than-a-dollar, HC-SR04 ultrasonic sensors to acquire a holistic view of the surroundings. But let’s take it from the beginning…

    The way I used the HC-SR04 ultrasonic sensors thus far was by triggering each to transmit an ultrasonic pulse, wait for it to reflect on an object and then determine how far away the object stood by the time it took for the “echo” to return. The problem with this lies in sequentially waiting for each measurement.

    Empirically, I know it takes more or less 10 milliseconds for each measurement to complete for ranges under 1.5 meters, common for miniature car applications.

    The solution was to execute the measurements in parallel. I checked out an article about using the HC-SR04 sensors with interrupts which verified the feasibility of the concept.

    Long story short, instead of waiting for each sensor to finish measuring, we initially trigger all sensors at once and then utilize the pin change interrupts to log down the echo arrival times. Finally, at a predefined interval we calculate the distance for each sensor. If an echo has not arrived yet, we consider the measurement as erroneous. The said interval is 10 milliseconds at the moment. This means we are able to conduct eight measurements in the time it took for a single one to be completed!

    SonicDisc is designed to transmit the calculated distances to another unit, e.g. a microcontroller or a Raspberry Pi. It “talks” over the widely-adopted I2C bus.

  29. Tomi Engdahl says:

    Beam-formed ultrasonic distance sensor

    Found a handful of the ubiquitous HC-SR04 ultrasonic sensors for cheap. Trying to teach them a new trick with beam forming for fast scanning and for a narrower beam width.

    Idealy the spacing between the elements would be less than a wavelength and preferably 1/4 wavelength. With the wavelength being aprox 14mm it makes it very difficult to pack the ultrasonic cans close enough. The last array had relatively large spacing. A redesign packed the sensors as close as possible.

    This array is still too limited to form arbitary beams. In combination with the already narrow beamwidth of the transducers, the side loves of the beam pattern formed by the array is suppressed. It might be possible to perform the scanning within a 30° range.


Leave a Comment

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