talofer99

Ultrasonic

Apr 24th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. /*
  2. * Ultrasonic Sensor HC-SR04 and Arduino Tutorial
  3. *
  4. * Crated by Dejan Nedelkovski,
  5. * www.HowToMechatronics.com
  6. *
  7. */
  8.  
  9. // defines pins numbers
  10. const int trigPin = 9;
  11. const int echoPin = 10;
  12.  
  13. // defines variables
  14. long duration;
  15. int distance;
  16.  
  17. void setup() {
  18. pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  19. pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  20. Serial.begin(9600); // Starts the serial communication
  21. }
  22.  
  23. void loop() {
  24. // Clears the trigPin
  25. digitalWrite(trigPin, LOW);
  26. delayMicroseconds(2);
  27.  
  28. // Sets the trigPin on HIGH state for 10 micro seconds
  29. digitalWrite(trigPin, HIGH);
  30. delayMicroseconds(10);
  31. digitalWrite(trigPin, LOW);
  32.  
  33. // Reads the echoPin, returns the sound wave travel time in microseconds
  34. duration = pulseIn(echoPin, HIGH);
  35.  
  36. // Calculating the distance
  37. distance= duration*0.034/2;
  38.  
  39. // Prints the distance on the Serial Monitor
  40. Serial.print("Distance: ");
  41. Serial.println(distance);
  42. }
Add Comment
Please, Sign In to add comment