Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
//pro_2
#define WINDOW_SIZE 3 //filter window
int inches = 0;
int cm = 0;
int sum =0;
int Avg = 0;
int Read;
int value=0;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW); //truning on and off the sensor to capture data
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
cm = 0.01723 * readUltrasonicDistance(7, 7);
sum = sum - Read;
value= digitalRead(7);
sum =cm + value;
Avg = sum/WINDOW_SIZE; //avarage fillterig method
Serial.print(Avg);
Serial.println("cm."); //printing in cm
inches = (Avg / 2.54);
Serial.print(inches);
Serial.print("in, "); //printing in inches
delay(100);
}