Use of Ultrasonic Sensor to Measure Distances

by TechMartian in Circuits > Arduino

21383 Views, 21 Favorites, 0 Comments

Use of Ultrasonic Sensor to Measure Distances

IMG_0943.jpg

The ultrasonic sensor is a cheap sensor that can measure 2cm to 400cm of non-contact measurement functionality with a ranging accuracy that can reach up to 3mm. It uses sonar waves for echolocation, like bats, to be able to measure distances. This project is an introduction to the use of an ultrasonic sensor, since it is often not straightforward nor intuitive to wire and code.

Tools and Materials

IMG_0939.jpg
  • Arduino 101 or Arduino Uno
  • HC-SR04 Ultrasonic Sensor
  • Breadboard
  • Jumper Wires

Circuitry

IMG_0944.jpg
IMG_0945.JPG

  • Connect the pin labeled "trigger" to pin 10 on the Arduino
  • Connect the pin labeled "echo" to pin 9 on the Arduino
  • Connect the Ultrasonic Sensor's 5V pin to the 5V pin on the Arduino
  • Lastly, complete the circuit by connecting the Ultrasonic Sensor's ground pin to the Arduino's ground pin.

Code

Screen Shot 2017-07-20 at 8.57.40 PM.png

// defining the trigger and echo pins of the ultrasonic sensor

const int trigger = 9; const int echo = 10;

// defining variables long duration; int distance;

void setup() { // Sets the trigger pin as an OUTPUT pinMode(trigger, OUTPUT);

// Sets the echo pin as an INPUT pinMode(echo, INPUT); // Begins the serial communication Serial.begin(9600); }

void loop() { // Clears the trigger pin digitalWrite(trigger, LOW);

delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigger, HIGH); delayMicroseconds(10); digitalWrite(trigger, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echo, HIGH); // Calculating the distance distance= duration*0.034/2; // Prints the distance on the Serial Monitor Serial.print("Distance: "); Serial.println(distance); }

Demo

Ultrasonic Sensor demo

The serial monitor will output the distance measured by the Ultrasonic sensor. As I move my hand, the serial monitor updates the new distance that the Ultrasonic sensor is reading.