Advertisement
Guest User

Untitled

a guest
Dec 15th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. const byte trig = 12;
  2. const byte echo = 11;
  3.  
  4. const int numReadings = 25;
  5.  
  6. long readings[numReadings]; // the readings from the analog input
  7. long readIndex = 0; // the index of the current reading
  8. long total = 0; // the running total
  9. float average = 0;
  10.  
  11. int duration;
  12. float distance;
  13.  
  14. void setup() {
  15. pinMode(trig, OUTPUT);
  16. pinMode(echo, INPUT);
  17.  
  18. Serial.begin(9600);
  19. for (int thisReading = 0; thisReading < numReadings; thisReading++) {
  20. readings[thisReading] = 0;
  21. }
  22. }
  23.  
  24. void loop() {
  25. digitalWrite(trig, LOW);
  26. delayMicroseconds(2);
  27.  
  28. digitalWrite(trig, HIGH);
  29. delayMicroseconds(10);
  30. digitalWrite(trig, LOW);
  31.  
  32. duration = pulseIn(echo, HIGH);
  33.  
  34. total = total - readings[readIndex];
  35. readings[readIndex] = duration;
  36. total = total + readings[readIndex];
  37. readIndex = readIndex + 1;
  38. average = total / numReadings;
  39.  
  40. distance = average*0.034 / 2.00;
  41.  
  42. if (readIndex >= numReadings) {
  43. readIndex = 0;
  44. }
  45.  
  46. delay(10);
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement