0% found this document useful (0 votes)
8 views1 page

Arduino Ultrasonic Distance Sensor Code

This document contains an Arduino code for measuring distance using an ultrasonic sensor. It defines pin numbers for triggering and receiving signals, initializes the Serial Monitor, and calculates the distance based on the duration of the pulse. The distance is printed to the Serial Monitor every half second.

Uploaded by

keshavjkapoor24
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)
8 views1 page

Arduino Ultrasonic Distance Sensor Code

This document contains an Arduino code for measuring distance using an ultrasonic sensor. It defines pin numbers for triggering and receiving signals, initializes the Serial Monitor, and calculates the distance based on the duration of the pulse. The distance is printed to the Serial Monitor every half second.

Uploaded by

keshavjkapoor24
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

// Define pin numbers

const int trigPin = 9;


const int echoPin = 8;

// Define variables for duration and distance


long duration;
float distance;

void setup() {
// Initialize the Serial Monitor
[Link](9600);

// Set trigPin as an OUTPUT and echoPin as an INPUT


pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Set the trigPin HIGH for 10 microseconds


digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the echoPin, and measure the duration of the pulse in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculate the distance in cm


distance = duration * 0.034 / 2; // Speed of sound = 343 m/s or 0.034 cm/μs

// Print the distance to the Serial Monitor


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

// Wait for a short period before the next measurement


delay(500);
}

You might also like