Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

const int trigPin = 2;
const int echoPin = 3;

const int numReadings = 10;
int readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average

void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}

void loop() {
long duration, inches;

// send a 10 microsecond pulse to the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// read the duration of the pulse from the echo pin
duration = pulseIn(echoPin, HIGH);

// calculate the distance in inches
inches = duration / 74 / 2;

// subtract the last reading:
total = total - readings[index];
// read from the sensor:
readings[index] = inches;
// add the reading to the total:
total = total + readings[index];
// advance to the next position in the array:
index = index + 1;

// if we're at the end of the array, wrap around to the beginning:
if (index >= numReadings)
index = 0;

// calculate the average:
average = total / numReadings;

Serial.print("Distance: ");
Serial.print(average);
Serial.println(" inches");

delay(100);
}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.