HC-SR04 Ultrasonic Module Testing Part 1

07.11.17

I received the HC-SR04 Module as part of an Arduino Starter Kit I ordered some time ago and thought I would run a few tests over it to see what it could potentially be used for in the future. I was thinking it would make a good addition to the self balancing robot to stop it bumping into things.

The link for the YouTube video is below, take a look at it as it covers off on the circuit, the code and the actual testing.

https://youtu.be/3mNtxuOFtUg

I have created a quick and dirty datasheet for the device based on information I dug up from the internet and have included it in the link below.

http://www.grumpyoldtech.technology/attachment/HC-SR04 Ultrasonic Module.pdf

 

The schematic is pretty straight forward as there are only 4 connections to the device. Just connect up the 5V and Ground connections and link the Trigger input to pin 12 on the Arduino and Echo pin to pin 2 on the Arduino. Its all labeled really well on the module.

Schematic

The Arduino code i used for this test is below, just copy and paste it into a blank Arduino project.

A full description of the code is in the YouTube video (link above):


//
//
// HC_SR04 Ultrasonic Sensor test
//
// Code by: Grumpy Old Tech
//


// Pins

#define trigPin     12
#define echoPin     2

// Variables

long echoDuration;
float distance;

// Setup

void setup() {
  
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.begin(9600);
  
}

// Loop

void loop() {
  
  // Create a trigger pulse, ___|_10µS_|˜˜˜˜50µS˜˜˜˜|_____
  digitalWrite(trigPin, LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(50);
  digitalWrite(trigPin, LOW);

  // Read the time the pulse is high, this equates the sound wave travel time in microseconds
  echoDuration = pulseIn(echoPin,HIGH);

  // Calculate the actual distance
  // Speed of sound = 340 m/s = 34000 cm/s = 34 cm/ms = 0.034 cm/µs
  // time = distance / speed
  // distance = time x speed
  // distance apart (cm) = time x speed / 2 = time x 0.034 / 2   *** distance is halved as signal goes to the object and back
  distance = echoDuration * 0.034 / 2.0;
  
  // send the value to the serial port
  Serial.print("Distance (cm): ");
  Serial.println(distance);

  delay(100);
}

 

 

 

 

Comments (0)


Leave a Comment