Advertisement
tedotedo771

Arduino Uno with ULTRASONIC SENSOR

Aug 28th, 2016
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. /*
  2. * Ultrasonic Sensor HC-SR04 and Arduino Tutorial
  3. *
  4. * Builded by Teodor Hristov
  5. * www.dev-hn.com
  6. *
  7. */
  8.  
  9. // defines pins numbers
  10. int trig = 2;
  11. int echo = 3;
  12. int go = 4;
  13.  
  14. // defines variables
  15. long duration;
  16. int distance;
  17.  
  18. void setup() {
  19. pinMode(go, OUTPUT);
  20. pinMode(trig, OUTPUT); // Sets the trig as an Output
  21. pinMode(echo, INPUT); // Sets the echo as an Input
  22. Serial.begin(9600); // Starts the serial communication
  23. }
  24.  
  25. void loop() {
  26. // Clears the trig
  27. digitalWrite(trig, LOW);
  28. delayMicroseconds(2);
  29.  
  30. // Sets the trig on HIGH state for 10 micro seconds
  31. digitalWrite(trig, HIGH);
  32. delayMicroseconds(10);
  33. digitalWrite(trig, LOW);
  34.  
  35. // Reads the echo, returns the sound wave travel time in microseconds
  36. duration = pulseIn(echo, HIGH);
  37.  
  38. // Calculating the distance
  39. distance= duration*0.034/2;
  40.  
  41. if (distance > 50){
  42.  
  43.  digitalWrite(go, HIGH);// High voltage on go or pin 4
  44.   }
  45.   else {
  46.     digitalWrite(go, LOW);
  47.    
  48.     }
  49.  
  50.  
  51. // Prints the distance on the Serial Monitor
  52. Serial.print("Distance: ");
  53. Serial.println(distance);
  54. delay(250); //1/4 from 1 sec
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement