Handheld Ultrasonic Rangefinder Using Atmel Mega32


Our ultrasonic rangefinder is capable of allowing the user to determine his or her distance from an object or wall.
Handheld Ultrasonic Rangefinder Using Atmel Mega32
When deciding on what type of project to design and construct, we decided that we wanted to create something that would have some practical use in life. Many groups in the past created video games, but we wanted to be different. We considered issues such as safety, user interface, and ease of use, and came up with the idea of making an ultrasonic rangefinder. A rangefinder can be used in various applications such as a measuring device or an obstacle detection device.

High level design

Rational of the project

As stated earlier, we wanted to create something that would be of practical use to people of various walks of life. For instance, our rangefinder could be used in the case of a blackout where a person needs to find his way through a dark building and cannot see where the walls are. Alternatively, it could be used by surveyors that are preparing a site for construction.
One group from a previous year had done a project using an ultrasonic rangefinder, but their project involved a pre-manufactured system. The bulk of their project was using AM transmission to communicate with the rangefinder module.
Our project is different in the fact that we built the rangefinder from the ground up.

Logical structure

The basic principal of the rangefinder is based on the simple concepts of SONAR (Sound Navigation and Ranging). First, an ultrasonic pulse is transmitted by a transducer (a device that converts a voltage signal into a sound wave and vice versa). This pulse then reflects off an object and is received by another transducer. Using the known speed of sound (340.29 m/s) and the time between the transmitted pulse (the ping) and the received pulse (the pong), one can simply calculate the distance traveled by the pulse.
In addition to determining the distance between the device and an object using the known speed of sound, our initial design included two additional modes of operation. One mode was a calibration mode while the other was a speed detection mode.
Since the speed of sound varies with altitude and atmospheric conditions, a calibration mode is quite useful. Our program is designed such that if in calibrate mode, the user can place the device a known distance 5 centimeters and send a pulse. The device then uses the time necessary for the pulse to reflect off the object and calculates a new value for the speed of sound. This new value is then used for all future distance calculations until the device is powered off.
The original speed detection mode was used to indicate to the user how quickly he or she is moving towards or away from an object. Since speed is determined by the change in distance divided by the change in time (dx/dt), speed can be determined quite simply using two pulse transmissions. When initiated, a first pulse is sent and received by the device. The distance is calculated and stored by the device. A second pulse is then sent and received by the device 0.25 seconds later and the results stored by the device. The MCU can now take the difference in distance, divide that by 0.25 seconds, and display the speed to the user on the LCD. We had initially considered using Doppler shifts in frequency to calculate speed, but we decided against it since measuring frequency is a completely new task we would have to program (compared to just detecting a pulse) and would have required much more complicated and CPU intensive math. We also felt that the velocity of a handheld device would not be fast enough to actually incur significant Doppler shifts that would make calculations doable.
Due to noise issues while testing our original program, the method of calculating distance was changed. We are now taking multiple distance samples and calculating the average. This enables more accurate readings. Obviously, the larger the number of samples, the higher the accuracy. Since we are now taking multiple samples, it is possible to measure the speed of the device in the same operating mode.
Replacing the original speed detection mode is a mode in which the user can change the number of samples to use for the distance calculation. The user can increase or decrease the number of samples by multiples of 50, with 50 being the minimum. Our calibration mode was still implemented.

Background math

The math required for our project is very simple. The speed of sound is 340.29 m/s at sea level. This equates to 340,290 millimeters per second. Taking the inverse of this, the time necessary for a sound wave to travel one millimeter is 2.9387 microseconds. By counting the time between the ping and pong, the distance traveled by the pulse can be determined. One has to keep in mind however, that the distance traveled is actually twice the distance between the device and the object (since the pulse travels in one direction, is reflected, and travels back in the other direction).
The speed calculation is simply the first derivative with respect to time of the position (dx/dt). Two pulses are sent and received at a known time interval and the difference in distances is used to determine the speed of the device relative to the object. More specifically, (x2  x1)/(t2  t1) = speed.

Hardware/software tradeoffs

Since the basic principle of a rangefinder is rather straight forward (send pulse, receive pulse, calculate distance based on time difference) we decided to stick with the Atmel Mega32 MCU that we have been using the entire semester. This MCU can easily handle the software needed for the rangefinder and there was no reason not to use it. Using a different MCU would require learning all the intricacies associated with it and was not practical.
Initially, we wanted to try an infrared or laser rangefinder. However, since we were going to use a Mega32 with a 16 MHz crystal, this wouldn’t be possible. The speed of light is 3e8 m/s, meaning the time to travel one meter is 3.33 nanoseconds. With a 16 MHz crystal, the time resolution of the Mega32 is 62.5 nanoseconds. This means that a rangefinder based on a light wave would be accurate to only 18.75 meters. Definitely not practical!
The alternative we chose was to use a 40 kHz ultrasound transducer pair. Ultrasonic transducers are relatively cheap (the ones we bought cost less than $7 for the pair) and easy to acquire. At 40 kHz, the human user would not be able to hear the pulse (human hearing is limited to approximately 20 Hz to 20 kHz) so irritancy is not an issue.
As stated earlier, the time resolution of sound is only about 3 microseconds, so speed and fast execution time of code was not of great importance (compared with some other application like NTSC video signals). This made ultrasound an easy decision.
Another hardware tradeoff that was taken into account when designing and construction the rangefinder was a matter of gain. When testing the transducers with a signal generator, we noticed that the effective range was proportional to the input voltage of the transmitting transducer. Simply put, the higher the input voltage, the farther its signal could travel. Since the transmitter was being fed a signal from an MCU port pin, it would only receive 5 volts. This resulted in a poor range using the signal generator while testing (a range of only a few centimeters). By increasing the voltage to around 20 volts using the signal generator, we were able to get a range in excess of 1.5 meters. The tradeoff here comes down to the power supply used when making the device completely portable. We could have used a single 9 volt battery, but the gain on the transducer would be less than 2 to 1. Using two 9 volt batteries in series (giving a total of 18 volts) would give us a gain of slightly more than 3 to 1 (18 to 5, more specifically). Unfortunately, this makes the device heavier and cost more to operate. Initially, we decided that increased range was more of a pro than the con of one more battery. Unfortunately, using 18 volts for the gain ended up not working as desired. More on this later.
The main software tradeoff was using dx/dt to calculate distance rather than using Doppler shifts. Doppler shifts would have required measuring the frequencies of the square waves as well as determining frequency shifts. This would have required code almost as difficult to write as our whole project so we just decided to measure speed using dx/dt from elementary physics.
Another tradeoff was the decision to use CodeVision C instead of assembly to program the MCU. Assembly most likely would have resulted in more accurate timing and thus distance measurements, however using C had the benefit of being more user friendly in regards to programming. Using C enabled us to save time while programming and allowed us to find bugs in the code more easily.

Design standards

Since our project is a ground-up portable device that does not interact with any other devices, there are no such design standards (IEEE, ISO, ANSI, etc.) that were considered when designing our rangefinder. Since the program for the MCU was written in the CodeVision C programming language, that could be considered the only standard used in the development of the rangefinder.

Intellectual property

Rangefinders are nothing new and can be purchased off the shelf for various applications. However, since we designed our rangefinder using only the basic principles of SONAR without using any existing product as a basis, we do not believe we are in violation of any existing patents, copyrights, or trademarks. We did, however, receive assistance from Prof. Land and the TAs in regards to circuit design and software structure, and for that we are appreciative.

Hardware/software design

Hardware design

The hardware for the rangefinder can be broken down into three functional units, the receiving circuit, the transmitting circuit, and the MCU circuit. The receiver and transmitter circuits can work independently of the MCU, which made testing with a signal generator quite useful. This allowed one of us to work on the hardware while the other worked on the software independently and not require one to be dependent on the other for testing.
At the heart of the receiver circuit is one of the ultrasonic transducers. The transducer converts an incoming sound wave and converts it into a voltage signal. This signal needs to be cleaned of noise, amplified, and turned into a TTL-type signal for the MCU. The signal from the transducer is fed through a capacitor to filter out noise and then through a voltage divider to center the signal at 2.5 volts. From here, the signal needs to be amplified to guarantee true TTL levels. Initially, this was attempted using an LM358 op-amp. However, the LM358 could not switch fast enough and was unable to create a clean square wave. At the suggestion of Prof. Land, we tried using a 74HC04 high speed CMOS inverter as a high gain linear amplifier. Initially, we used resistor values of 1 MΩ and 100 kΩ to achieve a gain of 10. This created voltage levels well beyond +5 volts and resulted in a clipped signal at the output. This, however, is actually desired because the output now represented a more of a square wave than a sine wave. The output of the inverter was then fed into a SN74HC14N Schmitt trigger to convert it into a true TTL square wave. The input of the Schmitt trigger was connected to ground using a 22 pF capacitor to clean the signal from noise. The output of the Schmitt trigger can now be fed into the MCU as the received pulse.
During testing, however, we noticed that this did not quite create a nice clean square wave and was influenced greatly by noise. To combat this, we changed the gain of the inverter amplifier by replacing the 100 kΩ resistor with a 10 kΩ resistor for a gain of 100. We then fed the signal through three cascaded Schmitt triggers to clean up the signal much more than previously. There is a single 22 pF capacitor on the input of the last Schmitt trigger to ground.
Unlike the receiver circuit which tries to generate a TTL square wave, the transmitter circuit starts with a TTL square wave. This square wave is generated by the MCU as a series of pulses. The goal of the transmitting circuit is to amplify the pulse train enough so that it can travel a significant distance and reflect back towards the receiver. Again, we had initially tried using a LM358 op-amp running into the same switching problems. We then tried using a 2N3904 BJT sourced by 9 volts at the collector as a simple switch. This ended up not working because the transducer did not create a DC path for current to flow through the BJT. In the end, a LM311 high speed comparator was used as the amplifier. In the spec sheet, an example of a zero-crossing detector was given. Changing that to a 2.5 volt-crossing detector was just a matter of changing the negative input terminal to 2.5 volts instead of GND and the VCC- pin to GND instead of -5 volts. By supplying the LM311s VCC+ pin with +18 volts, we were able to get high gain for the square wave generated by the MCU to transmit through the transducer.
Unfortunately, the high gain caused by the +18 volt supply also amplified noise in the circuit. The source of this noise is still unknown, but is likely due to the physical locations of the various circuits on the solder board. Many wires were crossing each other and are the likely culprit. As such, the amplified noise gave rise to incorrect readings by the receiver circuit. When we dropped the supply voltage back down to +9 volts, the range and accuracy of the device improved.
Handheld Ultrasonic Rangefinder Using Atmel Mega32
The Mega32 MCU is used as the brain of the rangefinder. Pins 4, 5, and 6 of PortB were used as the programming port. This allowed us to program the MCU using the STK500 development board without removing the MCU from the solder board. Pins 1, 2, and 3 of PortD were connected to SPST pushbuttons that are used to interface with the rangefinder. Depending on which mode the device is in, each button performs different functions. PortD.5 was used to supply the transmitter circuit with the TTL pulse train (ping), while PortD.7 was used as the input from the receiver circuit (pong). PortC was used for the LCD display. The LCD displays the calculated distance and speed to the user. PortA of the MCU was not used.
Power to the device was supplied by one 9 volt battery hooked up in series with a SPST pushbutton as the on/off switch. The +9 volts was fed into a LM340 voltage regulator to generate 5 volts for the MCU, ICs, and LCD. A 9 volt line was used to power the LM311 comparator to generate gain.
Acknowledgement must be paid towards Prof. Land and the TAs. Without their help, the hardware for the receiver and transmitter would have never been successful. Thanks.

Software design

The program for the rangefinder essentially does two things: 1) transmit a 40 kHz pulse, and 2) detect when the pulse is received. All that was needed to be done was to count the time that passed between the time of transmission of the ping and the reception of the pong. There were also 3 modes of operation: normal mode, change sample number mode, and calibration mode.
In order to generate the ping and count the time between ping and pong, we used two of the MCUs timers. Timer1 was running at 40 kHz in PWM mode to generate a square wave for transmission using PortD.5. Timer0 was running at 250 kHz. Timer0s purpose is to calculate time between the send pulse and the receive pulse.
In normal operation, the user pushes a button to send out the ping. The MCU then counts the number of ticks it takes before the receiver detects the pong. The number of ticks is then divided by a factor of two to represent the number of millimeters between the device and the object. As stated earlier, multiple distance samples are taken and then averaged to create more accurate readings. We noticed during testing that using one sample (or only a few) gave erroneous measurements due to picking up random noise spikes. By increasing the number of samples to a minimum of 50, we obtained pretty accurate measurements. The average of all the measurements is then displayed on the LCD. In addition, normal mode also displays the speed of the device relative to a stationary object. The speed is determined by using the distance values of the middle sample and the last sample using the dx/dt formula mentioned earlier. The LCD diplays the measured distance in millimeters and the speed in millimeters/second.
In the sample number changing mode you can change how many samples you want to take with a minimum number of samples being 50. This is to allow you to get a more precise measurement taking more measurements and eliminating randomness.
Calibration mode is used in cases when the speed of sound may differ from that at sea level. Factors such as altitude and humidity can affect the speed of sound. To maintain correct measurements, the user places the device exactly 5 centimeters from a flat wall or object. By pressing the pulse button, a pulse is sent out and received by the device. The MCU then uses the time between ping and pong to calculate the new number of ticks per meter. The MCU uses this value for all future measurements until the device is powered off.
The code was very straight forward in theory. The transducers that we used operate at 40 kHz. We first attempted to use a clock running at 80 kHz to toggle a port pin to generate a 40 kHz square wave. This did not work as well as expected. When we hooked up the port pin to the oscilloscope for testing, we noticed that the output was not an ideal 40 kHz square wave. To get around this we decided to use the PWM mode of Timer1. We configured the timer to toggle OC1A on compare match so we could pull a 40 kHz square wave off PortD.5. This seemed to solve the problem of producing a 40 kHz square wave from a port pin. To change the number of pulses in each pulse sequence for transmission we just turned on and off the toggle at certain times.
Another tricky part of the program was the timing and accuracy. As mentioned earlier, we programmed a timer tick to be 250 kHz. This translates roughly to 1.36 millimeters per second. To get the right distances required some floating point arithmetic. Finally knowing where to start and stop the counter clock was a bit tricky. We did not want to count any useless ticks that did not represent when the pulse was actually sent. These useless ticks are a result of the MCU performing other operations such as floating point calculation and conditionals. It was tricky to figure out where in the code to actually start the counter.

Parts List:


Supplier/Part #


Atmel Mega32 MCU supplied by lab $8.00
Solder board supplied by lab $2.50
LCD supplied by lab $5.00
40 kHz transducer pair Jameco #139491 $6.95
LM340 voltage regulator supplied by lab free
74HC04N inverter supplied by lab free
74HC14N Schmitt trigger supplied by lab free
LM311 comparator Digikey # 296-1389-5-ND $0.40
Pushbuttons supplied by lab free
SPST on/off button All Electronics CAT #PB-123 $0.75
9 volt battery clip (x2) supplied by lab $1.00
9 volt battery (x2) supplied by lab $2.00
Various resistors and capacitors supplied by lab free
Wire supplied by lab free
16 MHz crystal supplied by lab free
Total $26.60

For more detail: Handheld Ultrasonic Rangefinder

About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:

Leave a Comment

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

Scroll to Top