Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. /*
  2. * Speed should be a floating point value [-1,1].
  3. * i.e. 0.5 means 50% speed in the forward direction, -0.25 would be 25% speed backwards
  4. * Time is a value in milliseconds (1000 milliseconds in 1 second)
  5. */
  6. #define E1 6
  7. #define E2 5
  8. #define M1 8
  9. #define M2 7
  10. #define trigPin 2
  11. #define echoPin 3
  12.  
  13. void rover_right_track(float s) {
  14. if (s > 1.0) s = 1.0;
  15. if ( s < -1.0) s = -1.0;
  16. int spd = 255 * s;
  17. analogWrite(E1, abs(spd));
  18. digitalWrite(M1, (spd >= 0 ? LOW: HIGH));
  19. }
  20. void rover_left_track(float s) {
  21. if (s > 1.0) s = 1.0;
  22. if ( s < -1.0) s = -1.0;
  23. int spd = 255 * s;
  24. analogWrite(E2, abs(spd));
  25. digitalWrite(M2, (spd >= 0 ? LOW: HIGH));
  26. }
  27. void rover_drive(float s, int time) {
  28. if (s > 1.0) s = 1.0;
  29. if ( s < -1.0) s = -1.0;
  30. int spd = 255 * s;
  31. rover_right_track(spd);
  32. rover_left_track(spd);
  33. delay(time);
  34. rover_stop();
  35. }
  36. void rover_rotate_clockwise(float s, int time) {
  37. if (s > 1.0) s = 1.0;
  38. if ( s < -1.0) s = -1.0;
  39. int spd = 255 * s;
  40. rover_right_track(-spd);
  41. rover_left_track(spd);
  42. delay(time);
  43. rover_stop();
  44. }
  45. void rover_rotate_counter_clockwise(float s, int time) {
  46. if (s > 1.0) s = 1.0;
  47. if ( s < -1.0) s = -1.0;
  48. int spd = 255 * s;
  49. rover_right_track(spd);
  50. rover_left_track(-spd);
  51. delay(time);
  52. rover_stop();
  53. }
  54. void rover_stop() {
  55. rover_right_track(0);
  56. rover_left_track(0);
  57. }
  58. // Call this to end the mission
  59. void mission_end() {
  60. rover_stop();
  61. exit(0);
  62. }
  63.  
  64. void setup_hcsr04() {
  65. pinMode(trigPin, OUTPUT);
  66. pinMode(echoPin, INPUT);
  67. }
  68. float readDistance() {
  69. // Clear the trigPin by setting it LOW:
  70. digitalWrite(trigPin, LOW);
  71. delayMicroseconds(5);
  72. // Trigger the sensor by setting the trigPin high for 10 microseconds:
  73. digitalWrite(trigPin, HIGH);
  74. delayMicroseconds(10);
  75. digitalWrite(trigPin, LOW);
  76. // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  77. float duration = pulseIn(echoPin, HIGH);
  78. // Calculate the distance:
  79. float distance = duration*0.034/2;
  80. return distance;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement