Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Servo.h>
- #define TRIG_PIN 7
- #define ECHO_PIN 8
- #define SERVO_PIN 9
- #define BUZZER_PIN 10
- Servo myServo;
- void setup() {
- Serial.begin(9600);
- pinMode(TRIG_PIN, OUTPUT);
- pinMode(ECHO_PIN, INPUT);
- pinMode(BUZZER_PIN, OUTPUT);
- myServo.attach(SERVO_PIN);
- }
- void loop() {
- // Sweep from 0° to 180°
- for (int angle = 0; angle <= 180; angle += 5) {
- myServo.write(angle);
- delay(50);
- float distance = getDistance();
- Serial.print(angle);
- Serial.print(",");
- Serial.println(distance);
- // Buzzer alert if distance < 50 cm
- if (distance > 0 && distance < 50) {
- digitalWrite(BUZZER_PIN, HIGH);
- } else {
- digitalWrite(BUZZER_PIN, LOW);
- }
- }
- // Sweep back from 180° to 0°
- for (int angle = 180; angle >= 0; angle -= 5) {
- myServo.write(angle);
- delay(50);
- float distance = getDistance();
- Serial.print(angle);
- Serial.print(",");
- Serial.println(distance);
- // Buzzer alert if distance < 50 cm
- if (distance > 0 && distance < 50) {
- digitalWrite(BUZZER_PIN, HIGH);
- } else {
- digitalWrite(BUZZER_PIN, LOW);
- }
- }
- }
- // Function to measure distance
- float getDistance() {
- digitalWrite(TRIG_PIN, LOW);
- delayMicroseconds(2);
- digitalWrite(TRIG_PIN, HIGH);
- delayMicroseconds(10);
- digitalWrite(TRIG_PIN, LOW);
- long duration = pulseIn(ECHO_PIN, HIGH, 30000); // Timeout
- if (duration == 0) return -1; // No object detected
- float distance = duration * 0.034 / 2; // Convert time to distance
- return distance;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement