Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Ultrasonic Sensor Code

This document contains Arduino code for using an ultrasonic sensor to measure distance. It defines pins for triggering and receiving echo, calculates distance in both centimeters and inches, and prints the results to the Serial Monitor. The loop function continuously measures and displays the distance every second.

Uploaded by

VINEETH KUMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views1 page

Ultrasonic Sensor Code

This document contains Arduino code for using an ultrasonic sensor to measure distance. It defines pins for triggering and receiving echo, calculates distance in both centimeters and inches, and prints the results to the Serial Monitor. The loop function continuously measures and displays the distance every second.

Uploaded by

VINEETH KUMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

ultrasonic sensor code

const int trigPin = 12;


const int echoPin = 14;

//define sound velocity in cm/uS


#define SOUND_VELOCITY 0.034
#define CM_TO_INCH 0.393701

long duration;
float distanceCm;
float distanceInch;

void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculate the distance


distanceCm = duration * SOUND_VELOCITY/2;

// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;

// Prints the distance on the Serial Monitor


Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);

delay(1000);
}

You might also like