Challenge

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

1)answer

#define SAMPLESIZE 10 //Window Size
const int UL_PIN = 8;

int INDEX = 0;//By using index, we access array element
int VALUE = 0;// initializing value
int SUM = 0;// initializing sum
int avg[SAMPLESIZE];//array of sensor data readings and average them.
int AVERAGE = 0;
int cm = 0;
int inches = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
pinMode(UL_PIN, OUTPUT);
digitalWrite(UL_PIN, LOW);
delayMicroseconds(3);
digitalWrite(UL_PIN, HIGH);
delayMicroseconds(5);
digitalWrite(UL_PIN, LOW);
pinMode(UL_PIN, INPUT);
//Moving average algorithm
VALUE = analogRead(UL_PIN)*0.01723;// Reading from ultrasonic sensor
SUM = SUM+VALUE;
INDEX = ++INDEX % SAMPLESIZE;//Increment the index 1 and wrap it to zero if sample size is exceeded
SUM = SUM - avg[INDEX]; // subtract previous values
AVERAGE = SUM / SAMPLESIZE; //moving average formula
Serial.print(VALUE);
Serial.print(",");
Serial.println(AVERAGE);
delay(10);
}

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.