Easy AdSense by Unreal

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.

ultrasound1s

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).

ultrasound2s

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

http://www.arduino.cc/en/Tutorial/Ping

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:
Serial.begin(9600);
}

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);
delayMicroseconds(2);
digitalWrite(pingTrigPin, HIGH);
delayMicroseconds(5);
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(inches);
// Serial.print("in, ");
Serial.print(", ");
Serial.print(cm);
// Serial.print("cm");
Serial.println();

delay(100);
}

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: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
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:

[_setup_]
port=COM2
baudrate=9600

width=1000
height=201
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

[_default_]
min=-1
max=1

[Field1]
color=gray
min=0
max=255

[Field2]
color=red
min=0
max=255

Here is the output I got with SerialChart program:

serialchart_scaled

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

9 Comments

  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.
    Reply
  2. Tomi Engdahl says:
    Ultrasonic shoe sensors help the visually impaired
    http://www.edn.com/electronics-blogs/sensor-ee-perception/4422512/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.

    Reply
  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.
    Reply
  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. [...]
    Reply
  5. Tomi Engdahl says:
    Home Heating Hacking Part 1 or How to Measure an Oil Tank
    http://alaskanshade.blogspot.ch/2013/12/home-heating-hacking-part-1-or-how-to.html

    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.

    Reply
  6. Tomi Engdahl says:
    Good Vibrations: Giving the HC-SR04 a Brain Transplant
    http://hackaday.com/2014/03/17/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
    http://uglyduck.ath.cx/ep/archive/2014/01/Making_a_better_HC_SR04_Echo_Locator.html

    Reply
  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.
    Reply
    • 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..)
      Reply

Leave a Comment

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

*