#define trigPin 13 // This defines a constant "trigPin" with the value "13".
#define echoPin 12 // This defines a constant "echoPin" with the value "12".
#define led 11 // This defines a constant "led" with the value "11".
void setup() {
Serial.begin(9600); // Initializes the serial communication at baud rate of 9600 bits per second.
pinMode(trigPin, OUTPUT); // Sets the "trigPin" (pin13) as an output. This pin will send a signal to the ultrasonic sensor.
pinMode(echoPin, INPUT); // Sets the "echoPin" (pin12) as an input.
pinMode(led, OUTPUT); // Sets the "led" (pin11) as an output. This controls the LED.
}
void loop() {
long duration, distance; // Declared two variables "duration" and "distance" of type 'long' to store the time and distance.
digitalWrite(trigPin, LOW); // Sets the "trigPin" to 'LOW', ensuring there is no lingering signal from previous readings.
delayMicroseconds(2); // Waits for 2 microseconds to ensure a clean signal start.
digitalWrite(trigPin, HIGH); // Sets the "trigPin" to 'HIGH', sending a 10 microsecond pulse to the ultrasonic sensor.
delayMicroseconds(10); // Waits for 10 microseconds while the pulse is being sent.
digitalWrite(trigPin, LOW); // Stops the pulse by setting the "trigPin" to 'LOW'.
duration = pulseIn(echoPin, HIGH); // Measures the time in microseconds that "echoPin" is set to 'HIGH'.
distance = (duration/2) / 29.1; // The distance is divided by 2 because the pulse travels to the object and back.
if (distance < 100) {
digitalWrite(led, HIGH); // If the distance is less than 100 cm, LED is turned on.
} else {
digitalWrite(led, LOW); // If the distance is 100 cm or more, LED is off.
}
Serial.print(distance); // Prints distance in value.
Serial.print("cm"); // Prints cm after distance.
delay(500); // Pauses the loop for 500 milliseconds before the next measurement.
}