Advertisement
Guest User

Code

a guest
Nov 4th, 2014
780
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. #include <Servo.h>
  2.  
  3. Servo servo;
  4.  
  5. int frontFace = 85; // The Servo's front facing angle
  6. int rightFace = 40; // The Servo's right facing angle
  7. int leftFace = 130; // The Servo's left facing angle
  8.  
  9. #define trigPin 3; // Trig Pin (Digital)
  10. #define echoPin 2; // Echo Pin (Digital)
  11.  
  12. int alertRange = 30; // alert rainge in cm
  13. // #define maximumRange 10000;
  14. // #define minimumRange 0;
  15. long duration, cmFront, cmLeft, cmRight; // Duration used to calculate distance
  16.  
  17. void setup()
  18. {
  19. servo.attach(9);
  20. // Test the servo before begining
  21. servoTest();
  22. Serial.begin(9600);
  23. }
  24.  
  25. void loop()
  26. {
  27. cycleFront();
  28. cycleLeft();
  29. cycleRight();
  30. Serial.print("Front: ");
  31. Serial.print(cmFront);
  32. Serial.print("Left: ");
  33. Serial.print(cmLeft);
  34. Serial.print("Right: ");
  35. Serial.println(cmRight);
  36. }
  37.  
  38. void servoTest()
  39. {
  40. servo.write(frontFace);
  41. delay(1000);
  42. servo.write(rightFace);
  43. delay(1000);
  44. servo.write(frontFace);
  45. delay(1000);
  46. servo.write(leftFace);
  47. delay(1000);
  48. servo.write(frontFace);
  49. delay(1000);
  50. servo.write(0);
  51. delay(1000);
  52. servo.write(180);
  53. delay(1000);
  54. }
  55.  
  56. void cycleFront()
  57. {
  58. digitalWrite(trigPin, LOW);
  59. delayMicroseconds(2);
  60.  
  61. digitalWrite(trigPin, HIGH);
  62. delayMicroseconds(5);
  63.  
  64. digitalWrite(trigPin, LOW);
  65. duration = pulseIn(echoPin, HIGH);
  66.  
  67. cmFront = microsecondsToCentimeters(duration);
  68. }
  69.  
  70. void cycleLeft()
  71. {
  72. digitalWrite(trigPin, LOW);
  73. delayMicroseconds(2);
  74.  
  75. digitalWrite(trigPin, HIGH);
  76. delayMicroseconds(5);
  77.  
  78. digitalWrite(trigPin, LOW);
  79. duration = pulseIn(echoPin, HIGH);
  80.  
  81. cmLeft = microsecondsToCentimeters(duration);
  82. }
  83.  
  84. void cycleRight()
  85. {
  86. digitalWrite(trigPin, LOW);
  87. delayMicroseconds(2);
  88.  
  89. digitalWrite(trigPin, HIGH);
  90. delayMicroseconds(5);
  91.  
  92. digitalWrite(trigPin, LOW);
  93. duration = pulseIn(echoPin, HIGH);
  94.  
  95. cmRight = microsecondsToCentimeters(duration);
  96. }
  97.  
  98. long microsecondsToCentimeters(long microseconds)
  99. {
  100. // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  101. // The ping travels out and back, so to find the distance of the
  102. // object we take half of the distance travelled.
  103. return microseconds / 29 / 2;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement