Ultrasonic Distance sensor using HC-SR04

Tips, Tricks and methods for programming, learn ways of making your programming life easier, and share your knowledge with others.

Moderators: Benj, Mods

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

These sensor modules can be picked up from ebay for as little as £2 from china or Hong Kong or £4 from UK.
They work at 5V, and interface directly with microcontroller so do not require any external components for interfacing.

Attached is a flowchart created with V5 to measure the distance of an object (from about 3cm to approx 200cm! )
Ultrasonic1.png
(5.99 KiB) Downloaded 32854 times
It is reasonably accurate. (approximately +/- 1cm due to pic maths)
I have tested on hardware, and please with results.

Next version I will creating will be even more accurate and using interrupt for detection,
since this version does not use interrupts (so you can use any pins for detection).

I have used 16F883 with LCD connected to port A and HC-SR04 connected to portB (pusle on B1 and echo on B0)
Hope you find this useful.

I do plan on creating a tutorial on using HC-SR04 in the very near future.

If you have not got Flowcode V5, I do highly recommend tying it.
You can download the free version from here:
http://www.matrixmultimedia.com/lc_index.php?p=25

Martin
Attachments
Distance Sensor 16F883 V1.fcf
(11 KiB) Downloaded 2754 times
Martin

Mark
Posts: 209
Joined: Thu Oct 19, 2006 11:46 am
Location: Bakewell, UK
Has thanked: 20 times
Been thanked: 16 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by Mark »

Great, Thanks, I have just ordered two HC-SR04 on the basis of this.
Looking forward to the tutorial.

Mark
Go with the Flow.

User avatar
Benj
Matrix Staff
Posts: 15312
Joined: Mon Oct 16, 2006 10:48 am
Location: Matrix TS Ltd
Has thanked: 4803 times
Been thanked: 4314 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by Benj »

Yep I can see me playing with some of these too in the near future. Thanks Martin :D .

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

It's worth getting module. What made it really easy was having EB070 E-blocks test pod (a fantastic product, well worth investing in) and it was monitoring the waveforms on the pulse and echo lines.

From experimenting I noticed that the pulse can either be positive going or negative going.
I did wonder why some data sheets showed normally high with line going low for 10us, and other datasheets showed normally low and pulse going high for 10us
When I created interrupt version, I'm thinking of adding beeping that has time between beeps decreasing when object get nearer + switch to deactivate.
It could be then used as a vehicle reversing monitor, so you don't need to view LCD in order to safely reverse.

Note: This is not the version that's in the Book Microcontroller Systems Engineering by Bert van Dam that John mentioned.
So that least there is now two version to try.

Martin
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Hi Martin .

Just tried you flowchart with my SRF05 module, it works fine. These are almost identical the the SRF04 used in Berts book.

Main difference is it has a mode pin which allows the pulse to share the same pin as echo. Connect mode pin to ground to enable this.

Note this does not work with the SRF04, pin 4 on this should not be connected to anything (As far as i can tell from the data sheet)
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

JohnCrow wrote:

Main difference is it has a mode pin which allows the pulse to share the same pin as echo. Connect mode pin to ground to enable this.

Note this does not work with the SRF04, pin 4 on this should not be connected to anything (As far as i can tell from the data sheet)
Hi John Im using HC-SR04 which will have it's little differences to SRF04. One of the data sheets:
http://jaktek.com/wp-content/uploads/20 ... C-SR04.pdf
There are 4 pins on the HC-SR04 ( VCC, Trig, Echo & GND) so it makes connections and flowchart design a doddle.

For the calculations I just use number of times 100us delay occurred while Echo line is high X 100 then device by 58 which is what I got from Ben and my calculations to confirm number.
in Berts book he divides by 4.
Not tries that flowchart yet as I only got HC-SR04 yesterday evening so wanted to made up a flowchart that would hopefully work.
This is what I bought:
http://www.ebay.co.uk/itm/1x-HC-SR04-Ul ... 4ab6bd0653
It was worth the extra £2 as delivery was only 2 days (ordered on sunday, seller posted when post office opened on Monday goods arrived tuesday)instead of 22 odd days from china
Postage is free.

Martin
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

These sensor modules can be picked up from ebay for as little as £2 from china or Hong Kong or £4 from UK.
They work at 5V, and interface directly with microcontroller so do not require any external components for interfacing.
The SRF05 is about £17.00 (depending on supplier) and these look to be just as good quality going by the photos.

Also I noticed they have a crystal on them, maybe they could be more accurate than the SRF05
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

JohnCrow wrote: Also I noticed they have a crystal on them, maybe they could be more accurate than the SRF05
I have used USB test pot to measure the duration of the echo = 1.17ms (1170us) of an object 207mm from front edge of sensor.
Room temperature was measured at 21.7deg C
object 207mm away.png
(86.32 KiB) Downloaded 32819 times
Using fromula:
Distance = duration(us)/2*331.5+0.6*Room_Temperature m/s
Since answer is in m/s divide by 1000 to get mm/us

= 1170/2*0.34452

= 201.54mm
so accuracy = (201.54-207)/207*100 = -2.6%. This is very good considering some rounding in the calculations

LCD dispalyed 20cm

Martin
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

I'll set my sensor up the same as yours and see what results I ger
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

JohnCrow wrote:I'll set my sensor up the same as yours and see what results I ger
Sounds like a good idea John.

From what I have read SRF05 is superior to HC-SR04

So results and to compare them will be interesting.

I am working on the interrupt version now.

I have ruled out setting a timer interrupt up to rollover every 100us
So left with two options.

1) Set up CCP to capture and compare port interrupt
or
2)set timer to rollover every 6.4ms. then timer register is incremented every 256/6.4ms = 25uS.
Then when port change detected, timer os reset to 0, then second port change detcted timer value is read.
The total time of pulse is timer value * 25us
So in theory should be more accurate is counting lots of 100us.
(Well my theroy and actual practice could be two different things :lol: )

Will post on here when finished.

Martin.
Martin

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

Hi John,
did you get a chance to set your sensor up and obtain any results?
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Now that is strange.

I put a post about it here last night and its vanished, I'm sure I sent it.(And that was before I went to the pub :lol: )

But no, didnt have chance to test it with the pod, using a ruler its reading about 1 cm low. Same result with your program and the one from Bert's book.
i.e distance 17cm indicated 16cm.
Will set up and test the pod over the weekend.
1 in 10 people understand binary, the other one doesn't !

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Hi Martin

This is a screen shot of my pod output

The gap was set to 14.336cm (The lenght of a plastic box measured with a digital vernier)
The display shows 15 cm
Ultrasonic-Pod.jpg
Ultrasonic-Pod.jpg (111.52 KiB) Viewed 62800 times
Using your calculations
884.224 us equates to 15.23 cm

Which is about 5% error. Not as good as your sensor.
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

Hi John thanks for your reply.
I now find if I have Cursor Insta-measure set for Width, then by hovering mouse on the data line to be measured, the with is instantly shown without clicking on anything:
14.3cm.png
(109.47 KiB) Downloaded 32739 times
My result at 14.3cm

I'm struggling with measuring using interrupts.
I worked out if use timer0 set for an interrupt frequency of 1/(50us*256) =78.125Hz
then every count of the register will equate to 50us.
If roll-over once then microseconds = microseconds +256*50
All detections appear to be correct but retrieved timer value is not quiet correct yet.
Getting nearer.

Edit: yay :idea: worked out what was going wrong :)


When finished (if I can finish it of course, then it will be compatible with 16F88. I.e LCD and detection will be on bortB)

Martin

Edit: looks like you already got width selected, so you already knew that. :lol:
Martin

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

Here is a version that uses timer0 and port interrupts to work,
If someone would like to try it.
Not claiming accuracy is any better than the previous version.
Target is 16F88 or any other device that had at least 4K memory (added a float variable)

LCD is connected to portB (0 to 5)
Trigger is portB7 and Echo is portB6

As stated on an above post, using interrupts, I did find it difficult to measure a pulse accurately that is between 150us and 25ms.


Martin
Attachments
Distance Sensor 16F88 V2.fcf
(21.76 KiB) Downloaded 1517 times
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Hi Martin

Just tried your new version
It works fine

Distance = 16cm
Indicated = 16.5cm

Using test pod = 998.335us
Calculated = 17.19cm

Get the same results with a 16F877A and display on port a / sensor on port b
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

Hi John,
Thanks for testing flowchart.
The Distance variable is the value of microseconds that requires division of 58
Since using interrupts:
To have more room for adding addition functions, float and string can be removed and just use Distance = Distance / 58
JohnCrow wrote: Distance = 16cm
Indicated = 16.5cm

Using test pod = 998.335us
Calculated = 17.19cm
I guess there will always be an error of AT LEAST 3/4 of cm since sensor element it'self is about 3/4 cm back from the front surface.
17.19-0.75 = 16.44cm

Therefore calculation maybe more sound <pun :lol: than we first think?
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

I guess there will always be an error of AT LEAST 3/4 of cm since sensor element it'self is about 3/4 cm back from the front surface.
Good point never though about it that way

Ive mounted the sensor on a small pcb so the front edge of the pcb is approximatly where the sensor element will be.
Using this as a reference it seems to be quite accurate now. Will try this on the test pod.

Ive have also added a temperature sensor to the board. May try modifying the program to compensate for air temp. Though I dont think it will make a lot of difference at around room temperature levels.
Distance Sensor.JPG
Distance Sensor.JPG (107.12 KiB) Viewed 62748 times
1 in 10 people understand binary, the other one doesn't !

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Hi Martin

This seems to have made it a lot closer
Using your interupt flowchart

Distance = 22cm
Indicated Distance 22.1 cm
Time 1297.856 us
Calculated 22.35cm
1 in 10 people understand binary, the other one doesn't !

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Hi Martin
Put your calculation into a simple spreadsheet to calculate values from echo duration.

Try changing the temperature values, it makes a bigger difference than I though it would.
Temperature Compensation Calculator.zip
(7.52 KiB) Downloaded 1086 times
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

Hi John,
Thanks for useful additional information you have supplied.
I have had a play with excel, and yes I agree with you.
The higher the temperature the worse the error is going to be,

For Flowchart posted here:
http://www.matrixmultimedia.com/mmforum ... 694#p35378

Equipment used:
Flowcode V5
EB006 Programming board
16F88 microcontroller. (Any microcontroller can be use so long as full port b is available and memory is at least 4K of rom)
EB005 LCD
HC-SR04 semsor module (cost £4.50 inc postage from uk). See Ebay link on an earlier post.
Connections to sensor:
HC-SR04.png
(128.81 KiB) Downloaded 32595 times

How Flowchart works
1) Enable variable is set to 1 and Send 10us positive pulse on the trigger line connected to port B7

2) portB interrupt on change (IOC) waits for positive going pulse on Echo line port B6 (only waits for pulse when enable is set for 1)

3) When this positive going pulse on B6 is detected then :

Code: Select all

Count = 0
RollOver = 0
Microseconds = 0
tmr0=00;
4) Timer0 is set for 300Hz. This means every 1/300 = 3.3ms timer will rollover and every time it does: RollOver = RollOver+1
3.3ms is far too long for time measurement of 100us to 25ms ,and I found using interrupt of 100us was too quick to run all the other non-interrupt routines like updating LCD.
So the idea I had was to set timer0 to 0 (tmr0=00;) when IOC =1, allow timer0 to increment tmr0 register every 1/300 /256 = 13us.
The minimum resolution is 10’s of us. If the object is far away so timer0 rolls over then that would add 13*256 = 3328us to the total elapsed time.
Number 256 is used because timer0 Rollsover when 1 is added tmr0 register and it goes from 255 to 0 so that is 256 counts. That is when program pauses, runs timer0 macro, then resumes from the point it was paused from.

5) When Echo line goes from high to low the value of timer0 register is read and place into a variable called count: (FCV_COUNT = tmr0;).
Enable is set to 0 to prevent contents of timer0 register changing before the LCD has had a chance to update.
The total elapsed time in microseconds is: Count * 13 + RollOver * 3328
E.g if Count = 29 and RollOver = 1 then total time elapsed =

Code: Select all

29*13 + 1*3328 = 3705 us


6) According to Benj, data sheet and my calculations (see below) distance(in cm) = us/58
So distance of object = 3705/58 = 63.9cm
If a shorted distance is measure e.g Count = 93 and RollOver = 0 then Distance cm =

Code: Select all

 (93*13 +0*3328)/58 =  20.8cm
I have used a float variable to calculate results :

Code: Select all

Result = int2float (Distance)
Result = fdiv (Result,58)
Result_String = FloatToString$ (Result)
So decimal point can be placed in the correct 1 decimal place with up to only 4 numbers
Eg. 99.9 or 104 I have used:

Code: Select all

Result  <  99.9 then  Result_String = Left$ (Result_String,4)
What this means is If distance in cm is less than 99.9 then just display first 4 characters (including decimal point)
If the value is grater 99.9 then display all 5 characters since more Characters are required to still display to 1 decimal point.
e.g 201.4

Have fun with sensor and I will post some more flowcharts with added functions in the near future.

Martin
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Hi Martin

Ive just tried changing your first program to allow for temperature compensation.
I can get the temperature to display correctly, but the calculation for the temp correction makes it show a low reading.
15cm shows about 13.5cm. But the shorter the distance the closer to the true value is shown.
But If I disable that macro the distance is back to the correct reading.
Need to look have another look at my calculations. Temp is currently 25°C thats about 5°C warmer than Sunday.
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

Hi John, I'm currently removing the float number.
I will change the maths to allow temperature compensation.
If successful will post update.
I'm sure between us both, we can come up with something that works. :)

Martin
Martin

User avatar
JohnCrow
Valued Contributor
Valued Contributor
Posts: 1367
Joined: Wed Sep 19, 2007 1:21 pm
Location: Lincolnshire
Has thanked: 364 times
Been thanked: 716 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by JohnCrow »

Hi
This is my first test program
Distance Sensor 16F877A - Temp Compensation.fcf
(19.87 KiB) Downloaded 1313 times
1 in 10 people understand binary, the other one doesn't !

medelec35
Matrix Staff
Posts: 9520
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2585 times
Been thanked: 3815 times
Contact:

Re: Ultrasonic Distance sensor using HC-SR04

Post by medelec35 »

Hi John,
Thanks for you latest post, it's going to be a few hectic days ahead, but I will see if I get time to analyze whats going on, and post my own version.

Martin
Martin

Post Reply