How to read a distance sensor with Arduino

Photo of author

By Jackson Taylor

When it comes to building robotics or automation projects, reading data from sensors like distance sensors is a crucial skill for any Arduino enthusiast. Distance sensors are essential for detecting obstacles, measuring the distance between objects, or even enabling precise navigation systems. In this article, we’ll walk you through the process of reading a distance sensor with Arduino, from wiring to coding, ensuring that you understand the basics clearly.

What is a Distance Sensor?

Before diving into the steps, it’s important to understand what a distance sensor is. These sensors measure the distance between the sensor and an object in its line of sight. Ultrasonic sensors are the most common type used with Arduino, such as the popular HC-SR04, which measures distance by emitting sound waves and calculating how long it takes for the waves to bounce back.

Choosing the Right Distance Sensor for Your Project

Selecting the right sensor depends on your project requirements. Here are some common types:
  • Ultrasonic Sensors (HC-SR04): Ideal for measuring distances from 2 cm to 4 meters.
  • Infrared Sensors: Suitable for shorter ranges, typically up to 80 cm.
  • Lidar Sensors: Best for longer distances with higher accuracy but also more expensive.
For this guide, we’ll focus on the HC-SR04 Ultrasonic Distance Sensor, a widely used sensor in the Arduino community due to its reliability and affordability.

Materials Needed

To get started with reading a distance sensor using Arduino, gather the following materials:
  • Arduino Board (Uno, Nano, or Mega)
  • HC-SR04 Ultrasonic Sensor
  • Jumper Wires
  • Breadboard (Optional)
  • Arduino IDE (Software)

Wiring the HC-SR04 Sensor to Arduino

The first step in reading a distance sensor with Arduino is connecting the sensor to the board. The HC-SR04 has four pins: VCC, GND, Trigger, and Echo. Here’s how to connect them:
  1. VCC Pin: Connect this to the 5V pin on the Arduino.
  2. GND Pin: Connect this to the ground (GND) pin on the Arduino.
  3. Trigger Pin: Connect this to a digital I/O pin on the Arduino (usually pin 9).
  4. Echo Pin: Connect this to another digital I/O pin (commonly pin 10).
See also
How to read a gas sensor with Arduino
The following diagram should give you a clear visual of how to make these connections:
  • VCC → 5V on Arduino
  • GND → GND on Arduino
  • Trigger → Pin 9 on Arduino
  • Echo → Pin 10 on Arduino
Once the wiring is done, we are ready to move on to the coding part.

Setting Up the Arduino IDE

Before you can start reading data from the distance sensor, you need to install the Arduino IDE if you haven’t already. The IDE is a software platform used to write and upload code to your Arduino board. Download and install the IDE from the official Arduino website: Arduino IDE. After installation, open the IDE and select your Arduino board model and the correct COM port in the “Tools” menu.

Writing the Arduino Code

Now that everything is connected, it’s time to write the code that will control the sensor and output the distance readings. Below is a simple example of Arduino code to read the distance from the HC-SR04 sensor:
cpp
// Define pins for Trigger and Echo const int trigPin = 9; const int echoPin = 10; long duration; int distance; void setup() { // Start the serial communication Serial.begin(9600); // Set the Trigger pin as OUTPUT and Echo pin as INPUT pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { // Clear the Trigger pin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Send a pulse to the Trigger pin digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Measure the duration of the pulse from Echo pin duration = pulseIn(echoPin, HIGH); // Calculate the distance distance = duration * 0.0344 / 2; // Print the distance in centimeters Serial.print(“Distance: “); Serial.print(distance); Serial.println(” cm”); delay(500); }

Code Breakdown:

  • Pin Configuration: We define the Trigger Pin (9) and Echo Pin (10) to send and receive signals.
  • Trigger Pulse: The code first sends a 10-microsecond pulse to the Trigger pin.
  • Echo Pulse: The duration of the pulse received by the Echo pin is measured, which indicates how long it took for the sound wave to travel to an object and back.
  • Distance Calculation: Using the duration, we calculate the distance in centimeters. The formula distance = duration * 0.0344 / 2 converts the time into a distance value.
See also
Arduino machine learning for object detection

Upload the Code to Arduino:

After writing the code, click the Upload button in the Arduino IDE. Once uploaded successfully, open the Serial Monitor from the IDE. You should see the distance readings in real-time.

Understanding the Output

The Serial Monitor will display distance measurements in centimeters. These readings represent the distance between the HC-SR04 sensor and the nearest object in its path. The values will update approximately every 500 milliseconds.

Example Output:

makefile
Distance: 25 cm Distance: 30 cm Distance: 45 cm

Optimizing Your Sensor for Accuracy

To ensure that your sensor readings are accurate, follow these tips:
  1. Stable Mounting: Make sure the sensor is mounted securely and facing the object you want to measure.
  2. Clear Path: Ensure there are no obstacles or noise sources near the sensor that might interfere with the ultrasonic pulses.
  3. Test Different Distances: Try measuring objects at various distances to ensure the sensor’s accuracy within its operating range.

Troubleshooting Common Issues

If your sensor isn’t working as expected, here are some common issues and fixes:
  • Incorrect Wiring: Double-check the wiring connections, especially the Trigger and Echo pins.
  • Sensor Not Responding: Make sure the sensor is powered correctly (check VCC and GND).
  • Serial Monitor Shows ‘0’: This could indicate the sensor is not receiving a return signal. Try increasing the distance or ensuring the object is within range.

Applications of Distance Sensors

Distance sensors have numerous applications in various fields. Here are some common uses:
  • Obstacle Avoidance in Robots: Sensors help robots navigate through their environment by detecting obstacles.
  • Automated Measuring Systems: Used in industrial applications to measure distances between parts or machines.
  • Autonomous Vehicles: Distance sensors are essential in self-driving cars for detecting nearby objects and enabling safe navigation.

Conclusion

Reading a distance sensor with Arduino is a simple and effective way to add measurement capabilities to your projects. Whether you’re building a robot or automating a process, understanding how to interface with distance sensors is a valuable skill. By following this guide, you now know how to wire, code, and troubleshoot distance sensors like the HC-SR04 to get accurate readings. Experimenting with these sensors will allow you to unlock new possibilities in your Arduino projects.
See also
Arduino self-driving car using GPS