Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
CODE:
#include <LiquidCrystal.h>
// Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
LiquidCrystal lcd(10,9,5,4,3,2);
float in = 0;
float cm = 0;
float sum=0;
float value=0;
int index=0;
float reading[5]={0,0,0,0,0};
float avg=0;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
// Clears the LCD screen
lcd.clear();
}
long distance(int trigger, int echo)
{
pinMode(trigger, OUTPUT); // Clear the trigger
digitalWrite(trigger, LOW);
delayMicroseconds(10); // Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(trigger, HIGH);
delay(100);
digitalWrite(trigger, LOW);
pinMode(echo, INPUT); // Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echo, HIGH);
}
void loop()
{
cm =(0.0343/2.0) * distance(8, 8); //distance measurement using ulatrasonic sensor
in = (cm / 2.54); //conversion of units
sum = sum-reading[index]; // Remove the oldest entry from the sum
// Serial.print(sum);
value = in; // Read the next sensor value
reading[index] = value; // Add the newest reading to the window
sum = sum + value; // Add the newest reading to the sum
index = (index+1) % 5; //index increment
avg=sum/5.0;
Serial.println(avg);
/*Serial.print(cm);
Serial.print("cm, ");
Serial.print(avg);
Serial.println("in");*/
lcd.setCursor(0,0);
lcd.print("distance is:");
lcd.setCursor(0,1);
lcd.print(avg);
delay(100); // Wait for 100 millisecond(s)
}
