0% found this document useful (0 votes)
5 views

New Text Document

This document contains an Arduino code for interfacing an ultrasonic sensor. It defines the setup for triggering the sensor and measuring distance using pulse duration. The calculated distance is printed to the Serial Monitor every 500 milliseconds.

Uploaded by

alakhsir786
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

New Text Document

This document contains an Arduino code for interfacing an ultrasonic sensor. It defines the setup for triggering the sensor and measuring distance using pulse duration. The calculated distance is printed to the Serial Monitor every 500 milliseconds.

Uploaded by

alakhsir786
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

// Define the pins for the ultrasonic sensor

const int trigPin = 9; // Trigger pin connected to Arduino Pin 9


const int echoPin = 10; // Echo pin connected to Arduino Pin 10

// Variables to store the duration and distance


long duration; // Duration of the pulse in microseconds
int distance; // Calculated distance in centimeters

void setup() {
// Start the serial communication
Serial.begin(9600);

// Set the trigPin as OUTPUT and echoPin as INPUT


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

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

// Send a 10-microsecond pulse to the trigPin to initiate the ultrasonic pulse


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

// Read the pulse duration from the echoPin


duration = pulseIn(echoPin, HIGH);

// Calculate the distance (speed of sound in air is 0.0344 cm per microsecond)


distance = duration * 0.0344 / 2;

// Print the distance to the Serial Monitor


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

// Wait for a while before the next reading


delay(500);
}

You might also like