Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
I have attached the output along with the output link below with the code:
https://www.tinkercad.com/things/aCzO1dTXVRj?sharecode=xBXizJ10XrrPfobfbNwajW80XhupR03anPDpjCHqzk8
code:
#include <LiquidCrystal.h>
#define WINDOW_SIZE 5
// defines pins numbers
const int trigPin = 10;
const int echoPin = 9;
// defines variables
long duration;
float distance;
//moving average varaibles
int index = 0;
float sum = 0;
float read[WINDOW_SIZE];
float average = 0;
//Define the lcd pin for display
LiquidCrystal lcd_1(7, 6, 5, 4, 3, 2);
void setup()
{
lcd_1.begin(16, 2); // Set up the number of columns and rows on the LCD.
lcd_1.print("Project- 2!"); // Print a message to the LCD.
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop()
{
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
sum = sum - read[index]; // Remove the oldest entry from the sum
read[index] = distance; // Add the newest reading to the window
sum = sum + distance; // Add the newest reading to the sum
index = (index+1) % WINDOW_SIZE; // Increment the index, and wrap to 0 if it exceeds the window size
average = sum / WINDOW_SIZE; // Divide the sum of the window by the window size for the result
// Prints the distance on the lcd
lcd_1.setCursor(0, 1); //Setting the cursor to second row
lcd_1.print("Dist:");
lcd_1.print(average);
lcd_1.print("cm");
delay(100); //update delay for 100 milli second
}