Claim Your: Useful

"Arduino Software Guide"

   Right Now...



A PIC Ultrasonic distance meter project using a Seven Segment display and a PIC micro.

The PIC Ultrasonic distance meter works by transmitting a short pulse of sound at a frequency inaudible to the ear (ultrasonic sound or ultrasound).

Afterwards the microcontroller listens for an echo.

The time from transmission to echo reception lets you calculate the distance from the object.

PIC sonar ultrasonic range finder

PIC Ultrasonic Distance Meter Specification

Range ~5cm - 300cm (approx.)
Accuracy +/-3cm
Transducer frequency 40kHz
Internal oscillator frequency 4MHz

The project uses 5 standard transistors to receive and transmit the ultrasound and a comparator to set the threshold echo detection level - so there are no special components other than the microcontroller and the ultrasonic TX/RX modules which are standard 40kHz types.

Note: As you approach 300cm it is more difficult to receive a reflected signal so the practical range is probably nearer 200cm. The SR04 unit will perform better since it uses higher gain opamps.

Design

This design is experimental and educational since you can buy ready made modules such as the SR04 which are undoubtedly convenient - you supply a pulse trigger and they provide a distance (pulse width coded). These are quick and very easy to use but do not demonstrate what is going on. 

This design uses external components, comparators and transistors to achieve the same result.

The 16F88 also has a built in comparator and reference level generator which would save components but this design can be used with any microcontroller that has a capture module. It is probably possible to use it with a 16F84 using some careful coding for time measurement.

Specification

Note that the internal oscillator of the PIC micro is used and this saves two pins - that can be used as normal I/O pins.

Compiler Mikroelectronika MikroC compiler Free!
Target 16F88 (retargetable to other PICs that have a CCP module).
Software level Medium.
Software notes Drives multiplexed display, controls CCP, interrupt use.
Hardware level Medium.
Hardware notes High gain transistor amp.
Project version 1.03
Project files Enter your details to get the Download Link
and get the microcontroller newsletter:


(Your email is safe it will never be sold or rented).
You will get All the C source code and hex file.

Note: Check your email for the project code download link.

You can recompile the project files if you want examine code operation (using the built in simulator) or change the source code. Note the hex file is contained in the download so you do not have the recompile the source code.

How the PIC Ultrasonic Distance Meter works

The time from transmission of the pulse to reception of the echo is the time taken for the sound energy to travel through the air to the object and back again.

Since the speed of sound is constant through air measuring the echo reflection time lets you calculate the distance to the object using the DST equation :

Distance = (s * t)/2 (in metres)

You need to divide by 2 as the distance is the round trip distance i.e. from transmitter to object and back again.

Where:

s [m/s] the speed of sound in air
t [s] the round trip echo time.

Some delay times:

Round trip echo time Distance
t = 588us 10cm
t = 5.8ms 1m

Note: The speed of sound in air is more or less constant at 330m/s (@ 0ºC) - it varies mainly with temperature (~340m/s @ 20ºC). In this project I am using a value of 340m/s i.e. it is assumed that the project is used indoors. You can change it to whatever you like by modifying the code.

You can get ultrasonic transducers optimized for 25kHz, 32kHz, 40kHz or wide bandwidth transducers. This project uses a 40kHz transducer but it will still work with the others if you make simple changes to the software. The receiver and generator circuits will work as they are.

Note: If you use a different transducer you must change the software to generate the correct frequency for the transducer as they only work at their specific operating frequency.

The 40kz signal is easily generated by the microcontroller but detection requires a sensitive amplifier. I have used a three transistor amplifier for the receiver.

This is followed by a peak detector and comparator which sets the sensitivity threshold so that false reflections (weaker signals) are ignored.

CCP - Capture mode

This project makes use of the CCP module (in its capture mode) to accurately measure the signal reception time at the CCP port pin. When a signal triggers the CCP module the value of timer 1 is stored in a CCP register (or captured).

If you store the value of timer 1 and then enable the CCP after transmitting an ultrasound pulse the CCP will trigger when the comparator activates i.e. as soon as an ultrasonic echo is received.

Subtracting the stored value from the CCP register value gives the time delay in machine cycles. Since the project uses a 4MHz main clock then the time delay will be measured in micro-seconds.

PIC Ultrasonic Distance Meter Practical limits

The minimum distance of this scheme is about 5cm. Looking at the output of the first receiver amplifier shows a that it should be more accurate at lower distances - it is inaccurate by about 2cm which is still quite good. Probably the addition of amplifiers for the longer range stops accurate short range operation.

The maximum distance is limited by the sensitivity, gain and noise performance of the receive amplifier and also the transmit power and duration of transmission.

For this circuit the maximum distance is about 3m.

PIC ultrasonic distance meter circuit.
(Click diagram to open a pdf).


ultrasonic pic range finder circuit



The previous design incorrectly used RA5 as output and it is the MCLRn pin that can only be used as an input. So RA5 drive to the seven segment was removed and the DP pin (Decimal Point) is left unconnected. RA6 and RA7 were moved up one 7 segment drive position.

Click to view Bill of materials (parts list).

PIC Ultrasonic distance meter Hardware

You can use any PIC microcontroller that has an internal CCP module and enough memory to hold the program and youcan program the PIC in circuit through the ICSP connector.

The circuit uses a three transistor amplifier and a two transistor output driver and it can be constructed out of standard component). The comparator is a well known M311 type (you could even use an opamp as a comparator, with suitable circuit changes, as this system is not particularly high speed).

PIC Ultrasonic Distance Meter hardware block diagram
pic sonar ultrasonic schematic circuit

Transistor Amplifiers

First of all why use them?

I wanted to see what you could do using only transistors and it seems that you can do quite well i.e. the system works to the same distance as other designs using op-amps.

Of course when using op-amps you can achieve lower power operation and use less components.

Transistor amplifier design

The first two transistor amplifiers use standard biasing to set the output at the collector in the middle of the supply. If you look at the dc conditions the two (100k) input bias resistors across 5V to 0V set the input bias point at 2.5V. When the Vbe voltage is dropped across the transistor's emitter junction the voltage at the emitter is Vbias - 0.6 (approx 2V). So the emitter current =2/2k2 ~ 1mA. Ic=Ie. So the dc bias point is 5V-IcRc 2.7k*1mA ~ 2.5V.

The AC gain of these transistors is RC over RE (but at AC the capacitor has impedance of 40Ohms at 40kHz) so the effective Re is the intrinsic transistor emitter resistance (re~25ohms) plus the impedance of the capacitor (re is temperature dependent). So the gain is 2k7/65 ~ 40. If used at different temperatures you will get some gain variation.

The last transistor uses fixed biasing to set the bias point. For a more stable amplifier (less affected by Beta variation) use the same amplifier as the other two. I have just used it to see how it works as it can be seen quite often in other circuits and it seems to work well. It will however be dependent on the exact transistor used (its Beta value) and it will also be dependent on temperature - which will both affect its bias point and gain.

The comparator is setup as a standard circuit will a small amount of hysteresis (to stop oscillation if the input changes slightly) - the 1M ohm feeds back to set the hysteresis level.

Setting up the PIC Ultrasonic distance meter.

PIC Ultrasonic Distance Meter: Oscilloscope setup

Using an oscilloscope monitor the signals RB3 and RB0. Use RB3 as the trigger as this is the signal that regularly generates the ultrasound. RB0 is the detected echo.

Set the output of the comparator (RB0) low by turning preset VR2 fully in one direction. Point the transducers at an object at about 1 metre away and turn the preset until a signal appears (at about 6ms after RB3).

PIC Ultrasonic Distance Meter Manual setup

Set the output of the comparator (RB0) low by turning preset VR2 fully in one direction. Point the transducers at an object at about 1 metre away and turn the preset until a the display generates '100' (approx).

Move the board back and forwards to check that it displays a larger and then smaller number. Check the longer distance e.g. point at the ceiling and then a closer object e.g. a wall 20-50cm away. Adjust the preset as necessary.

Improvements to the PIC Ultrasonic distance meter

You could remove the comparator and use the internal analogue comparator but this would require more software to set the comparator level. It would require 'Up' and 'Down' buttons to control the level settings.

With a temperature sensor you could change the value used for the speed of sound (currently fixed at 340m/s for 20ºC operation i.e. indoors!). This would make the PIC Ultrasonic distance meter more accurate in different environments.

PIC Ultrasonic distance meter Software

Project files for the PIC Ultrasonic distance meter

Compiler project files
16F88_Ultrasonic_ranger.mcppi

C Source files.
16F88_Ultrasonic_ranger.c

Header files.
bit.h

Output files
16F88_Ultrasonic_ranger.hex

For a tutorial on compiling these project files click here.

PIC Ultrasonic Distance Meter Description

16F88_Ultrasonic_ranger.c

This contains all the code except the bit manipulation routines found in bit.h.

It enters a continuous a continuous loop calling ulta_gen - the routine that generates the ultrasound at 40kHz.

The ultra_gen routine is set up using the simulator to set the timing of the output signal for a period of 25us (40kHz). This is then repeated every 40ms. The required refresh rate of the seven segment display is 20ms so the display update routine (seg_display_int) is called twice over the 40ms period. (I should really say that the display update routine takes 20ms and calling this twice creates the total 40ms delay).

The display relies on persistence of vision to make it appear that the display is not flickering - a refresh rate of 50Hz or more does the job ( 1/50Hz = 20ms).

In theory the maximum distance that you could measure is 40ms*340m = (13.6) 6.8m (half the round trip time delay ) but in practice this is limited by the signal conditioning circuits. If they were changed you could get more range.

If a capture occurs indicated by gCapInt then the DST calculation is performed and the value of variable val is updated. val is the value displayed by the seven segment display routine 'seg_display_int' so val is continuously refreshed to the seven segment display.

PIC Ultrasonic Distance Meter Interrupts

The interrupt routine is only enabled when required and when the capture occurs (if it does) only the first capture is stored - so that later reflections are ignored (by resetting gCapOn).

The first reflection should be the strongest and therefore the closest object. When captured the variables t_capL,t_capH and t_capO are set to the value of the capture register which will be the value of timer 1 when the capture module triggered.

At the moment I have not used t_capO (and should do so) as it accounts for the roll over when timer 1 overflows. All that happens is that occasionally (when an overflow occurs) the wrong value will be generated - for hand held use it is not noticeable at all.

A few more notes on the code operation

1. generate ultrasound at 40kHz (a few pulses of a square wave) to the TX

2. Turn on receiver.

3. Count time from end of 40kHz pulses to start of reception of reflected ultrasound

4. Ultrasound takes a set time to travel through air (varies mainly with temperature)

5. Apply D=SxT (Distance, Speed, Time)

You know the time taken for the round trip – the capture module is started at the end of the TX pulse – this just counts pulses of timer1 until it receives an input – when it does -the capture interrupt makes the program jump the interrupt routine where the current captured time is stored in:

t_capL = CCPR1L;

t_capH = CCPR1H;
t_capO = T1_O;

variable gCapInt = 1; // signal that a capture occurred.

indicates to the main program that an echo was captured

This is where the distance is calculated

calc = ((s1)<<8)+s2;

change to 16 bit number

Multiply by 340 m/s

to get cm divide by 100.
divide by 2 to get half the complete round trip delay

so calc * (340/100)/2

i.e. calc * 340/200


But I have 4 digits and only want to display on the right 3
so use another divide by 10 to shift the digits along 1 to the
right.

Final calculation is

calc * (((340/100)/2)/10) the same as 340/2000

But you don't want to do this calculation all at once if using only

integers as it will overflow so its split into 2 pieces

calc = calc * 34;

calc = calc / 2000;

i.e. its the same as calc * 340/2000 but does not
overflow the calc integer store.

The variable val is assigned the calculated value
and then automatically displayed on the 7segments.








Learn to program in C

in easy steps.

Essential & EASY:

PIC C Programming Course:

CLICK HERE.


Jump from ultrasonic distance meter to Home page.



Privacy Policy | Contact | About Me

Site Map | Terms of Use | Links




Google

Recent Articles

  1. An Ultrasonic Distance meter project.

    Nov 25, 14 12:00 PM

    An PIC Ultrasonic Distance meter project using a PIC microcontroller which is ideal since it has a capture timer that can accurately measure the ultrasonic echo time, so calculating the distance is ea…

    Read more

  2. A dot matrix LED display project for an 8x8 or 5x7 led matrix.

    Nov 20, 14 04:58 AM

    How to drive a dot matrix LED display. This project shows you how to drive one with 64 LEDs (8 rows by 8 columns) or less e.g. 35 LEDs (7 rows by 5 columns).

    Read more

  3. USB Serial Port: How to setup an RS232 serial link through a USB port.

    Nov 20, 14 04:55 AM

    USB serial port: How to setup an RS232 serial link when you only have a USB port. There are two types of digital interfaces to consider...

    Read more

Custom Search

Sign up for MicroZine:
''The'' Microcontroller Newsletter


Enter your first Name and primary email address in the form below:

And receive absolutely FREE a full project for:


"Measuring Analogue Voltages
Without An ADC"

(Using only one pin).

Instant Download:
You Can
Get It Right Now

Warning: This project could be Removed
at any time.  

It will NOT be
available indefinitely SO

To avoid
disappointment get it:

Now



:
:
Don't worry -- your e-mail address is totally secure. I promise to use it only to send you MicroZine
Remember this is a project with full description and fully debugged C Source code - and it's not available from the main website.

You can only get it through this newsletter.


To get exclusive access Enter your first name Name and primary email address Now in the form above.:

But wait !

There's more...

You'll receive more
free and exclusive reports as well as site information and site product updates.

Scroll up to the form above and sign up NOW.  Don't forget it's FREE and if you don't like it you can unsubscribe at any time.

Click Here Now to use the form above to get your Valuable information absolutely free.



Social Bookmarking
Click & Add:
add to BlinkBlink
add to Del.icio.usDel.icio.us
add to DiggDigg
add to FurlFurl
add to GoogleGoogle
add to SimpySimpy
add to SpurlSpurl
Bookmark at TechnoratiTechnorati
add to YahooY! MyWeb
Readers comments

"I wanted to thank
you so so so much
for all the information
you have provided in
your site it's

SUPERB and FANTASTIC."


- Ranish Pottath


"This site really is
the best and my favorite.
I find here many useful
projects and tips."

- Milan

bursach<at>gmail.com

Learn PIC C Now
Wondering how to program your next project using C and need a great start?


"Awesome site,
very, very easy and nice
to navigate!"


- Matt
matt_tr<at>
wolf359.cjb.net


"I am a newbie to PIC
and I wanted to say
 how great your
site has been for me."


- Dave

de_scott<at>bellsouth.net

Learn Microcontrollers
"Interested in
Microcontrollers?"


Sign up for The
Free 7 day guide:

FREE GUIDE : CLICK HERE

"Your site is a great
and perfect work.
congratulations."


- Suresh

integratredinfosys<at>
yahoo.com

"I couldn't find the correct
words to define
yourweb site.

Very useful, uncovered,
honest and clear.

Thanks so much for
your time and works.
Regards."


- Anon