5.Ultrasonic Obstacle Detection with Buzzer
Ultrasonic Obstacle Detection with Buzzer
Materials Needed:
- Arduino board
- Ultrasonic sensor (e.g., HC-SR04)
- Buzzer
- Jumper wires
- Breadboard (optional)
Connections:
Ultrasonic Sensor to Arduino:
- TRIG pin → Pin 9
- ECHO pin → Pin 10
- VCC pin → 5V
- GND pin → GND
Buzzer to Arduino:
- Connect one terminal of the buzzer to Pin 11.
- Connect the other terminal to GND.
Connect the Ultrasonic Sensor and Buzzer:
- Use jumper wires to connect the ultrasonic sensor as described above.
- Connect the buzzer to Pin 11 and GND.
Write the Arduino Code:
- Copy and paste the following code into the Arduino IDE:
Procedure:
C++ Code
const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 11;
int thresholdDistance = 20; // Set the distance threshold in centimeters
void setup() {
Serial.begin(9600); // Start the serial communication at 9600 baud rate
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
long duration;
int distance;
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on the buzzer if the object is closer than the threshold distance
if (distance <= thresholdDistance) {
tone(buzzerPin, 1000); // Emit a 1kHz sound
} else {
noTone(buzzerPin); // Turn off the buzzer
}
delay(500); // Wait for a short while before the next measurement
}
Upload the Code:
- Connect your Arduino to the computer and upload the code using the Arduino IDE.
Open the Serial Monitor:
- Open the Serial Monitor to see the distance readings. Ensure the baud rate is set to 9600.
Observe Buzzer Behavior:
- The buzzer will emit a sound when an object is closer than 20 cm (you can adjust the
thresholdDistance
value to change the threshold). - When the object is beyond that distance, the buzzer will turn off.
- The buzzer will emit a sound when an object is closer than 20 cm (you can adjust the
Explanation:
tone(buzzerPin, 1000)
) generates the sound, and the noTone(buzzerPin)
function turns it off.
Comments
Post a Comment