Challenge

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

CODE:

int sample_size = 20;
float inches = 0.0;
float cm = 0.0;
float cm_act = 0.0;
float arr[20]={0.0};

long readUltrasonicDistance(int triggerPin, int echoPin)
{
  pinMode(triggerPin, OUTPUT);  // Clear the trigger
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);
  // Sets the trigger pin to HIGH state for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);
  // Reads the echo pin, and returns the sound wave travel time in microseconds
  return pulseIn(echoPin, HIGH);
}

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

}

void loop()
{
  // measure the ping time in cm
  //  
  cm_act = 0.01744 *readUltrasonicDistance(7, 7);
  //Serial.println(cm_act);
  // convert to inches by dividing by 2.54
  cm = moving_avg(cm_act);
  inches = (cm / 2.54);
  
  Serial.print(inches);
  Serial.print("inches,  ");
  Serial.print(cm);
  Serial.println("cm"); 
}

float moving_avg(float newNum)
{
  int i;
  float Sum=0;
  for(i=0;i<sample_size-1;i++)
  {
    arr[i] = arr[i+1];
  }
  arr[sample_size-1] = newNum;
  for(i=0;i<sample_size;i++)
  {
    Sum = Sum+arr[i];
    }
  return Sum/sample_size;
}

OUTPUT:

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.

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.