Advertisement
qianzhe

UltraSonic Sensor Trial with tank

Mar 20th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <NewPing.h>
  2. #include <Servo.h>
  3. #define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
  4. #define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
  5. #define MAX_DISTANCE 250 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
  6. Servo left,right; // 360 servo
  7. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
  8. int led=13;
  9. int pos=0;
  10. int pos1=0;
  11. void setup() {
  12. Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  13. pinMode(13, OUTPUT);
  14. left.attach(6);//left side
  15. right.attach(5); //right side
  16. }
  17. void loop() {
  18. Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  19. Serial.println("cm");
  20. if (sonar.ping_cm() >= 15 && sonar.ping_cm() != 0) //move forward
  21. {
  22.  digitalWrite(led, LOW);
  23.  for (pos1 = 95; pos1 <= 360; pos1 += 1) {
  24.   right.write(pos1);
  25.   left.write(-pos1);
  26.   }
  27. }
  28. else if (sonar.ping_cm() > 0 && sonar.ping_cm() <= 15 ) // move left
  29. {
  30.  for(pos1=95; pos1<=360; pos1 +=1){
  31.   right.write(pos1);
  32.   left.write(pos1);
  33.  }
  34. }
  35. else //move backward
  36. {
  37.  digitalWrite(led,HIGH);
  38.  for (pos1 = 95; pos1 <= 360; pos1 += 2){
  39.   right.write(-pos1);
  40.   left.write(pos1);
  41.  }
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement