electronut Programming & Embedded Systems - by Mahesh Venkitachalam

Talking to Ultrasonic Distance Sensor HC-SR04 using an ATtiny84

The HC-SR04 works as follows:

  • Send a 10us HIGH pulse on the Trigger pin.
  • The sensor sends out a “sonic burst” of 8 cycles.
  • Listen to the Echo pin, and the duration of the next HIGH signal will give you the time taken by the sound to go back and forth from sensor to target.

Here, the PB0 pin is used to send out the 10 us pulse. To measure the width of the echo pulse, we can use a pin-change interrupt and a timer. Here is the idea:

  • Setup pin change interrupt PCINT0 so that any logical change on pin will cause an interrupt.
  • Send a 10 us pulse to the trigger pin.
  • Loop till the PCINT0 interrupt sets a flag to indicate that measurement is done.
  • In the PCINT0 interrupt, start an 8-bit timer when you see a rising edge - ie., the echo pulse has gone from low to high. The 8-bit timer is setup to use the overflow interrupt.
  • The 8-bit counter overflows every time it reaches 255, and so when that interrupt fires, we add 255 to a running 32-bit counter value.
  • In the PCINT0 interrupt, stop 8-bit timer when you see a falling edge - ie., the echo pulse has gone from high to low. Update 32 bit count, and set flag to indicate that the measurement is done.
  • The measured pulse width is in terms of a counter value, and we can convert that into seconds, since we know the clock speed. This time value is then used to calculate the distance.

The distance is then sent using serial communications on pin PB1 - I've covered this part in a previous post. This is also the reason we cannot use the 16-bit timer to measure the pulse width - it's already being used for serial communications. Plus it's fun to learn how to use the 8-bit timer to count large values, right? ;-)

Here is the schematic:

And the breadboard looks like this:


The full C code is listed below:

This is the Makefile that goes along with the above code. It is similar to the ones posted before - I've just added some extra linker flags to support full printf formatting.


And here is the Python code used to plot the data:


The Python code is a minor modification to what I posted before on the subject.

You can get the ATtiny84 at element14.

If you liked this article, please consider supporting my efforts by purchasing my book.

Python Playground, published by No Starch Press, USA, is a collection of imaginative programming projects that will inspire you to use Python to make art and music, build simulations of real-world phenomena, and interact with hardware like the Arduino and Raspberry Pi. Do check it out!