Advertisement
Ceiifadore

Ultrassônico e servo

Nov 11th, 2015
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. #include <Servo.h>
  2. #define trigpin 5//set trigpin
  3. #define echopin 6//set echopin
  4.  
  5. Servo myservo;// declare servo name type servo
  6. int duration, distance;//declare variable for unltrasonic sensor
  7.  
  8. void setup() {
  9. Serial.begin(9600);
  10. pinMode(trigpin, OUTPUT);
  11.  
  12. pinMode(echopin, INPUT);
  13. myservo.attach(2);// attach your servo
  14. myservo.writeMicroseconds(1500);
  15. // put your setup code here, to run once:
  16. }
  17. void loop() {
  18. myservo.write(0);// always set servo to 90 to position it to the middle
  19. //ultrasonic code
  20. digitalWrite(trigpin,HIGH);
  21. delay(500);
  22. digitalWrite(trigpin, LOW);
  23.  
  24. duration=pulseIn(echopin,HIGH);
  25. distance=(duration/2)/29.1;
  26. if(distance <=3)// if ultrasonic sensor detects an obstacle less than 20cm in 90 degree angle.
  27. {
  28. myservo.write(90); //servo rotates at full speed to the right
  29. delay(30000);
  30. }
  31. else
  32. { myservo.write(0);
  33. delay (200);
  34. }
  35.  
  36. Serial.print("cm"); //print distance unit cm
  37. Serial.println(distance);//distance
  38.  
  39. // put your main code here, to run repeatedly:
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement