Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
code:
#include
LiquidCrystal lcd(8,7,9,10,11,12);
#define sample 5 //sample taken
#define pingPin 5//pin of sensor output
#define led 3
long chirp;//wave from sensor
int duration[sample];//storing sample value in arrary
volatile int i=0;
float inches,average;//inches = time to inche convert
//average =sum of sample/ number of sample
void setup()
{
lcd.begin(16,2);
Serial.begin(9600);//for printing on serial monitor
pinMode(led,OUTPUT);
}
void loop()
{
//it take 10 sample and took average of that sample
for (int k=0;k
pinMode(pingPin, OUTPUT);
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
// The sensor is triggered by a HIGH pulse of 5 or more microseconds.
//it only takes a small amount of time
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object
pinMode(pingPin, INPUT);
chirp = pulseIn(pingPin, HIGH);
//Calling function for calculating average
average=microsecondsToAverage(chirp);
}
//Call function for time to inche conversion
inches = microsecondsToInches(average);
if((130
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("ObjectIsFar OR");
lcd.setCursor(0,1);
lcd.print("ObjectIsNear");
digitalWrite(led,HIGH);
}
else
{
digitalWrite(led,LOW);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("DistanceOfObject");
lcd.setCursor(0,1);
lcd.print(inches);
lcd.print(" inches");
millis();
}
}
//function definition
float microsecondsToAverage(long chirp)
{
//storing the value of each sampe to ith element of array
duration[i]=chirp;
i++;
if(sample==i)//if collection of sample is done then calculating sum
{
Serial.print("Sample is \n");
for(int j=0;j
average += duration[j];
Serial.print(duration[j]);
Serial.print(",");
}
average= average/sample;
Serial.print("Average of the sample is = \n");
Serial.print(average);
Serial.print("\n");
i=0;//because start arrary again arr[0]
return average;//return the value average
}
}
//function definition
float microsecondsToInches(int average)
{
float timeToInch;
Serial.print(average);
timeToInch = ((average/2)*0.03434)/2.5;
//speed of sound is 343 meter per second at 20.C
// as given in data sheet to convert into cm multiply by 0.03434
//to convert cm to inche divide by 2.54 because 1 inch=2.54 cm
// This gives the distance travelled by the ping, outbound and return,
// so we divide by 2 to get the distance of the obstacle.
return timeToInch;
}
output:

