Challenge

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

1)Measuring distance of an object using ultrasonic distance sensor (28015 Ping) and also smoothen the sensor data using moving average filter:

// C++ code
//
#define Window_Size 5
const int pingPin=7; 
int index=0;
int value=0;
int sum=0;
int readings[Window_Size];
int averaged = 0;

void setup() 
{
   Serial.begin(9600);
}

void loop() 
{
   long duration, inches, cm;
   pinMode(pingPin, OUTPUT);
   digitalWrite(pingPin, LOW);
   delayMicroseconds(2);
   digitalWrite(pingPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(pingPin, LOW);
   pinMode(pingPin, INPUT);
   duration = pulseIn(pingPin, HIGH);
   inches = microsecondsToInches(duration);
   cm = microsecondsToCentimeters(duration);
   Serial.print(inches);
   Serial.print("in, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println();
   delay(100);
   sum=sum-readings[index]; 
   value=cm;
   readings[index]=value; 
   sum=sum+value;
   index=(index+1)%Window_Size;
   averaged=sum/Window_Size;  
   Serial.print(averaged);
   Serial.print(",");
   delay(25);
}
long microsecondsToInches(long microseconds) 
{
   return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds) 
{
   return microseconds / 29 / 2;
}

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.