Using Parallax Ping ultrasonic sensor is very easy, the main advantage of this sensor is that only one pin is needed. Communication protocol: The PING))) sensor detects objects by emitting a short ultrasonic burst and then "listening" for the echo. Under control of a host microcontroller (trigger pulse), the sensor emits a short 40 kHz (ultrasonic) burst. This burst travels through the air, hits an object and then bounces back to the sensor. The PING))) sensor provides an output pulse to the host that will terminate when the echo is detected, hence the width of this pulse corresponds to the distance to the target. As the velocity of sound waves in air is known (about 340 m/s), the width of the pulse represents the twice of the time it takes the signal to hit the nearest object that can be seen by the sensor (locates in its field of view), hence the distance equals: Distance = (Tin/2)*340 meters where Tin is the echo return time Note that the bold black pulse is sent by the microcontroller, and the gray pulse is the response of the sensor, both of them is transmitted on the same pin. Circuit: The circuit is very simple, ATmega32 microcontroller is used:
![]() Program: This is the algorithm followed: Initialization:
Loop:
The distance can be calculated as following:
Distance = TimerValue * 340 / (crystalFreqency * 2) Operation: Timer1 is used to make use of Input Capture (ICP) facility, only Timer1 is used, no external interrupts are needed, it is recommended to keep as many as resources available for future use. What can I do if Timer1 is already used for another purpose ? If Timer1 is used for another purpose, any other timer can be used along with an external interrupt, this method is illustrated in an attached fileTimer1 and INT0 are used together. ICP is not used, so Timer1 can be replaced by any other timer. Project files: Complete project with simulation All project files, created using CodeVisionAVR,and simulation files using Proteus,this is the original project, Input Capture is used here. Using an interrupt rather than ICP If you want to test this project using an interrupt with any timer rather than ICP with Timer1,replace Ultrasonic.c and Ultrasonic.DSN in the original project with those two files. Using simulation: Ping))) sensor is not modeled in Proteus, so I added another ATmega32 microcontroller to model it. Run the simulator and observe the virtual terminal window, whenever "GET" comes into screen, you can push the button connected to Ping))) microcontroller to send the echo signal. The duration of echo signal is set to simulate 2 meters distance. Note: you can change this distance by modifying line 33, in (project's directory/tester/tester.c) according to formula commented in line 32. |


