Ultrasonic Sensor Distance Measurement

Ultrasonic Sensor Distance Measurement

Introduction

In this experiment, you will use an ultrasonic sensor to measure the distance to an object. Based on the measured distance, an LED will turn on when the object is closer than a specified threshold.

Arduino Minima R4 with Breadboard and LED setup

Objective

The goal of this experiment is to interface an ultrasonic sensor with a microcontroller to measure distance and perform actions based on proximity.

Components Required

Arduino Minima R4 with Breadboard and LED setup

Circuit Diagram

Connect the components as follows:

Arduino Minima R4 with Breadboard and LED setup

Code

Use the following code to measure distance and control the LED:


// Pin Definitions
const int trigPin = A1;     // Ultrasonic sensor Trig pin
const int echoPin = A0;     // Ultrasonic sensor Echo pin
const int ledPin = 9;       // LED pin
const int distanceThreshold = 10; // Distance threshold in centimeters

void setup() {
    Serial.begin(115200);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, LOW);
    Serial.println("Ultrasonic Sensor Distance Measurement Initialized");
}

void loop() {
    // Send a 10-microsecond pulse to the Trig pin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Measure the time for the Echo pin signal to return
    long duration = pulseIn(echoPin, HIGH);

    // Convert the duration to distance in centimeters
    int distance = duration * 0.034 / 2;

    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");

    // Control the LED based on distance
    if (distance > 0 && distance < distanceThreshold) {
        digitalWrite(ledPin, HIGH);
    } else {
        digitalWrite(ledPin, LOW);
    }

    delay(100);
}
            

Procedure

  1. Connect the components as per the circuit diagram.
  2. Copy the code above and paste it into your Arduino IDE.
  3. Select the correct board and port in Tools.
  4. Upload the code to your microcontroller.
  5. Open the Serial Monitor and set the baud rate to 115200.
  6. Place an object in front of the ultrasonic sensor and observe the distance readings in the Serial Monitor.
  7. When the object is closer than 10 cm (or your specified threshold), the LED will turn on.

How It Works

Arduino Minima R4 with Breadboard and LED setup

Troubleshooting