Challenge

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

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

#define windowsize 5 //window size of moving average filter is defined as 5
#define pingpin 7 //ultrasonic sensor signal pin in 7
long duration; //duration of type long

float inches,cm; //inches,cm are of type float


int index=0; //used for indexing the array readings,initially in 0

long sum=0;//to sum the duration readings
long readings[windowsize];//each duration readings are stored in the array upto the windowsize
long averaged=0;//the sum value is averaged to get noisefree readings,initially in 0

void setup()
{
Serial.begin(9600);//starts serial monitor to view distance value
}
void loop()
{
pinMode(pingpin,OUTPUT);//signalpin of ultrasonic sensor can act as trigger and echo so first it is set as trig, in output mode
digitalWrite(pingpin,LOW);//writes the signal in LOW mode for 2 microseconds
delayMicroseconds(2);
digitalWrite(pingpin,HIGH);//sets the signal pin in HIGH,to trigger for 10 microseconds
delayMicroseconds(10);
digitalWrite(pingpin,LOW);//after that signal pin is set to LOW

pinMode(pingpin,INPUT);//signal pin is set as input ,in echo mode


/* Moving average filter */
sum=sum-readings[index];//remove the oldest entry from the sum
duration=pulseIn(pingpin,HIGH);//reads the duration of pulse
readings[index]=duration;//add the newest duration readings to the window
sum+=duration;//add the newest duration readings to the sum
index=(index+1)%windowsize;//increment the index and return to 0 if it exceeds the window size

averaged=sum/windowsize; //sum is divided by window size to get averaged value

cm=averaged*0.034/2;//to get distance measured in cm
inches=averaged*0.0133/2;//to get distance in inches
Serial.print("distance in cm ");//displays cm readings in serial monitor
Serial.println(cm);
Serial.print("distance in inches ");//displays inches readings in serial monitor
Serial.println(inches);
}

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.