Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const byte trig = 12;
- const byte echo = 11;
- const int numReadings = 25;
- long readings[numReadings]; // the readings from the analog input
- long readIndex = 0; // the index of the current reading
- long total = 0; // the running total
- float average = 0;
- int duration;
- float distance;
- void setup() {
- pinMode(trig, OUTPUT);
- pinMode(echo, INPUT);
- Serial.begin(9600);
- for (int thisReading = 0; thisReading < numReadings; thisReading++) {
- readings[thisReading] = 0;
- }
- }
- void loop() {
- digitalWrite(trig, LOW);
- delayMicroseconds(2);
- digitalWrite(trig, HIGH);
- delayMicroseconds(10);
- digitalWrite(trig, LOW);
- duration = pulseIn(echo, HIGH);
- total = total - readings[readIndex];
- readings[readIndex] = duration;
- total = total + readings[readIndex];
- readIndex = readIndex + 1;
- average = total / numReadings;
- distance = average*0.034 / 2.00;
- if (readIndex >= numReadings) {
- readIndex = 0;
- }
- delay(10);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement