Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
//MASTER
#include<LiquidCrystal.h>
#include<Wire.h>
LiquidCrystal lcd(2,3,4,5,6,7);
int distance;
void setup()
{
Serial.begin(9600);
Wire.begin();
//To begin the I2C Commuinication
lcd.begin(16,2);
//To begin the LCD Display
lcd.clear();
}
void loop()
{
Wire.requestFrom(8,4);
distance=Wire.read();
lcd.setCursor(0,0);
lcd.print(distance);
lcd.print(" inches");
//To display the LCD
delay(50);
Wire.end();
}
//for slave
#include<Wire.h>
int sig = 2;
//pin2 is assigned to send and receive data.
int duration, inches, cm;
static int avg;
void setup()
{
Serial.begin(9600);
Wire.begin(8);
//To begin the I2C Commuinication with address 8
Wire.onRequest(distance);
}
void loop()
{
delay(100);
}
void distance()
{
pinMode(sig, OUTPUT);
//Declaring the pin2 as the output
digitalWrite(sig, LOW);
//Triggering sensor.
delay(5);
digitalWrite(sig, HIGH);
delay(10);
digitalWrite(sig, LOW);
pinMode(sig, INPUT);
duration = pulseIn(sig, HIGH);
inches = (duration/74)/2;
Wire.write(inches);
delay(10);
}