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>//header file for i2c communication
#include<LiquidCrystal.h>//header for lcd
LiquidCrystal lcd(11,10,6,5,4,3);//arduino pins connected to lcd
void setup()
{
lcd.begin(16,2);//begin the lcd
lcd.setCursor(5,0);//set the cursor in lcd
lcd.print("Master");//print master in lcd
delay(1000);//delay 1 sec
lcd.clear();//clear the lcd display
Wire.begin(); //enable i2c the communication
}
void loop()
{
Wire.requestFrom(1,2); //request one byte from slave
byte CM= Wire.read();//store the received byte in CM
lcd.setCursor(0,0);//set the cursor in lcd
lcd.print(" Distance in CM");//print in lcd
lcd.setCursor(7,1);
lcd.print(CM);//print the cm value in lcd
delay(3000);//3 sec delay
lcd.clear();//clear the lcd
byte INCH = Wire.read();//store the received byte in INCH
//lcd.begin(16,2);
lcd.setCursor(0,0);//set the cursor in lcd
lcd.print(" Distance in INCH");
lcd.setCursor(7,1);
lcd.print(INCH);
delay(3000);
lcd.clear();
}
//slave
#include<Wire.h>//header for i2c communication
int CM=0,inch=0,duration=0;//assign the variable for store values
void setup()
{
Serial.begin(9600); // serial monitor begin
pinMode(12,OUTPUT); //set the pin as output
pinMode(11,INPUT);//set the pin as input
Wire.begin(1); //begin i2c communication
Wire.onRequest(requestEvent); //function call when master request value from slave
}
void loop()
{
}
void requestEvent()
{
digitalWrite(12,LOW);//set the trigger pin as low
delayMicroseconds(2);//delay 2 mic sec
digitalWrite(12,HIGH);//set trigger pin as high for send wave
delayMicroseconds(2);
digitalWrite(12,LOW);
duration=pulseIn(11,HIGH); // it will find the duration of ultrosonic wave
CM=0.01723*duration;// formula to convert the cm
Wire.write(CM);//write the value in wire
inch=(CM/2.54); //formula for inch conversion
Wire.write(inch);//write the value in wire
Serial.println("inch = ");//print in serial monitor
Serial.println(inch);
Serial.println("CM = ");
Serial.println(CM);
}