Challenge

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

Objective -

To implement code for “Measuring distance of an object using ultrasonic distance sensor (28015 Ping) and also smoothen the sensor data using moving average filter”.

Model -

Code -

#include <LiquidCrystal.h>

// Define LCD module Pins(RS,EN,D4,D5,D6,D7)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// Variable declaration
float inches = 0;
float cm = 0;
float sum = 0;
float avg = 0;

// Function for Ultrasonic sensor
long readUltrasonicDistance(int triggerPin, int echoPin)
{
  // Clear the trigger
  pinMode(triggerPin, OUTPUT);
  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()
{
  // Begins Serial Communiacation at 9600 baud rate
  Serial.begin(9600);
  // Initialize LCD display
  lcd.begin(16,2);
  // Set Cursor at first line of display
  lcd.setCursor(0,0);
  // Prints Distance measured in LCD 
  lcd.print("Distance measured");
  // Set Cursor at second line of display
  lcd.setCursor(0,1);
  // Prints by Ultrasonic in LCD 
  lcd.print("by Ultrasonic");
  // Delay of 2 seconds
  delay(2000);
  // Clear lcd display
  lcd.clear();
}

void loop()
{
  // For loop of Smoothening average filter
  for(int i=0;i<5;i++)
  {    
    // Measure the ping time in cm
    cm = 0.01723 * readUltrasonicDistance(7, 7);
    // Convert to inches by dividing by 2.54
    inches = (cm / 2.54);
    
    // Total of 5 values
    sum = sum + inches;
    // Average of 5 values
    avg = sum/5;
  }
  
  // Reset sum value to 0; 
  sum = 0;
  
  // Set Cursor at first line of display
  lcd.setCursor(0,0);
  // Prints Inches in LCD 
  lcd.print("Inches: ");
  // Prints inches value in LCD 
  lcd.print(avg);
  // Set Cursor at second line of display
  lcd.setCursor(0,1);
  // Prints Centimeter in LCD 
  lcd.print("cm: ");
  // Prints cm value in LCD 
  lcd.print(cm);
  
  // Prints in Serial Monitor
  Serial.print(avg);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.println("cm");
  // Delay of 100ms
  delay(100);  
}

Output -

TinkerCAD Model Link -> https://www.tinkercad.com/things/elmUDy3NqC9-copy-of-ultrasonic-distance-measurement/editel?sharecode=kHhSgvPtOnrCazH7hq-1MACT3Ym1ZDVM2nbImLWecZo

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.