Original source: https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor

 

Hardware Required

1×Arduino UNO or Genuino UNO
1×USB 2.0 cable type A/B
1×Ultrasonic Sensor
1×Jumper Wires
1×Breadboard

About Ultrasonic Sensor

Ultrasonic sensor HC-SR04 is used to measure the distance to an object by using ultrasonic waves.

Pinout

The ultrasonic sensor HC-SR04 includes four pins:

How It Works

This section is the in-depth knowledge. DON'T worry if you don't understand. Ignore this section if it overloads you, and come back in another day. Keep reading the next sections.

  1. Micro-controller: generates a 10-microsecond pulse on the TRIG pin.
  2. The ultrasonic sensor automatically emits the ultrasonic waves.
  3. The ultrasonic wave is reflected after hitting an obstacle.
  4. The ultrasonic sensor:
    • Detects the reflected ultrasonic wave.
    • Measures the travel time of the ultrasonic wave.
  5. Ultrasonic sensor: generates a pulse to the ECHO pin. The duration of the pulse is equal to the travel time of the ultrasonic wave.
  6. Micro-controller measures the pulse duration in the ECHO pin, and then calculate the distance between sensor and obstacle.

See animated GIF image here (you may need to wait a moment for loading)

    How Ultrasonic Sensor Works

How to Get Distance From Ultrasonic Sensor

To get distance from the ultrasonic sensor, we only need to do two steps (1 and 6 on How It Works part)

Distance Calculation

We have:

So:

Arduino - Ultrasonic Sensor

Arduino's pins can generate a 10-microsecond pulse and measure the pulse duration. Therefore, we can get the distance from the ultrasonic sensor by using two Arduino's pins:

Wiring Diagram

Arduino Ultrasonic Sensor Wiring Diagram

Image is developed using Fritzing

How To Program

digitalWrite(9, HIGH);
delayMicroseconds(10);
digitalWrite(9, LOW);

Arduino Code

/*
 * Created by ArduinoGetStarted, https://arduinogetstarted.com
 *
 * Arduino - Ultrasonic Sensor HC-SR04
 *
 * Wiring: Ultrasonic Sensor -> Arduino:
 * - VCC  -> 5VDC
 * - TRIG -> Pin 9
 * - ECHO -> Pin 8
 * - GND  -> GND
 *
 * Tutorial is available here: https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor.php
 */

int trigPin = 9;    // TRIG pin
int echoPin = 8;    // ECHO pin

float duration_us, distance_cm;

void setup() {
  // begin serial port
  Serial.begin (9600);

  // configure the trigger pin to output mode
  pinMode(trigPin, OUTPUT);
  // configure the echo pin to input mode
  pinMode(echoPin, INPUT);
}

void loop() {
  // generate 10-microsecond pulse to TRIG pin
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // measure duration of pulse from ECHO pin
  duration_us = pulseIn(echoPin, HIGH);

  // calculate the distance
  distance_cm = 0.017 * duration_us;

  // print the value to Serial Monitor
  Serial.print("distance: ");
  Serial.print(distance_cm);
  Serial.println(" cm");

  delay(500);
}