Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Offline embedded Batch-2
Master code
#include<LiquidCrystal.h> // header file for LCD display
LiquidCrystal lcd(10,11,2,3,4,5); // pins connected to LCD from Arduino UNO
#include<Wire.h> // header file for I2C communication
void setup()
{
lcd.begin(16,2); // Initialiasing the LCD
lcd.setCursor(0,0); // cursor set at 0th column and 0th row
lcd.print("MASTER");
lcd.setCursor(0,1); // // cursor set at 0th column and 1st row
lcd.print("data from Slave");
delay(1000); // delay of 1000 milliseconds
lcd.clear(); // clearing the content in LCD
Wire.begin(); // beginning the serail communication
}
void loop()
{
Wire.requestFrom(1,2);// request from slave to receive the data
byte a=Wire.read(); // reading the data from slave
lcd.begin(16,2); // beginning the LCD for printing data received from slave
lcd.setCursor(0,0);
lcd.print("Distance");
delay(1000); // delay of 1000 milliseconds
lcd.setCursor(0,1);
lcd.print(a); // printing the distance in centimeters
lcd.print("cm");
delay(1000);// delay of 1000 milliseconds
lcd.clear(); // clearing the content in LCD
byte b=Wire.read();// reading the data from slave
lcd.begin(16,2);// beginning the LCD for printing data received from slave
lcd.setCursor(0,0);
lcd.print("Distance");
delay(1000);// delay of 1000 milliseconds
lcd.setCursor(0,1);
lcd.print(b);// printing the distance in inches
lcd.print("inches");
delay(1000);// delay of 1000 milliseconds
lcd.clear(); // clearing the content in LCD
}
slave code
#include<Wire.h> // header file for I2C communication
int CM=0; // declaring variable globally
long duration=0;
void setup()
{
pinMode(10, OUTPUT); // configuring pin as output
pinMode(11,INPUT); // configuring pin as input
Wire.begin(1);// begining serail communication
Wire.onRequest(requestevent); // function call for sending data
}
void loop(void)
{
}
void requestevent()
{
digitalWrite(10,LOW); // making the sensor low
delayMicroseconds(2); //delay of 2 microseconds
digitalWrite(10,HIGH);// making sensor to measure send the pulse
delayMicroseconds(10); // delay of 10 microseconds
digitalWrite(10,LOW); // making the sensor low
duration=pulseIn(11,HIGH); // reading data from the sensor using pulseIn keyword
CM=0.01723*duration; // converting data to centimeter
Wire.write(CM); // sending data to master
int inches=(CM/2.54); // converting centimeter to inches
Wire.write(inches);// sending data to master
}