Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
#include<LiquidCrystal.h>
LiquidCrystal lcd(2,3,4,5,6,7);
int inches = 0;
#define SAMPLESIZE 10 // Filter Size Or Window Size
const int UL_PIN = 8;
int INDEX = 0;
int VALUE = 0;
int SUM = 0;
int avg[SAMPLESIZE];
int AVERAGE = 0;
int cm = 0;
void setup()
{
lcd.begin(16,2); //Initilize LCD display
lcd.setCursor(0,0); //Sets Cursor at first line of Display
lcd.print("UL Distance"); //Prints in LCD
lcd.setCursor(0,1); //Sets Cursor at second line of Display
lcd.print("VALUES"); //Prints in LCD
delay(5000); //Delay for 5 seconds
lcd.clear(); //Clears LCD display
Serial.begin(9600); //Begins Serial Communication at 9600 baud rate
//pinMode(UL_PIN, INPUT); //ultrasonic sensor as input pin
}
void loop()
{
pinMode(UL_PIN, OUTPUT);
digitalWrite(UL_PIN, LOW);
delayMicroseconds(2);
digitalWrite(UL_PIN, HIGH);
delayMicroseconds(5);
digitalWrite(UL_PIN, LOW);
//Moving average algorithm
SUM = SUM - avg[INDEX]; // subtract previous values
VALUE = analogRead(UL_PIN);// Read from ultrasonic sensor
SUM = SUM+VALUE;
INDEX = (INDEX+1)%SAMPLESIZE;//Increment the index and wrap it to zero if sample size is exceeded
AVERAGE = SUM / SAMPLESIZE; //Moving average formula
Serial.print(VALUE);
lcd.print(VALUE);
Serial.print(",");
lcd.print(",");
Serial.println(AVERAGE);
lcd.println(AVERAGE);
delay(5);
}