Advertisement
Guest User

Arduino Code

a guest
May 17th, 2014
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. /*
  2. HC-SR04 Ping distance sensor:
  3. VCC to arduino 5v
  4. GND to arduino GND
  5. Echo to Arduino pin 7
  6. Trig to Arduino pin 8
  7.  
  8. This sketch originates from Virtualmix: http://goo.gl/kJ8Gl
  9. Has been modified by Winkle ink here: http://winkleink.blogspot.com.au/2012/05/arduino-hc-sr04-ultrasonic-distance.html
  10. And modified further by ScottC here: http://arduinobasics.blogspot.com.au/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html
  11. on 10 Nov 2012.
  12. */
  13.  
  14.  
  15. #define echoPin 7 // Echo Pin
  16. #define trigPin 8 // Trigger Pin
  17. #define LEDPin 13 // Onboard LED
  18.  
  19. int maximumRange = 200; // Maximum range needed
  20. int minimumRange = 0; // Minimum range needed
  21. long duration, distance; // Duration used to calculate distance
  22.  
  23. void setup() {
  24. Serial.begin (9600);
  25. pinMode(trigPin, OUTPUT);
  26. pinMode(echoPin, INPUT);
  27. pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
  28. }
  29.  
  30. void loop() {
  31. /* The following trigPin/echoPin cycle is used to determine the
  32. distance of the nearest object by bouncing soundwaves off of it. */
  33. digitalWrite(trigPin, LOW);
  34. delayMicroseconds(2);
  35.  
  36. digitalWrite(trigPin, HIGH);
  37. delayMicroseconds(10);
  38.  
  39. digitalWrite(trigPin, LOW);
  40. duration = pulseIn(echoPin, HIGH);
  41.  
  42. //Calculate the distance (in cm) based on the speed of sound.
  43. distance = duration/58.2;
  44.  
  45. if (distance >= maximumRange || distance <= minimumRange){
  46. /* Send a negative number to computer and Turn LED ON
  47. to indicate "out of range" */
  48. Serial.println("-1");
  49. digitalWrite(LEDPin, HIGH);
  50. }
  51. else {
  52. /* Send the distance to the computer using Serial protocol, and
  53. turn LED OFF to indicate successful reading. */
  54. Serial.println(distance);
  55. digitalWrite(LEDPin, LOW);
  56. }
  57.  
  58. //Delay 50ms before next reading.
  59. delay(50);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement