Guest User

Untitled

a guest
Jul 23rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. int motorForward = 9; //Motor control pin
  2. int motorBackward = 10; //Motor control pin
  3. float duration; //Variable
  4. float distance; //Variable
  5. int echoPin = 8; //Echo pin of HC-SR04
  6. int triggerPin = 7; //Trigger pin of HC-SR04
  7. float maxDistance=200;
  8.  
  9.  
  10. void setup() {
  11. pinMode(echoPin,INPUT);
  12. pinMode(triggerPin,OUTPUT);
  13. pinMode(motorForward,OUTPUT);
  14. pinMode(motorBackward,OUTPUT);
  15. Serial.begin(9600); //Enable serial monitor
  16.  
  17. }
  18.  
  19. void move_forward() //Function to move motor 'forward'
  20. {analogWrite(motorForward,maxDistance-255+distance);
  21. digitalWrite(motorBackward,LOW);
  22. }
  23.  
  24. void move_backward() //Function to move motor 'backward'
  25. {analogWrite(motorBackward,50+distance);
  26. digitalWrite(motorForward,LOW);
  27. }
  28.  
  29. void move_stop() //Function to stop the motor
  30. {digitalWrite(motorForward,LOW);
  31. digitalWrite(motorBackward,LOW);
  32. }
  33. void loop() {
  34. digitalWrite(triggerPin,LOW); //Ensure the sensor is not ON at start of loop
  35. delayMicroseconds(2);
  36.  
  37. digitalWrite(triggerPin,HIGH); //Trigger the sensor to send a high frequency pulse
  38. delayMicroseconds(10);
  39. digitalWrite(triggerPin,LOW);
  40. duration = pulseIn(echoPin,HIGH); //Calculate time taken to receive the reflected signal
  41. distance = (duration/2)*0.0344; //Compute distance of object (in cm) from the sensor face
  42. if (distance >= maxDistance || distance <= 2){ //Display the distance, change the condition for your range
  43. Serial.print("Distance = ");
  44. Serial.println("Out of range");
  45. }
  46. else {
  47. Serial.print("Distance = ");
  48. Serial.print(distance);
  49. Serial.println(" cm");
  50. }
  51. if(distance<=20) //If object is at a distance less than 20 cm, move 'forward'
  52. {move_backward();
  53. }
  54. if(distance>=30) //If object is at a distance greater than 30 cm, move 'backward'
  55. {move_forward();
  56. }
  57. if(distance>20 and distance<30) //If object is between 20 and 30 cm from the sensor, stop the motor
  58. {move_stop();
  59. }
  60. delay(500); //Run every half second
  61. }
Add Comment
Please, Sign In to add comment