Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
//MASTER
#include<Wire.h>// 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);//
delayMicroseconds(2);
digitalWrite(pin,LOW);//making it has low
pinMode(pin,INPUT);
time=pulseIn(pin,HIGH);//
result=conversion(time);//
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);//
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
}
#include<Wire.h>//getting the I2C library file
#include<LiquidCrystal.h>//
LiquidCrystal lcd(2,7,8,9,10,11);//(RS,EN,8,
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);/
}
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);//
lcd.print("Slave Received");//printing the value in the lcd
lcd.setCursor(0,1);
lcd.print(slaveValue);//
Serial.println("slave");
Serial.println(slaveValue);
delay(1000);
}