Challenge

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

#define PING_PIN 7 // Arduino pin connected to the PING))) sensor

#define NUM_READINGS 5 // Number of readings to be averaged

long duration;

int distance;

int readings[NUM_READINGS]; // Array to store distance readings

int index = 0; // Index to keep track of readings array

void setup() {

Serial.begin(9600);

pinMode(PING_PIN, INPUT);

// Initialize readings array with initial distance value

for (int i = 0; i < NUM_READINGS; i++) {

readings[i] = getDistance();

delay(50); // Delay to stabilize readings

}

}

void loop() {

// Read distance and apply moving average filter

distance = getMovingAverageDistance();

Serial.print("Distance: ");

Serial.print(distance);

Serial.println(" cm");

delay(1000); // Delay between readings

}

int getDistance() {

// Send a pulse to the PING))) sensor

pinMode(PING_PIN, OUTPUT);

digitalWrite(PING_PIN, LOW);

delayMicroseconds(2);

digitalWrite(PING_PIN, HIGH);

delayMicroseconds(5);

digitalWrite(PING_PIN, LOW);

// Read the duration of the pulse

pinMode(PING_PIN, INPUT);

duration = pulseIn(PING_PIN, HIGH);

// Calculate distance in centimeters

return duration / 29 / 2;

}

int getMovingAverageDistance() {

// Read new distance value

int newDistance = getDistance();

// Subtract oldest reading, add new reading and update readings array

distance -= readings[index];

distance += newDistance;

readings[index] = newDistance;

// Move to the next index

index = (index + 1) % NUM_READINGS;

// Calculate and return moving average

return distance / NUM_READINGS;

}

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.