Arduino UNO – Ultrasonic Sensor HC-SR04

In this tutorial, I am going to show you how to use an Ultrasonic Sensor (HC-SR04) with Arduino UNO. You can use any Arduino board.

HC-SR04 emits an ultrasound (high frequency), which spreads through the air and if there is an obstacle on its path it will come back (reflection) to the HC-SR04. Through the travel time and the speed of the sound (340 m/s), you can compute the distance between the sensor and the obstacle.

Example of distance calculation

Speed of sound:
v = 340 m/s
Time = distance / speed
t = d / v
Distance:
d = t * 340 / 2
(divide by 2 because total time is round trip sound).

Parts Required

  • Arduino Mega 2560;
  • Breadboard (optional);
  • 1x HC-SR04;
  • Jumper wires.

Building the Circuit and Schematic

You need to connect the power to the sensor (red and black lines) and you need to connect trigPin (Output) to Arduino pin 11 and echoPin(Input) to Arduino pin 12. You can use other Arduino pins, but you should change the pins at the beginning of the code (#define pinName pinNumber).

Code

#define echoPin 12 // Echo Pin
#define trigPin 11 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  //TrigPin to LOW state, to make sure it's not high
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  //Send pulse to TrigPin
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); //pulse with 10us
  digitalWrite(trigPin, LOW);
  //measures te time to arrival of the pulse
  duration = pulseIn(echoPin, HIGH);

  //distance calculation
  distance = duration / 58.2; //simplified form

  //if distance out of range, so distance = -1
  if (distance >= maximumRange || distance <= minimumRange) {
    distance = -1;
    Serial.println("-1");
  }
  else {
    //send distance value to serial monitor
    // you can view this value in your IDE serial monitor 
    Serial.println(distance);
  }
  // wait 500 ms for next measure
  delay(500);
}

If you compile the code and send it to Arduino without errors, you will see on your monitor that the distance is measured and displayed every 500 ms. Do not forget that the obstacle cannot be too near or too far or the distance will be -1.

Any questions send us a message or leave a comment.

Leave a Reply

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