Know how far things are with Ultrasonic Sensor 📏

Updated: May 12, 2020


Know it

The ultrasonic sensor is a simple sensor that can be used to measure distance such as the sensor that is used in the back of your car.


That sensor knows the distance between your car and the wall so you will not collide. What happened was the ultrasonic sensor tells you the distance of a solid object or a barrier by transmitting soundwaves for it to bounce back from the object. It measures the distance it takes for time to bounce back to the transistor. It is simple physics!


Wire it

This is one of the simplest circuit! All you need is:

  • Breadboard and Jumper wires

  • Ultrasonic Sensor

  • Arduino board and USB cable


Connections:

  • Arduino pin GND → Ultrasonic sensor GND pin

  • Arduino pin 5V → Ultrasonic sensor VCC pin

  • Arduino pin 7 → Ultrasonic sensor Trig pin

  • Arduino pin 6 → Ultrasonic sensor Echo pin



Code it

This sketch will get the distance that is detected by the ultrasonic sensor and display it on the serial monitor.

/*      
Measuring distance using Ultrasonic sensor    

Tutorial link: https://www.learn.voltaat.com/post/ultrasonic-sensor

This is an Arduino sketch that read the measured distance using ultrasonic sensor, and displays it on the Serial Monitor.
      
Components Needed:   
1. Ultrasonic Sensor HC-SR04 .....x1     

Connections:   
- Arduino pin GND → Ultrasonic sensor GND pin
- Arduino pin 5V → Ultrasonic sensor VCC pin
- Arduino pin 7 → Ultrasonic sensor Trig pin
- Arduino pin 6 → Ultrasonic sensor Echo pin
*/

#define echoPin 6 // attach pin 6 Arduino to pin Echo of HC-SR04
#define trigPin 7 //attach pin D3 Arduino to pin Trig of HC-SR04

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

// This routine run once at the start
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  
  Serial.begin(9600); //opening the serial monitor
  
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
}

// This routine loops forever
void loop() {

  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
}