0% found this document useful (0 votes)
32 views2 pages

Ultrasonic Sensor

Uploaded by

Zohaib Javed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views2 pages

Ultrasonic Sensor

Uploaded by

Zohaib Javed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

// Pin definitions

const int trigPin = 9;


const int echoPin = 10;
const int ledPin = 2;
const int buzzerPin = 12;

// Variables for duration and distance


long duration;
int distance;

void setup() {
// Initialize pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);

// Begin Serial communication


[Link](9600);
}

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

// Measure the duration of the echo


duration = pulseIn(echoPin, HIGH);

// Calculate distance in cm (speed of sound is ~343 meters per


second)
distance = duration * 0.034 / 2;

// Display the distance on the Serial Monitor


[Link]("Distance: ");
[Link](distance);
[Link](" cm");

// If the distance is less than 20 cm, turn on LED and buzzer


if (distance < 20) {
digitalWrite(ledPin, HIGH);
digitalWrite(buzzerPin, HIGH);
} else {
// Otherwise, turn them off
digitalWrite(ledPin, LOW);
digitalWrite(buzzerPin, LOW);
}

// Small delay before the next reading


delay(500);
}

You might also like