Challenge

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

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

#include <avr/io.h>

#include <util/delay.h>

#include <stdio.h>

#define TRIG_PIN PD2 // Digital pin for the ultrasonic sensor's trigger pin

#define ECHO_PIN PD3 // Digital pin for the ultrasonic sensor's echo pin

#define NUM_READINGS 10 // Number of readings for the moving average filter

unsigned long totalDistance = 0;

unsigned long averageDistance = 0;

unsigned long readings[NUM_READINGS];

int currentReading = 0;

void setup() {

DDRD |= (1 << TRIG_PIN); // Set TRIG_PIN as output

DDRD &= ~(1 << ECHO_PIN); // Set ECHO_PIN as input

Serial.begin(9600);

}

void loop() {

// Trigger the ultrasonic sensor

PORTD &= ~(1 << TRIG_PIN);

_delay_us(2);

PORTD |= (1 << TRIG_PIN);

_delay_us(10);

PORTD &= ~(1 << TRIG_PIN);

// Measure the duration of the echo pulse

unsigned long duration = pulseIn(ECHO_PIN, HIGH);

// Calculate the distance in centimeters

unsigned long distance = duration / 58;

// Apply the moving average filter

totalDistance = totalDistance - readings[currentReading];

readings[currentReading] = distance;

totalDistance = totalDistance + readings[currentReading];

currentReading = (currentReading + 1) % NUM_READINGS;

averageDistance = totalDistance / NUM_READINGS;

// Print the smoothened distance

printf("Distance: %lu cm\n", averageDistance);

_delay_ms(100); // Adjust the delay as needed

}

Output:

Distance: 23 cm

Distance: 22 cm

Distance: 24 cm

Distance: 23 cm

...

Description:

Each line represents a distance reading in centimeters. The values will vary depending on the actual distance measured by the ultrasonic sensor and the efficiency of the moving average filter in smoothening the data.

Please note that you need to open the Serial Monitor in your development environment (e.g., Arduino IDE) and set the baud rate to 9600 to view the output.

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.