Challenge

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

1.sollution

code:

#define IN_PIN A0
#define WINDOW_SIZE 5
const int out=12;
const int in=13;
int INDEX = 0;
int VALUE = 0;
int SUM = 0;
int READINGS[WINDOW_SIZE];
int AVERAGED = 0;

void setup()
{
     pinMode(in, INPUT);
     pinMode(out, OUTPUT);
     pinMode(IN_PIN, INPUT);
     Serial.begin(9600);
}

void loop()
{
    long dur;
    long dis;
    long tocm;
    digitalWrite(out,LOW);
    delayMicroseconds(2);
    digitalWrite(out,HIGH);
    delayMicroseconds(10);
    digitalWrite(out,LOW);
    dur=pulseIn(in,HIGH);
    tocm=microsecondsToCentimeters(dur);
    Serial.println(String(tocm));
    delay(100);
    SUM = SUM - READINGS[INDEX]; // Remove the oldest entry from the sum
    VALUE = analogRead(IN_PIN); // Read the next sensor value
    READINGS[INDEX] = VALUE; // Add the newest reading to the window
    SUM = SUM + VALUE; // Add the newest reading to the sum
    INDEX = (INDEX+1) % WINDOW_SIZE; // Increment the index, and wrap to 0 if it exceeds the window size

     AVERAGED = SUM / WINDOW_SIZE; // Divide the sum of the window by the window size for the result

     Serial.print(VALUE);
     Serial.print(",");
    Serial.println(AVERAGED);
    delay(25);

}
long microsecondsToCentimeters(long microseconds)
{
    return microseconds / 29 / 2;
}

Circuit Diagram:

Output :

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.