Challenge

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

onst int digPin = 6;

long dist,cm;

int index = 0;

  int value = 0;

  int sum = 0;

  int read[5];

  int average = 0;

  int buff=0;

void setup() {

  Serial.begin(9600);

}

void loop() {

  int n;

  pinMode(digPin, OUTPUT);

  digitalWrite(digPin, LOW);

  delay(200);

  digitalWrite(digPin, HIGH);

  delay(200);

  digitalWrite(digPin, LOW);

  pinMode(digPin, INPUT);

  dist = pulseIn(digPin, HIGH);

  cm=dist/58;

  Serial.print("Distance in cm:");

  Serial.println(cm); 

  sum = sum - read[index]; 

  buff=dist;

  read[index] = buff;           

  sum = sum + buff;                 

  index = (index+1) % 5;   

  average = sum / 5; 

  n=average/58;

  Serial.print("Distance after filter in cm:"); 

  Serial.println(n); 

  delay (100); 

}

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.