Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. #define TRIG_PIN 1
  2. #define ECHO_PIN 0
  3. #define TIME_OUT 5000
  4.  
  5. float GetDistance()
  6. {
  7. long duration, distanceCm;
  8.  
  9. digitalWrite(TRIG_PIN, LOW);
  10. delayMicroseconds(2);
  11. digitalWrite(TRIG_PIN, HIGH);
  12. delayMicroseconds(10);
  13. digitalWrite(TRIG_PIN, LOW);
  14.  
  15. duration = pulseIn(ECHO_PIN, HIGH, TIME_OUT);
  16.  
  17. // convert to distance
  18. distanceCm = duration / 29.1 / 2;
  19.  
  20. return distanceCm;
  21. }
  22.  
  23. void setup() {
  24. Serial.begin(9600);
  25.  
  26. pinMode(TRIG_PIN, OUTPUT);
  27. pinMode(ECHO_PIN, INPUT);
  28. }
  29.  
  30. void loop() {
  31. long distance = GetDistance();
  32.  
  33. if (distance <= 0)
  34. {
  35. Serial.println("Echo time out !!");
  36. }
  37. else
  38. {
  39. Serial.print("Distance to nearest obstacle (cm): ");
  40. Serial.println(distance);
  41. }
  42. delay(1000);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement