HC-SR04 ultra sonic sensor

Overview

The HC-SR04 is a low-cost ultrasonic ranging sensor for measuring distance. The principle of ultrasonic sensor is similar to sonar or radar in which interpretation of echoes from radio or sound waves to evaluate the attributes of a target by generating the high-frequency-sound waves (around 40kHz). The transducer used for converting energy into ultrasound or sound waves with ranges above human hearing range is called an ultrasonic transducer. Each HC-SR04 module includes an ultrasonic transmitter, a receiver and a control circuit.

Documentation for this sensor is available here. If you want to understand the details of how an ultra-sonic sensor for measuring distance works, you can have a look at this page from https://howtomechatronics.com.

There are only four pins that you need to worry about on the HC-SR04:

HC-SR04 Sensor Pins Description
VCC Power Supply: 5V
Trig Trigger input of sensor: the Trig pin triggers sound
Echo Echo output of sensor: the echo pin returns the elapsed time during the reading of the reflected echo
GND Ground: 0V

Connecting to Arduino

Code example

/********************
 *  Program:  HC-SR04 sensor tester
 *  Description: print distance to serial
 ********************/

#define ECHO_PIN 6	
#define TRIG_PIN 7  

void setup(){
  Serial.begin(38400); // initialize the serial port
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);
  pinMode(ECHO_PIN, INTPUT);
}

// Define a new function that reads and converts the raw reading to distance (cm)
float distance_centimetre() {
  // Send sound pulse
  digitalWrite(TRIG_PIN, HIGH); // pulse started
  delayMicroseconds(12);
  digitalWrite(TRIG_PIN, LOW); // pulse stopped

  // listen for echo 
  float tUs = pulseIn(ECHO_PIN, HIGH); // microseconds
  float distance = tUs / 58; // cm 
  return distance;
}

void loop(){
  Serial.print(distance_centimetre(), DEC);
  Serial.println("cm");
  delay(1000); // ms 
}

The raw source of the sketch example is visible here.

Enjoy!