Advertisement
Guest User

Untitled

a guest
Jun 24th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. // Libraries
  2. #include <Servo.h>
  3.  
  4. //Fixed pins
  5. // Servo
  6. const int servoPin = 3;
  7. // Ultrasonic Sensor
  8. const int trigPin = 12;
  9. const int echoPin = 11;
  10. // Motors
  11. const int enA = 10;
  12. const int in1 = 9;
  13. const int in2 = 8;
  14. const int in3 = 7;
  15. const int in4 = 6;
  16. const int enB = 5;
  17.  
  18. //other variables
  19. Servo myServo;
  20. long duration;
  21. int distance;
  22. int zero = 0;
  23. int right = 50;
  24. int middle = 100;
  25. int left = 150;
  26.  
  27. void setup() {
  28.   // put your setup code here, to run once:
  29.   pinMode(enA, OUTPUT);
  30.   pinMode(enB, OUTPUT);
  31.   pinMode(in1, OUTPUT);
  32.   pinMode(in2, OUTPUT);
  33.   pinMode(in3, OUTPUT);
  34.   pinMode(in4, OUTPUT);
  35.   myServo.attach(servoPin);
  36.   pinMode(trigPin, OUTPUT);
  37.   pinMode(echoPin, INPUT);
  38.   Serial.begin(9600);
  39. }
  40.  
  41. void loop() {
  42.   // make it run only once (there's probably a better way ^^)
  43.   if(zero == 0){
  44.     testDriving();
  45.     zero++;
  46.   }
  47. }
  48.  
  49. void testDriving()
  50. {
  51.   digitalWrite(in1, HIGH);
  52.   digitalWrite(in2, LOW);
  53.   analogWrite(enA, 200);
  54.   digitalWrite(in3, HIGH);
  55.   digitalWrite(in4, LOW);
  56.   analogWrite(enB, 200);
  57.   delay(5000);
  58.  
  59.  
  60.   Serial.println(getDistance(right));
  61.   delay(2000);
  62.   Serial.println(getDistance(middle));
  63.   delay(2000);
  64.   Serial.println(getDistance(left));
  65.   delay(2000);
  66. }
  67.  
  68.  
  69. int getDistance(int rotation){
  70.   myServo.write(rotation);
  71.   delay(500);
  72.   // Clears the trigPin
  73.   digitalWrite(trigPin, LOW);
  74.   delayMicroseconds(2);
  75.   // Sets the trigPin on HIGH state for 10 micro seconds
  76.   digitalWrite(trigPin, HIGH);
  77.   delayMicroseconds(10);
  78.   digitalWrite(trigPin, LOW);
  79.   // Reads the echoPin, returns the sound wave travel time in microseconds
  80.   duration = pulseIn(echoPin, HIGH);
  81.   // Calculating the distance
  82.   distance= duration*0.034/2;
  83.   return distance;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement