Challenge

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

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <avr/io.h>
#include <util/delay.h>

#define TRIGGER_PIN 11
#define ECHO_PIN 10

int main(void)
{

DDRB |= (1 << TRIGGER_PIN);
PORTB &= ~(1 << TRIGGER_PIN);

DDRB &= ~(1 << ECHO_PIN);
PORTB &= ~(1 << ECHO_PIN);

uint16_t distance;
uint8_t i;
float distance_array[10];
float total_distance;
float average_distance;

while (1)
{

PORTB |= (1 << TRIGGER_PIN);
_delay_us(10);
PORTB &= ~(1 << TRIGGER_PIN);


while (!(PINB & (1 << ECHO_PIN)));
uint16_t startTime = TCNT1;
while (PINB & (1 << ECHO_PIN));
uint16_t travelTime = TCNT1 - startTime;


distance = travelTime / 58;


distance_array[i] = distance;
total_distance = 0;
for (int j = 0; j < 10; j++)
{
total_distance += distance_array[j];
}
average_distance = total_distance / 10;
i = (i + 1) % 10;
}

return 0;
}

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.