Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
ABINAYA INBAMANI, BATCH
ANSWER
code--->
#include
#define WINDOW_SIZE 5
#define trigger 18
#define echo 19
int INDEX = 0;
//int VALUE = 0;
int SUM = 0;
int READINGS[WINDOW_SIZE];
int AVERAGED = 0;
LiquidCrystal lcd(2,3,4,5,6,7);
float time=0,distance=0,distance1=0;
void setup()
{
lcd.begin(16,2);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
lcd.print(" Ultra sonic");
lcd.setCursor(0,1);
lcd.print("Distance Meter");
delay(2000);
lcd.clear();
lcd.print(" Circuit Digest");
delay(2000);
}
void loop()
{
lcd.clear();
digitalWrite(trigger,LOW);
delayMicroseconds(2);
digitalWrite(trigger,HIGH);
delayMicroseconds(10);
digitalWrite(trigger,LOW);
delayMicroseconds(2);
time=pulseIn(echo,HIGH);
distance= time*0.0344 / 2;
SUM = SUM - READINGS[INDEX];
READINGS[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
AVERAGED = SUM / WINDOW_SIZE;
Serial.println(distance);
Serial.println(AVERAGED);
lcd.clear();
lcd.print("Dist.:");
lcd.print(AVERAGED);
lcd.print("cm");
lcd.setCursor(0,1);
lcd.print("Dist.:");
lcd.print(AVERAGED*0.394);
lcd.print("in");
delay(1000);
}