0% found this document useful (0 votes)
4 views

arduino code- buzzer

ctrs

Uploaded by

higowa5217
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

arduino code- buzzer

ctrs

Uploaded by

higowa5217
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <Servo.

h>

const int buzzerPin = 6;


Servo myservo;
int pos = 0;

// Sensor
const int trig_pin = 3;
const int echo_pin = 2;

float duration, distance;


const int distanceThreshold = 15; // Distance threshold for stopping the servo

void setup() {
Serial.begin(9600);

// Pin setup
pinMode(buzzerPin, OUTPUT);
pinMode(trig_pin, OUTPUT);
pinMode(echo_pin, INPUT);

myservo.attach(5); // Attach servo to pin 5


delay(1000);
}

void loop() {
for (pos = 0; pos <= 180; pos++) {
myservo.write(pos); // Move servo from 0 to 180 degrees
scanAndCheckDistance(pos);
delay(15); // Servo movement delay
}

for (pos = 180; pos >= 0; pos--) {


myservo.write(pos); // Move servo from 180 to 0 degrees
scanAndCheckDistance(pos);
delay(15); // Servo movement delay
}

delay(200); // Additional delay between scans


}

void scanAndCheckDistance(int angle) {


digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);

duration = pulseIn(echo_pin, HIGH);


distance = (duration * 0.0343) / 2; // Calculate distance in cm

Serial.print(angle);
Serial.print(",");
Serial.println(distance);

if (distance < distanceThreshold) {


// If an object is detected within threshold distance, stop the servo and
activate the buzzer
myservo.detach();
tone(buzzerPin, 1000); // Activate buzzer
delay(1000); // Buzzer delay
noTone(buzzerPin); // Turn off buzzer
delay(1000); // Cooldown period to avoid rapid stop-start motion
myservo.attach(5); // Reattach servo to resume scanning
}
}

You might also like