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:

  1. Ultrasonic Sensor to Arduino:

    • TRIG pin → Pin 9
    • ECHO pin → Pin 10
    • VCC pin → 5V
    • GND pin → GND
  2. Buzzer to Arduino:

    • Connect one terminal of the buzzer to Pin 11.
    • Connect the other terminal to GND.
  3. Procedure:

    1. 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.
    2. Write the Arduino Code:

      • Copy and paste the following code into the Arduino IDE:

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
}

  1. Upload the Code:

    • Connect your Arduino to the computer and upload the code using the Arduino IDE.
  2. Open the Serial Monitor:

    • Open the Serial Monitor to see the distance readings. Ensure the baud rate is set to 9600.
  3. 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.

Explanation:

  • The TRIG pin is used to send a pulse to initiate distance measurement.
  • The ECHO pin receives the reflected pulse, and the time taken is used to calculate the distance.
  • The buzzer is controlled by Pin 11 and emits a 1kHz tone when the object is within the threshold distance.
  • The tone function (tone(buzzerPin, 1000)) generates the sound, and the noTone(buzzerPin) function turns it off.

    Comments

    Popular posts from this blog

    esp8266