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

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

You need to divide by 2 as the distance is the round tripdistance 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 timeDistance
t = 588us 10cm
t = 5.8ms 1m

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

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

Cs condition zero mission pack download. Note: If you use a different transducer you must change thesoftware to generate the correct frequency for the transducer as they only workat their specific operating frequency.

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

This is followed by a peak detector and comparator which setsthe sensitivity threshold so that false reflections (weaker signals) areignored.

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 asignal 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 aftertransmitting an ultrasound pulse the CCP will trigger when the comparatoractivates i.e. as soon as an ultrasonic echo is received.

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

PIC Ultrasonic Distance Meter Practicallimits

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

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

For this circuit the maximum distance is about 3m.

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

Digital Energy Meter Using Microcontroller




The previous design incorrectly used RA5 as output and it is the MCLRn pin thatcan only be used as an input. So RA5 drive to the seven segment was removed andthe DP pin (Decimal Point) is left unconnected. RA6 and RA7 were moved up one 7segment drive position.
Clickto view Bill of materials (parts list).

PIC Ultrasonic distance meter Hardware

You can use any PIC microcontroller that has an internal CCPmodule and enough memory to hold the program and program the PIC in circuitthrough the ICSPconnector.

The circuit uses a three transistor amplifier and a twotransistor 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 acomparator, with suitable circuit changes, as this system is not particularlyhigh speed).

PIC Ultrasonic Distance Meter hardware block diagram

Transistor Amplifiers

First of all why use them?
I wanted to see what you could do using only transistors and it seems thatyou can do quite well i.e. the system works to the same distance as otherdesigns using op-amps.
Of course when using op-amps you can achieve lower power operation and useless components.

Transistor amplifier design

The first two transistor amplifiers use standard biasing to set the outputat the collector in the middle of the supply. If you look at the dc conditionsthe two (100k) input bias resistors across 5V to 0V set the input bias point at2.5V. When the Vbe voltage is dropped across the transistor's emitter junctionthe 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 thecapacitor has impedance of 40Ohms at 40kHz) so the effective Re is theintrinsic transistor emitter resistance (re~25ohms) plus the impedance of thecapacitor (re is temperature dependent). So the gain is 2k7/65 ~ 40. If used atdifferent 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 sameamplifier as the other two. I have just used it to see how it works as it canbe seen quite often in other circuits and it seems to work well. It willhowever be dependent on the exact transistor used (its Beta value) and it willalso be dependent on temperature - which will both affect its bias point andgain.

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

Setting up the PIC Ultrasonic distance meter.

PIC Ultrasonic Distance Meter: Oscilloscopesetup

Using an oscilloscope monitor the signals RB3 and RB0. Use RB3as 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 presetVR2 fully in one direction. Point the transducers at an object at about 1 metreaway 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 presetVR2 fully in one direction. Point the transducers at an object at about 1 metreaway and turn the preset until a the display generates '100' (approx).

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

Improvements to the PIC Ultrasonic distancemeter

You could remove the comparator and use the internal analoguecomparator but this would require more software to set the comparator level. Itwould require 'Up' and 'Down' buttons to control the level settings or analgorithm could change the levels to find the optimum threshold.

With a temperature sensor you could change the value used forthe 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 indifferent environments.

Piezo elements also generate more output when a higher voltage is applied sousing a voltage doubling circuit would increase the range of the unit. Alsousing a negative voltage generator and doubler would increase the overallvoltage across the transducer output.

PIC Ultrasonic distance meter using amicrocontroller Software

Project files for the PIC Ultrasonic distancemeter

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 projectfiles click here.

PIC Ultrasonic Distance Meter Description

16F88_Ultrasonic_ranger.c

This contains all the code except the bit manipulation routinesfound in bit.h.

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

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

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

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

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

PIC Ultrasonic Distance Meter Interrupts

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

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

Using

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

A few more notes on the code operation

1. generate ultrasound at40kHz (a few pulses of a square wave) to the TX
2. Turn on receiver.
3. Count time from end of40kHz pulses to start of reception of reflected ultrasound
4. Ultrasound takes a set timeto travel through air (varies mainly with temperature)
5. Apply D=SxT (Distance,Speed, Time)
You know the time taken forthe 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 thecurrent captured time is stored in:
t_capL = CCPR1L;
t_capH = CCPR1H;

Microcontroller 8051 Programming

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) thesame as 340/2000
But you don't want to do thiscalculation 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 assignedthe calculated value
and then automatically displayed on the 7segments.

New! Comments

Have your say about what you just read! Leave me a comment in the box below.

Jump from ultrasonic distance meter to Homepage.


Privacy Policy | Contact | About Me
Site Map | Terms of Use

Download Project Document/Synopsis


The project aims at measuring the distance of any object with the help of an ultrasonic transducer for inaccessible areas like high temperature, pressure zones where the traditional methods are inappropriate to be implemented.
A microcontroller of 8051 family is used to interface the ultrasonic module. Ultrasonic module consists of a transmitter and a receiver. The module transmits the sound waves to the object and the transducer receives the waves reflected back from it. The measurement of the distance is calculated by the total time taken from sending the waves and receiving it with respect to the velocity of sound. The calculation is done by the programmed microcontroller and displays it on LCD screen.