Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Measuring the distance of an object using an ultrasonic sensor and also smoothening the sensor data using a moving average filter
Code:
Master Code
#include// we are getting the I2C protocol
const int pin =7;//seting pin 7 as signal pin
long sum =0;//declaring all the global variable
long avg;
byte send;
void setup()
{
Serial.begin(9600);
Serial.begin(9600);//baud rate for transmission
Wire.begin();//begin communication for i2c in a4 and a5
}
void loop()
{
//Wire.requestFrom(8,1);
long time ,inch ,cm;
long result;
pinMode(pin,OUTPUT);//makeing pin 7 as output
digitalWrite(pin,LOW);//making low for some time
delayMicroseconds(2);
digitalWrite(pin,HIGH);//making that pin has high
delayMicroseconds(2);
digitalWrite(pin,LOW);//making it has low
pinMode(pin,INPUT);
time=pulseIn(pin,HIGH);//getting the retrun wave noted in the time
result=conversion(time);//calling the function
cm=(result/2)/29.1;//value from function part are calculated for the CM
inch=(result/2)/74;//value from function part are calculated for the Inches
Serial.println("inch");
Serial.println(inch);
//Serial.println("inch");
// Serial.println(inch);
// Serial.println("cm");
// Serial.println(cm);
Wire.beginTransmission(8);
Wire.write(inch);//Transmitting the value to slave
Wire.endTransmission();
delay(500);
}
long conversion( long time)
{
int a[5];//intializing the variable
int n;
int av=0;
while(n<=5)
{
a[n] = time;//storing the value in array upto window size as 5
n++;
}
for(int i=0;i<5;i++)
{
av=av+a[i];
}
av=av/5;//geeting the average value
return av;//returning that value
}
Slave Code:
#include//getting the I2C library file
#include//getting the lcd library file
LiquidCrystal lcd(2,7,8,9,10,11);//(RS,EN,8,9,10,11)
byte slaveValue =0;//intiallizing the global value
void setup()
{
lcd.begin(16,2);
Serial.begin(9600);
Wire.begin(8);//Transmission begins command
Wire.onReceive(receiveEvent);//intruppt for receiving the data
}
void loop()
{
//lcd.setCursor(0,1);
// lcd.print("Slave Received");
}
void receiveEvent(int howMany)
{
slaveValue = Wire.read();//reading data from the Master
lcd.setCursor(0,0);//positioning the cursor
lcd.print("Slave Received");//printing the value in the lcd
lcd.setCursor(0,1);
lcd.print(slaveValue);//printing the master value in LCD
Serial.println("slave");
Serial.println(slaveValue);
delay(1000);
}
Output:

Link: