Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
#include<LiquidCrystal.h> // Header to use LCD functions
#include<Wire.h> // Header to use I2C communication
LiquidCrystal lcd(12,11,6,5,4,3); //pins connected to LCD
int distance; //variable to print the data from slave
void setup()
{
lcd.begin(16,2);
lcd.setCursor(5,0);
lcd.print("Master");
delay(2000);
lcd.clear();
lcd.setCursor(3,0);
lcd.print("sachin");
delay(2000);
lcd.clear();
Wire.begin(); //enable the communication
}
void loop()
{
Wire.requestFrom(8,4); //address of slave and qty of bytes
distance=Wire.read(); //To print character by character
lcd.setCursor(0,0);
lcd.print(" Dist in inch");
lcd.setCursor(3,1); //To move the cursor to the second line
lcd.print(distance); //To print the received message from slave 1
lcd.print(" inches"); //To display in LCD
delay(1000); //delay
Wire.end();
}
//Slave
#include<Wire.h> // Header to use I2C communication
int ping = 2; //Assigning pin2 as sig for readabilty
int duration, inches, cm; //Declaring as integer type
static int avg; //Declaring avg as static int type
void setup()
{
Serial.begin(9600);
Wire.begin(8); //To begin I2C communication with address 8
Wire.onRequest(distance); //Calling function from master
}
void loop()
{
}
void distance() //Called function
{
pinMode(ping, OUTPUT); //Declaring pin2 as output
digitalWrite(ping, LOW); //Sensor is triggered by pin2 with delay
digitalWrite(ping, HIGH);
digitalWrite(ping, LOW);
pinMode(ping, INPUT); //Declaring pin2 as input
duration = pulseIn(ping, HIGH); //To read the pulse
cm=0.01723*duration;// formula to convert the cm
Wire.write(cm);//write the value in wire
inches=(duration/74)/2; //formula for inch conversion
Wire.write(inches); //write the value in wire
Serial.println("inches = ");
Serial.println(inches);
Serial.println("cm = ");
Serial.println(cm);
}