/*
MSJ Researchers World
Date - 18th NOV 2024
Mentor - Mr. Siranjeevi M
Contact - 7373771991
*/
// Define pins for Ultrasonic Sensor
const int trigPin = 9; // Trigger pin
const int echoPin = 10; // Echo pin
// Variable to store the duration and distance
long duration;
int distanceCm;
float distanceIn;
void setup()
{
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
// Send a 10-microsecond pulse to trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate the duration
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm and inches
distanceCm = duration * 0.034 / 2; // Speed of sound = 0.034 cm/μs
distanceIn = distanceCm * 0.393701; // 1 cm = 0.393701 inches
// Print the distance in cm and inches to the serial monitor
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.print(" cm, ");
Serial.print(distanceIn);
Serial.println(" in");
// Wait before the next measurement
delay(500);
}