Advertisement
rabirajkhadka

Ultrasonic Arduino

Aug 25th, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. /* HC-SR04 Sensor
  2. This sketch reads an HC-SR04 ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return. The length of the returning pulse is proportional to the distance of the object from the sensor.
  3.  
  4. The circuit:
  5. * VCC connection of the sensor attached to +5V
  6. * GND connection of the sensor attached to the ground.
  7. * TRIG connection of the sensor attached to digital pin 2
  8. * ECHO connection of the sensor attached to digital pin 4
  9. */
  10.  
  11.  
  12. const int trigPin = 2;
  13. const int echoPin = 4;
  14.  
  15. void setup() {
  16. // initialize serial communication:
  17. Serial.begin(9600);
  18. }
  19.  
  20. void loop()
  21. {
  22. // establish variables for the duration of the ping,
  23. // and the distance result in inches and centimeters:
  24. long duration, inches, cm;
  25.  
  26. // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  27. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  28. pinMode(trigPin, OUTPUT);
  29. digitalWrite(trigPin, LOW);
  30. delayMicroseconds(2);
  31. digitalWrite(trigPin, HIGH);
  32. delayMicroseconds(10);
  33. digitalWrite(trigPin, LOW);
  34.  
  35. // Read the signal from the sensor: a HIGH pulse whose
  36. // duration is the time (in microseconds) from the sending
  37. // of the ping to the reception of its echo off of an object.
  38. pinMode(echoPin, INPUT);
  39. duration = pulseIn(echoPin, HIGH);
  40.  
  41. // convert the time into a distance
  42. inches = microsecondsToInches(duration);
  43. cm = microsecondsToCentimeters(duration);
  44.  
  45. Serial.print(inches);
  46. Serial.print("in, ");
  47. Serial.print(cm);
  48. Serial.print("cm");
  49. Serial.println();
  50.  
  51. delay(100);
  52. }
  53.  
  54. long microsecondsToInches(long microseconds)
  55. {
  56. // According to Parallax's datasheet for the PING))), there are
  57. // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  58. // second). This gives the distance travelled by the ping, outbound
  59. // and return, so we divide by 2 to get the distance of the obstacle.
  60. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  61. return microseconds / 74 / 2;
  62. }
  63.  
  64. long microsecondsToCentimeters(long microseconds)
  65. {
  66. // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  67. // The ping travels out and back, so to find the distance of the
  68. // object we take half of the distance travelled.
  69. return microseconds / 29 / 2;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement