Measure Distance with HC-SR04 Ultrasonic Sensor and Arduino

Ever heard of Tesla? The autonomous cars (no drivers) produced in the US owned by Elon Musk. These are able to perform without drivers with the help of ultrasonic sensors which measures distances between it and other objects.

The HC-SR04 ultrasonic sensor uses sonar to determine distance to an object like bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package. From 2cm to 400 cm or 1” to 13 feet. It operation is not affected by sunlight or black material like Sharp rangefinders are (although acoustically soft materials like cloth can be difficult to detect). It comes complete with ultrasonic transmitter and receiver module.

HC-SR04
HC-SR04

 

What you’ll need to carry out this project.

Hardware

  • HC-SR04 ultrasonic sensor module, get it here
  • Arduino UNO, get it here
  • Jumper cables, get it here

Software

  • The latest Arduino IDE (download here)

STEP 1: CIRCUIT DESIGN

hc-sr04 arduino schematic

STEP 2: SOURCE CODE

int trigPin = 11;    //Trig - green Jumper
int echoPin = 12;    //Echo - yellow Jumper
long duration, cm, inches;
 
void setup() {
  //Serial Port begin
  Serial.begin (9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}
 
void loop()
{
  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
 
  // convert the time into a distance
  cm = (duration/2) / 29.1;
  inches = (duration/2) / 74; 
  
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  
  delay(250);
}

Wanna do more?

Build an alarm system, monitor if someone enters your office/room.

  • 1 x 5V buzzer, get it here
  • 1 x Arduino Uno, get it here

 

Leave a Reply

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