Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
mastercode
#include<Wire.h> // Header to use I2C communication
int sig = 3; //Assigning pin3 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()
{
delay(100);
}
void distance() //Called function
{
pinMode(sig, OUTPUT); //Declaring pin2 as output
digitalWrite(sig, LOW); //Sensor is triggered by pin2 with delay
delay(5);
digitalWrite(sig, HIGH);
delay(10);
digitalWrite(sig, LOW);
pinMode(sig, INPUT); //Declaring pin2 as input
duration = pulseIn(sig, HIGH); //To read the pulse
inches = (duration/74)/2; //converting time into a distance
Wire.write(inches); //Return value to master
delay(10);
}
slave code
#include <LiquidCrystal.h>
#include<Wire.h> // Header to use I2C communication
int seconds = 0;
int distance;
LiquidCrystal lcd_1(12, 11, 5, 4, 3, 2);
void setup()
{
Serial.begin(9600);
Wire.begin(); //To begin I2C communication
//To begin LCD display
lcd_1.begin(16, 2); // Set up the number of columns and rows on the LCD.
lcd_1.clear();
// Print a message to the LCD.
}
void loop()
{
Wire.requestFrom(8,4); // 8 is address 4 byte
distance=Wire.read(); //To print character by character
lcd_1.setCursor(0,0); //To move the cursor to the first line
lcd_1.print(distance); //To print the received message from slave 1
lcd_1.print(" inches"); //To display in LCD
delay(50); //delay
Wire.end(); //To end the I2C transmission
}