Tags: , , ,

The HC-SR04 is an ultrasonic sensor that measures distance with ultrasound waves. It uses the same principle as a sonar which is sending a sound wave and measuring the time between the transmission and reception of its echo.

Material

  • Computer
  • Arduino UNO
  • USB cable to connect Arduino to the computer
  • Ultrasonic distance sensor HC-SR04

Wiring

HC-SR04 arduino schematics

 

Code

According to the sensor specifications, HC-SR04 has a range of 2 to 400 cm. To measure a distance, a pulse of 10µs has to be sent to the trigger pin (at least every 60ms) and the output pulse duration need to be measured from the echo pin. This duration divided by 58 should give the value in centimetres. A useful function to measure a pulse duration is the function pulseIn().

#define trigPin 3 
#define echoPin 2

long distance;

void setup() { 
  
#define trigPin 3 
#define echoPin 2
long distance;
long duration; 
void setup() { 
 Serial.begin(9600); 
 pinMode(trigPin, OUTPUT); 
 pinMode(echoPin, INPUT); 
 } 
 
 void loop() { 
   distance=readUltrasonicSensor();
   if (distance >= 400 || distance <= 0){ 
     Serial.println("Unknown value"); } 
   else { 
     Serial.print(distance); 
     Serial.println(" cm"); 
     } 
     delay(500);// delay in milliseconds 
} 
long readUltrasonicSensor(){ 
 // Send 10µs pulse 
 digitalWrite(trigPin, HIGH); 
 delayMicroseconds(10); 
 digitalWrite(trigPin, LOW); 
 // Read pulse duration 
 duration = pulseIn(echoPin, HIGH); 
 Serial.println(duration); //Convert and return value 
 return duration/ 58; 
}

N.B. Depending on where you purchased your sensor and its version, the range and conversion value may differ a bit. Check your sensor specifications.

 

Library

To simplify the code, you can create or download the library SR04.h (by mrRobot62). The code can then be rewritten as follow:

#include "SR04.h"
#define TRIG_PIN 3
#define ECHO_PIN 2
#define LOOPDELAY 1000
SR04 hcsr04 = SR04(ECHO_PIN,TRIG_PIN);
long distance;
void setup() {
Serial.begin(9600);
delay(LOOPDELAY);
}
void loop() {
distance=hcsr04.Distance();
Serial.print(distance);
Serial.println("cm");
delay(LOOPDELAY);
}

 

Application

Obstacle detection and avoidance for mobile robot

 

Source

datasheet HC-SR04