Advertisement
NB52053

Untitled

Aug 5th, 2019
1,672
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. // Sonar and servo code
  4.  
  5.  
  6.  
  7.  
  8.  
  9. // Define Trig and Echo pin:
  10. #define trigPin 2
  11. #define echoPin 3
  12. // Define variables:
  13. long duration;
  14. int distance;
  15. #include <Servo.h>
  16. int servoPin = 5;
  17. Servo Servo1;
  18.  
  19. void setup() {
  20.   // Define inputs and outputs:
  21.   pinMode(trigPin, OUTPUT);
  22.   pinMode(echoPin, INPUT);
  23.   //Begin Serial communication at a baudrate of 9600:
  24.   Serial.begin(9600);
  25.   Servo1.attach(servoPin);
  26. }
  27.  
  28.  
  29.  
  30. void loop() {
  31.   // Clear the trigPin by setting it LOW:
  32.   digitalWrite(trigPin, LOW);
  33.   delayMicroseconds(5);
  34.   // Trigger the sensor by setting the trigPin high for 10 microseconds:
  35.   digitalWrite(trigPin, HIGH);
  36.   delayMicroseconds(10);
  37.   digitalWrite(trigPin, LOW);
  38.   // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  39.   duration = pulseIn(echoPin, HIGH);
  40.   // Calculate the distance:
  41.   distance= duration*0.034/2;
  42.   // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  43.   Serial.print("Distance = ");
  44.   Serial.print(distance);
  45.   Serial.println(" cm");
  46.  
  47.   delay(50);
  48.  
  49.  
  50.  
  51.  
  52.   if(distance<=15){
  53.    
  54.  
  55.  // Make servo go to 90 degrees
  56.   Servo1.write(90);
  57.   delay(1000);
  58.  
  59.   }
  60.  
  61.  
  62.    else{  
  63.       Servo1.write(0);
  64.      
  65.    }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement