// Define the pin number connected to the TRIG pin of the ultrasonic sensor
const int TRIG_PIN = 13;
// Define the pin number connected to the ECHO pin of the ultrasonic sensor
const int ECHO_PIN = 12;
// Declare variables to store the echo pulse duration and calculated distance
long duration, distance;
void setup() {
// Start serial communication at 115200 baud rate
// This is used to display distance values on the Serial Monitor
Serial.begin(115200);
// Set TRIG pin as OUTPUT because Arduino sends trigger pulses to the sensor
pinMode(TRIG_PIN, OUTPUT);
// Set ECHO pin as INPUT because Arduino receives echo signal from the sensor
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Call the distance calculation function and store the returned value
distance = getDistanceInCentimeters();
// Print the distance value on the Serial Monitor
// String(distance) converts the number into text format
Serial.println("ULTRASONIC SENSOR Distance = " + String(distance));
// Delay of 1 second between each reading
delay(1000);
}
// Function to calculate distance in centimeters
long getDistanceInCentimeters() {
// Ensure TRIG pin is LOW before sending a pulse
digitalWrite(TRIG_PIN, LOW);
// Small delay to stabilize the sensor
delayMicroseconds(2);
// Set TRIG pin HIGH to send ultrasonic pulse
digitalWrite(TRIG_PIN, HIGH);
// Keep the pulse HIGH for 10 microseconds (required by HC-SR04)
delayMicroseconds(10);
// Set TRIG pin LOW to stop the pulse
digitalWrite(TRIG_PIN, LOW);
// Measure the time (in microseconds) for which ECHO pin remains HIGH
// This time represents the sound wave travel time (to object and back)
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance using speed of sound:
// Speed of sound = 0.034 cm per microsecond
// Divide by 2 because sound travels to the object and returns back
// +1 is added to reduce small measurement errors
return (duration * 0.034 / 2) + 1;
}