Introduction: Use of Ultrasonic Sensor to Measure Distances

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.

Step 1: Tools and Materials

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

Step 2: Circuitry

  • 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.

Step 3: Code

// 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); }

Step 4: 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.

Makerspace Contest 2017

Participated in the
Makerspace Contest 2017