HC-SR04 Ultrasonic sensor (How-to & Review)

Today’s subject is a very popular sensor module for small autonomous robots. Why is it so popular? Because it is extremely cheap, easy to use and quite reliable. Let’s see how to hook up the module with an Arduino.

The connection is really straightforward:

  • GND to GND
  • VCC of sensor with 5V of Arduino
  • TRIG of sensor with any digital i/o of Arduino (I used D10)
  • ECHO of sensor with any other digital i/o of Arduino (I used D11)

I also attached two probes of my oscilloscope to the TRIG and ECHO signals to see what is actually happening.

IMG_20150920_112856

Now let’s load up the Arduino software and copy the following into a new sketch:

int outPin = 10;
int inPin = 11;

void setup()
{
  Serial.begin(9600);
  pinMode(outPin, OUTPUT);
  pinMode(inPin, INPUT);
}

void loop()
{
  digitalWrite(outPin, HIGH);
  delayMicroseconds(15);     
  digitalWrite(outPin, LOW);
  int distance = pulseIn(inPin, HIGH);
  distance  = distance/58;
  Serial.println(distance);
  delay(50);     
}

What this sketch does is first it sets up the input and output pins and the serial communication in the setup loop. Then in the main loop it makes a 15 microseconds long positive signal on the TRIGGER line (the manual of the module recommends a minimum of 10 microseconds so we used 15 microseconds to be on the safe side). Then it waits for a response pulse on the ECHO line, measures its length, transmits the measured distance on UART and finally waits for 50 milliseconds before repeating the whole procedure.

If we compile and upload the sketch and run the built-in serial monitor we should see the distance values with a high (~20 Hz) refresh rate:

serial_monitor

If you only see zeroes and the refresh rate is low (around one second per minute) it means that the ‘pulseIn’ function times out and returns with a default value of ‘0’. Check if everything is connected correctly.

The image on the oscilloscope shows the two signals nicely. Channel 1 (yellow) is the 15 us trigger, channel 2 (blue) is the response. The length of the response is 11 milliseconds (11000 microseconds) so the measured distance is 11000/58=189.66 in centimeters. This seems to be correct because I was pointing the sensor upwards and distance between my desktop and the ceiling is around that value.

DS1Z_QuickPrint1

The sensor works quite reliably under normal circumstances. The measurements can only be false when the measured surface is in a weird angle or a small object is in the way. I was able to measure up to about 5 meters, after that I got this:

serial_monitor_2

Summary

Pros
  • Extremely cheap
  • Reliable measurements up to almost 5 meters
  • Needs only 2 pins
Cons
  • Very small holes for fixation.

3 CommentsLeave a comment

Leave a Reply

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