Why This Code Is Useful
Why This Code Is Useful
- These lines define four constants: `trigPin`, `echoPin`, `buzzer`, and `ledPin`. They represent the pin
numbers to which components are connected.
2. ```cpp
long duration;
int distance;
int safetyDistance;
These lines declare three variables: duration, distance, and safetyDistance. These variables will be used
to store values related to the operation of the ultrasonic sensor.
void setup() {
pinMode(buzzer, OUTPUT);
pinMode(ledPin, OUTPUT);
}
- The `setup()` function initializes the pins. It sets `trigPin` as an output pin, `echoPin` as an input pin,
and configures `buzzer` and `ledPin` as output pins. It also starts serial communication at a baud rate of
9600.
4. ```cpp
void loop() {
delayMicroseconds(2);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in
microseconds
safetyDistance = distance;
if (safetyDistance <= 5) {
digitalWrite(buzzer, HIGH);
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(buzzer, LOW);
digitalWrite(ledPin, LOW);
}
Serial.print("Distance: "); // Prints the distance on the Serial Monitor
Serial.println(distance);
The loop() function is where the main operation of the code occurs:
It measures the duration of the echo pulse, which corresponds to the time taken for the ultrasonic signal
to travel to the object and back.
It checks if the calculated distance is less than or equal to 5 units (presumably in centimeters or inches).
If so, it activates the buzzer and LED to indicate that an object is too close. Otherwise, it turns off the
buzzer and LED.
It prints the calculated distance to the Serial Monitor for debugging or monitoring purposes.