Ultrasonic Distance Sensor

In this project, you'll learn how to control an ultrasonic distance sensor.

The ultrasonic distance sensor measures the distance to an object by bouncing off sound wave from the object and measuring the time that it takes for the sound wave to travel to the object and back.

The distance between the ultrasonic sensor and the object can be calculated based on the time that it takes for the sound wave to make the round trip between the sensor and the object.

Parts needed:
  • Arduino
  • Distance ultrasonic sensor HC-SR04
  • Wires
  • Breadboard
Ultrasonic distance sensor
1 Making the connections
  • Connect the Trig pin on the sensor to pin 7 on the Arduino.
  • Connect the Echo pin on the sensor to pin 8 on the Arduino.
  • Connect Vcc to 5V.
  • Connect GND to GND.
2 Create a new BareMinimum program and type in this program.

Defines a function called distance() for finding out the distance from the ultrasonic sensor.

Define where the Trig and Echo pins are connected.

These three digitalWrite commands to send out a sequence of LOW, HIGH and LOW signals is to initiate the trigger to send out one ultrasound pulse.

The pulseIn command with the HIGH specified, will first wait for the echoPin to go HIGH, starts timing, then waits for the echoPin to go LOW and stops timing. The command returns the length of the pulse in microseconds, and is stored in the variable duration.

This formula calculates the distance (in cm) based on the time obtained from the pulseIn command and the speed of sound. The calculated distance is then returned by the function.

Serial.print prints the distance out to the monitor.
// this function calculates and returns the distance
// as obtained from the ultrasonic sensor
long distance() {
  int trigPin = 7;
  int echoPin = 8;  
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // STEP 1
  // The next five lines will send out one ultrasound pulse
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);

  // STEP 2
  // The pulseIn command starts the timing and wait for the echo
  // when it hears the echo it will return the time in microseconds
  long duration = pulseIn(echoPin, HIGH);

  // STEP 3
  // Calculate the distance (in cm) based on the time from STEP 2 and the speed of sound
  // the calculated distance is returned by the function
  return duration/58.2;
}	// end of function

void setup() {

void loop() {
  // call the distance() function to find the distance from the ultrasonic module
  long d = distance();  
  // Now do whatever you want with the distance value stored in the variable d
  // the next line simply prints the distance value to the serial monitor
3 Open the Serial Monitor.
4 Run the program and point the sensor to objects at different distances. You should see the distance in centimeters being shown on the monitor.