Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

// master code
#include//i2c communication hedder file
#include//lcd disply headder file
LiquidCrystal lcd(12,11,5,4,3,2);

void setup()
{

lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("ALWAYS BE HAPPY");
delay(10000);
lcd.clear();
Wire.begin(); //enable the communication

}

void loop()
{

Wire.requestFrom(1,2); //address of slave and qty of bytes
byte CMReceive = Wire.read();//receive the req from slave
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Distance in CM");
lcd.setCursor(6,1);
lcd.print(CMReceive);
delay(2000);
lcd.clear();
byte INCHReceive = Wire.read();//receive the req from slave
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Distance in INCH");
lcd.setCursor(5,1);
lcd.print(INCHReceive);
delay(3000);
lcd.clear();

}

slave
#include // headder file for i2c communication
int CM = 0;
int inch = 0;
int duration = 0; // variable decleration

void setup()
{

pinMode(12, OUTPUT); // pin mode decleration
pinMode(11, INPUT);
Wire.begin(1); // communication begin
Wire.onRequest(requestEvent); // recevie the req from master

}

void loop()
{
}

void requestEvent() // isr fun
{

digitalWrite(12, LOW);
delayMicroseconds(2);
digitalWrite(12, HIGH);
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

}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.