Challenge

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

#define IN_PIN A0

#define WINDOW_SIZE 5


int triggerPin = 7 ;


int echoPin = 4;
signed long duration;
int distance;
int INDEX = 0;
int VALUE = 0;
int SUM = 0;
int READINGS[WINDOW_SIZE];
int AVERAGED = 0;
void setup()
{
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(IN_PIN, INPUT);
Serial.begin(9600);

}

void loop()
{
SUM = SUM - READINGS[INDEX];
VALUE = analogRead(IN_PIN);
READINGS[INDEX] = VALUE;
SUM = SUM + VALUE;
INDEX = (INDEX+1) % WINDOW_SIZE;
AVERAGED = SUM / WINDOW_SIZE;
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = 0.01723 * duration;
Serial.println(distance);
Serial.print(VALUE);
Serial.print(",");
Serial.println(AVERAGED);
delay(20);

}

// output and stimulation attached below

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.