6677

Arduino Obstacle Avoidance Code

Oct 17th, 2013
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.23 KB | None | 0 0
  1. //Arduino/Energia Obstacle Avoidance Robot Code, Callum King-Underwood, 17/10/2013, do whatever the hell you want with it
  2.  
  3. //These are the pins used for the HCSR04
  4. int echo = 2;
  5. int trigger = 3;
  6.  
  7. //These are the pins for the motor driver, I used an L9110S
  8. int AIA = 10;  //Motor A, input A
  9. int AIB = 9;   //Motor A, input B
  10. int BIA = 8;   //Motor B, input A
  11. int BIB = 7;   //Motor B, input B
  12.  
  13. //Variables for the distance measurements
  14. int distance;  //This you leave alone, the program will fill it as required.
  15. int dangerLevel = 50;//this is in cm, the distance at which to avoid an obstacle.
  16. void setup()
  17. {
  18.   // set the motor driver pins to output
  19.   pinMode(AIA, OUTPUT);
  20.   pinMode(AIB, OUTPUT);
  21.   pinMode(BIA, OUTPUT);
  22.   pinMode(BIB, OUTPUT);
  23.   //set the motor driver pins high to start with.
  24.   //both pins being high results in the motor not spinning, as does both low, I don't think it matters which you use.
  25.   digitalWrite(AIA, HIGH);
  26.   digitalWrite(AIB, HIGH);
  27.   digitalWrite(BIA, HIGH);
  28.   digitalWrite(BIB, HIGH);
  29.  
  30.   //set the ultrasound pins up too
  31.   pinMode(echo, INPUT);
  32.   pinMode(trigger, OUTPUT);
  33.   digitalWrite(trigger, LOW);
  34.  
  35.   Serial.begin(9600);
  36. }
  37.  
  38. void loop()
  39. {
  40.   //Send a short pulse on HCSR04 trigger
  41.   digitalWrite(trigger, HIGH);
  42.   delay(1);
  43.   digitalWrite(trigger, LOW);
  44.  
  45.   //record the pulse from the echo pin
  46.   distance = pulseIn(echo, HIGH);
  47.  
  48.   //dividing it by 58 roughly converts to cm, tweak this value if you wish.
  49.   distance = distance / 58;
  50.   //debug feature: print out the distance over serial.
  51.   Serial.println(distance);
  52.   if (distance > dangerLevel){
  53.     //there is no obstacle too close to the robot. We will go forwards.
  54.     //you may need to rewire the motor or swap a low for a high and vice versa to get the correct direction for your robot
  55.     digitalWrite(AIA, LOW);
  56.     digitalWrite(AIB, HIGH);
  57.     digitalWrite(BIA, LOW);
  58.     digitalWrite(BIB, HIGH);
  59.   }
  60.   else{
  61.     //there is an obstacle, so one motor will go forwards and the other backwards.
  62.     digitalWrite(AIA, LOW);
  63.     digitalWrite(AIB, HIGH);
  64.     digitalWrite(BIA, HIGH);
  65.     digitalWrite(BIB, LOW);
  66.     //Confirm that we are avoiding an obstacle over serial.
  67.     Serial.println("Danger Hit");
  68.   }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment