Challenge

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

Program:

#include <Adafruit_LiquidCrystal.h>

Adafruit_LiquidCrystal lcd(0);

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop()
{
  float sum = 0, avg = 0;

  // using Simple Moving Average smoothen the sensor data,
  // add the 5 consecutive and calculate average by dividing sum 
  for(int i = 0; i < 5; i++) {
    pinMode(4, OUTPUT);
    digitalWrite(4, LOW);
    delayMicroseconds(2);
    digitalWrite(4, HIGH);
    delayMicroseconds(5);
    digitalWrite(4, LOW);

    pinMode(4, INPUT);
    unsigned long pulseTimeinMs = pulseIn(4, HIGH);

    // pulse width is in micro seconds, to calculate distance travelled by sound in cm 
    // multiply 0.0343 (speed of sound is 343 m/s) 
    // and divide by 2 since the signal travelled from sensor TX and bounce back to sensor RX
    sum += pulseTimeinMs * 0.0343 / 2;
  }
  
  avg = sum / 5;

  lcd.setCursor(0,0);
  lcd.print("Disatnce in CM: ");
  lcd.setCursor(0,1);
  lcd.print(avg);
  Serial.println(avg);
}

Circuit:

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.