Ultrasonic sensor HC-SR04

Arduino IDE used: 1.6.6, Arduino used: Mega

Function


This sketch uses the HC-SR04 ultrasonic sensor to measure distances and display them in the Serial Monitor.

Hardware


Sensor specs

Connections

Connect Gnd to a GND pin of the arduino, Echo to pin 2, Trig to pin 3 and Vcc to 5V.

connections connections

A connector I made from a serial port cable

connections

You could also solder wires to the pins

Theory

A measurement is started by setting the trigger-pin HIGH for at least 10 microseconds. Then the device sends out 8 pulses at 40 kHz and starts to listen for their returns. When this is completed it sets the echo-pin HIGH for as long as it took the signal to return. Knowing the speed of sound the distance is calculated.

theory

Code

Basic version

Improved version

In this version the temperature dependence of the speed of sound is accounted for by setting the temperature in the code (measuring it with the arduino would be a great add-on). The accuracy is further improved by taking the last 5 measurements, removing the highest and lowest one and calculating the average of the remaining 3.

  download code