Advertisement
Raqeeb_Alnakib

Full code scripts for An object detector, with Arduino

Mar 5th, 2020
6,469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1.  
  2.  
  3. //            Support us on : https://global-prog.com
  4.  
  5.  
  6.  
  7. #include <Ultrasonic.h> // Ultrasonic Library
  8. #include <Servo.h>     // Servo Library
  9.  
  10. Servo servo;
  11.  
  12. Ultrasonic ultrasonic(4,5); // Ultrasonic object for the Ultrasonic library
  13. int pos;                   // Variable to save the servo position
  14. int distance;             // Variable to save the distance from Ultrasonic sensor
  15. int buzzer = 12;        // Define the buzzer pin to pin 12
  16.  
  17. void setup()
  18. {
  19.  
  20.   Serial.begin(9600);        // Begin the serial monitor
  21.  
  22.   servo.attach(3);          // Attach servo pin
  23.  
  24.   pinMode(buzzer, OUTPUT); // Make a buzzer pin as output
  25.  
  26. }
  27.  
  28. void loop()
  29. {
  30.  
  31.   for(pos=0;pos&lt;=180;pos++){ // Loop to go from 0 to 180 degrees
  32.  
  33.     servo.write(pos);  // Write the position to the servo
  34.  
  35.     distance=ultrasonic.read();  // Read the distance from the ultrasonic sensor
  36.  
  37.     Serial.print(pos+&quot; , &quot;);  // Write the position to the serial monitor
  38.  
  39.     Serial.println(distance+&quot; CM&quot;); // Write the distance to the serial monitor
  40.    
  41.        if(distance&lt;=100){  // Buzzer function when the distance less than 100cm
  42.    
  43.        digital.write(buzzer,HIGH);  // Turn the buzzer on
  44.    
  45.        }
  46.    
  47.        else{
  48.    
  49.        digital.write(buzzer,LOW);  // Turn the buzzer off
  50.    
  51.        }
  52.    
  53.   delay(50); // Wait for 50 milliseconds
  54.   }
  55.  
  56.   for(pos=180;pos&gt;=0;pos--){  // Loop to go from 180 to 0 degrees
  57.    
  58.     servo.write(pos);    // Write the position to the servo
  59.    
  60.     distance=ultrasonic.read();  // Read the distance from the ultrasonic sensor
  61.    
  62.     Serial.print(pos+&quot; ْ , &quot;);  // Write the position to the serial monitor
  63.    
  64.     Serial.println(distance+&quot; CM&quot;);  // Write the distance to the serial monitor
  65.    
  66.       if(distance&lt;=100){  // Buzzer function when the distance less than 100cm
  67.        
  68.       digital.write(buzzer,HIGH);  // Turn the buzzer on
  69.        
  70.       }
  71.    
  72.       else{
  73.        
  74.       digital.write(buzzer,LOW);  // Turn the buzzer off
  75.      
  76.       }
  77.    
  78.   delay(50);  // Wait for 50 milliseconds
  79.   }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement