Purpose:
The code is designed to interact with an HC-SR04 ultrasonic sensor and a buzzer to
detect objects within a certain distance. When an object is detected within 15 cm,
the buzzer is activated to alert the user.
Breakdown:
1. Include necessary libraries:
○ #define trigPin 9 and #define echoPin 8 define the pins
connected to the trigger and echo pins of the HC-SR04 sensor,
respectively.
○ #define BUZ 13 defines the pin connected to the buzzer.
2. Declare variables:
○ long duration, distance; declares two long integer variables to
store the measured pulse duration and calculated distance.
3. Setup function:
○ pinMode(BUZ, OUTPUT); sets the BUZ pin as an output to control the
buzzer.
○ pinMode(trigPin, OUTPUT); sets the trigPin as an output to send
ultrasonic pulses.
○ pinMode(echoPin, INPUT); sets the echoPin as an input to receive
the reflected echo pulses.
4. Loop function:
○ Serial.begin(9600); initialises serial communication at a baud rate
of 9600 for debugging and monitoring.
○ digitalWrite(trigPin, LOW); sets the trigPin low to prepare for
sending a pulse.
○ delayMicroseconds(2); delays for 2 microseconds.
○ digitalWrite(trigPin, HIGH); sends a 10-microsecond high pulse
to trigger the ultrasonic sensor.
○ delayMicroseconds(10); delays for 10 microseconds.
○ duration = pulseIn(echoPin, HIGH); measures the time taken for
the echo pulse to return and stores it in the duration variable.
○ distance = duration / 58.2; calculates the distance to the object
based on the measured pulse duration and the speed of sound
(approximately 58.2 cm/µs).
○ Serial.println(distance); prints the calculated distance to the
serial monitor for debugging.
○ delay(10); delays for 10 milliseconds.
○ if (distance < 15): This conditional statement checks if the
detected distance is less than 15 cm.
■ If the distance is less than 15 cm, the buzzer is activated 5
times:
■ for (int i=0; i<5; i++): This loop iterates 5 times.
■ digitalWrite(BUZ, HIGH); turns on the buzzer.
■ delay(50); delays for 50 milliseconds.
■ digitalWrite(BUZ, LOW); turns off the buzzer.
■ delay(50); delays for 50 milliseconds.
Overall Functionality:
The code continuously measures the distance to an object using the HC-SR04
ultrasonic sensor. If an object is detected within 15 cm, the buzzer is activated to
alert the user. The calculated distance is also printed to the serial monitor for
debugging purposes.