Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Project-2
ULTRASONIC SENSOR
Aim- The ultrasonic sensor uses a moving average filter to measure the distance of an object.
Circuit diagram-

Master code-
//Master
#include
#include
LiquidCrystal lcd(13,12,6,5,4,3); //pin connected to LCD
void setup()
{
lcd.begin(16,2);
Wire.begin();
}//setup
void loop()
{
Wire.requestFrom(9,1); //requesting data from 9 address
while(Wire.available()) //checking availability of data
{
float data=Wire.read(); //reading data available in bus
lcd.print("distance=");
lcd.print(data); //printing distance in inches
lcd.setCursor(0,1);
lcd.print(" inches");
delay(5000);
lcd.clear(); //clearing lcd screen
}
}
Slave code-
//slave
#include
uint8_t distance=0;
float time=0;
float y=0;
float t[4];
float x=0;
//Variaxble initialization
void setup()
{
Wire.begin(9);
// lcd.begin(16,2);
Serial.begin(9600);
Wire.onRequest(doit);//When master will requst the data it will call doit function
}
void loop()
{
}
void doit() //called function
{
for(int i=0;i<5;i++)
{
y=0;
x=ultrasonic_sensor(); //calling function
t[i]=x;
}//reading 5 data
for(int i=0;i<5;i++)
{
y=t[i]+y;
}//adding 5 data
/* sound velocity
v=340 m/sec
v=d/t
d=v*t;"t in sec"
d=340*t; "t in second,m=meter"
d=340*t*100; "t in second ,m=cm"
*/
y=y/(5); //microseconds
time=y/2; //divided by 2 due sound travel twice distace
time=time*0.000001; //time in second
//d=340*t*100
distance=time*340*39.3701; //tim in sec and distance in inches
Wire.write(distance);//sending data to master
Serial.println(distance);
}
int ultrasonic_sensor(void) //called function
{
pinMode(2,OUTPUT); //making pin 2 as output pin
digitalWrite(2,HIGH);
delayMicroseconds(2);
digitalWrite(2,LOW);
pinMode(2,INPUT); //making pin 2 as input pin
float t=pulseIn(2,HIGH); //reading time to get wave back to the sensor
pinMode(2,OUTPUT);
return t;
/* After triggering the ultrasonic sensor we are calculating the time
which will be taken by sound pulse to get reflected back and reach to the
sensor so here sound is travelling twice distance*/
}
Output-
distance-43.3 inches
distance-78.1 inches
(it may expire)