Advertisement
Megafish1024

Arduino Sonar Scanner

Mar 19th, 2025
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <Servo.h>
  2.  
  3. #define TRIG_PIN 7
  4. #define ECHO_PIN 8
  5. #define SERVO_PIN 9
  6. #define BUZZER_PIN 10
  7.  
  8. Servo myServo;
  9.  
  10. void setup() {
  11.     Serial.begin(9600);
  12.     pinMode(TRIG_PIN, OUTPUT);
  13.     pinMode(ECHO_PIN, INPUT);
  14.     pinMode(BUZZER_PIN, OUTPUT);
  15.     myServo.attach(SERVO_PIN);
  16. }
  17.  
  18. void loop() {
  19.     // Sweep from 0° to 180°
  20.     for (int angle = 0; angle <= 180; angle += 5) {
  21.         myServo.write(angle);
  22.         delay(50);
  23.         float distance = getDistance();
  24.         Serial.print(angle);
  25.         Serial.print(",");
  26.         Serial.println(distance);
  27.  
  28.         // Buzzer alert if distance < 50 cm
  29.         if (distance > 0 && distance < 50) {
  30.             digitalWrite(BUZZER_PIN, HIGH);
  31.         } else {
  32.             digitalWrite(BUZZER_PIN, LOW);
  33.         }
  34.     }
  35.  
  36.     // Sweep back from 180° to 0°
  37.     for (int angle = 180; angle >= 0; angle -= 5) {
  38.         myServo.write(angle);
  39.         delay(50);
  40.         float distance = getDistance();
  41.         Serial.print(angle);
  42.         Serial.print(",");
  43.         Serial.println(distance);
  44.  
  45.         // Buzzer alert if distance < 50 cm
  46.         if (distance > 0 && distance < 50) {
  47.             digitalWrite(BUZZER_PIN, HIGH);
  48.         } else {
  49.             digitalWrite(BUZZER_PIN, LOW);
  50.         }
  51.     }
  52. }
  53.  
  54. // Function to measure distance
  55. float getDistance() {
  56.     digitalWrite(TRIG_PIN, LOW);
  57.     delayMicroseconds(2);
  58.     digitalWrite(TRIG_PIN, HIGH);
  59.     delayMicroseconds(10);
  60.     digitalWrite(TRIG_PIN, LOW);
  61.  
  62.     long duration = pulseIn(ECHO_PIN, HIGH, 30000); // Timeout
  63.     if (duration == 0) return -1; // No object detected
  64.  
  65.     float distance = duration * 0.034 / 2;  // Convert time to distance
  66.     return distance;
  67. }
Tags: C++ Arduino
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement