Site icon AranaCorp

Distance measurement with sensor HC-SR04

distance sensor hcsr04 arduino wiring

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

Operating principle

The HC-SR04 module consists of an ultrasonic transmitter and receiver. The transmitter sends out sound waves when it receives a signal from the trigger control. These waves are reflected when they encounter an obstacle. The transmitter detects these reflected waves and sends a signal back to the Echo pin.

N.B.: Some surfaces are better at reflecting sound waves. Choose your sensor carefully according to your application.

Wiring of sensor HC-SR04

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

Source

Find other examples and tutorials in our Automatic code generator
Code Architect

Exit mobile version