9.Distance Measurement System Using Ultrasonic Sensor and LCD Display with Arduino

 Distance Measurement System Using Ultrasonic Sensor and LCD Display with Arduino

                                                                   Circuit Diagram

Materials Needed:

  • Arduino board
  • Ultrasonic sensor (e.g., HC-SR04)
  • LCD (16x2) with I2C interface
  • Jumper wires
  • Breadboard (optional)

Connections:

  1. Ultrasonic Sensor to Arduino:

    • TRIG pin → Pin 9
    • ECHO pin → Pin 10
    • VCC pin → 5V
    • GND pin → GND
  2. LCD to Arduino:

    • RS → Pin 8
    • E → Pin 7
    • D4 → Pin 6
    • D5 → Pin 5
    • D6 → Pin 4
    • D7 → Pin 3

Procedure:

  1. Connect the Components:

    • Use jumper wires to connect the ultrasonic sensor and the LCD as described above.
  2. Write the Arduino Code:

    • Copy and paste the following code into the Arduino IDE:

C++ Code

#include <Adafruit_LiquidCrystal.h>

// Ultrasonic sensor pins
const int trigPin = 9;
const int echoPin = 10;

// Initialize the LCD with RS, E, D4, D5, D6, D7 pins
Adafruit_LiquidCrystal lcd(8, 7, 6, 5, 4, 3);

void setup() {
  Serial.begin(9600);  // Start the serial communication at 9600 baud rate
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  lcd.begin(16, 2);  // Set up the LCD's number of columns and rows
  lcd.print("Distance:");
}

void loop() {
  long duration;
  int distance;

  // Send a 10us pulse to trigger the sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the duration of the pulse on the echo pin
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance in centimeters
  distance = duration * 0.034 / 2;

  // Print the distance to the serial monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Display the distance on the LCD
  lcd.setCursor(0, 1);  // Set the cursor to the second row
  lcd.print("                "); // Clear previous value
  lcd.setCursor(0, 1);  // Set the cursor to the second row again
  lcd.print(distance);
  lcd.print(" cm");

  delay(500);  // Wait for a short while before the next measurement
}

  1. Upload the Code:

    • Connect your Arduino to the computer and upload the code using the Arduino IDE.
  2. Observe LCD Behavior:

    • The LCD will display "Distance:" on the first line and the current distance in centimeters on the second line.
    • You can also check the distance readings in the Serial Monitor if needed.

Explanation:

  • The TRIG pin sends a pulse to start measuring distance.
  • The ECHO pin receives the reflected pulse, and the time taken is used to calculate the distance in centimeters.
  • The Adafruit_LiquidCrystal library is used to control the LCD, which displays the distance value on the second line.

Comments

Popular posts from this blog

esp8266