Abhi 4
Abhi 4
COMPUTERSCIENCE&ENGINEERING
Experiment 4
2. Objective: The objective of this experiment is to measure the distance to an object using an ultrasonic
sensor by emitting sound waves and calculating the time taken for the echo to return.
3. Input/Equipment Used:
a. 1×ArduinoUnoR3
b. 1×Ultrasonic Sensor (HC-SR04)
c. 16×2 LCD 12C Display
d. Jumper Wires
4. Procedure:
i. Connect Sensor: Attach VCC, GND, Trig, and Echo pins of the ultrasonic sensor to the
microcontroller.
ii. Trigger Pulse: Send a 10 µs pulse to the Trig pin to emit an ultrasonic wave. iii.
Measure Echo: Capture the time between the Echo pin going HIGH and LOW.
iv. Calculate Distance: Use the formula Distance=Time×3432\text{Distance} =
\frac{\text{Time} \times 343}{2}Distance=2Time×343 to determine the distance.
v. Display Result: Output the calculated distance to the desired interface. vi. Repeat:
Continuously repeat the measurement for real-time distance monitoring.
5. Connections:
• Connect the VCC pin of the ultrasonic sensor to the 5V pin on the microcontroller.
• Connect the GND pin of the sensor to the GND pin on the microcontroller.
• Connect the Trig pin of the sensor to a digital output pin on the microcontroller (e.g., D2).
Step 3: Echo Pin Connection
DEPARTMENT OF
COMPUTERSCIENCE&ENGINEERING
• Connect the Echo pin of the sensor to a digital input pin on the microcontroller (e.g., D3).
• Double-check all connections to ensure they are secure and correct according to your
microcontroller’s pin configuration.
6. CODE:
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // Initialize the LCD with the appropriate pins
void setup() {
Serial.begin(115200);
lcd.begin(16, 2);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
lcd.print("Ultra sonic");
lcd.setCursor(0, 1);
lcd.print("Distance Meter");
delay(2000); lcd.clear();
lcd.print(" Circuit Digest");
delay(2000); lcd.clear();
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// LED indication
digitalWrite(LED_PIN, isNearby);
lcd.setCursor(0, 1);
lcd.print("Distance: ");
lcd.print(distanceCM / 100);
lcd.print(" m");
7. Result: