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,6,5,4,3);

void setup()
{
  lcd.begin(16,2);
  lcd.setCursor(5,0);
  lcd.print("Master");
  delay(1000);
  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(7,1);
  lcd.print(CMReceive);
  delay(1000);
  lcd.clear();
  
 
 //int inch=(CM/2.54);
  byte INCHReceive = Wire.read();//receive the req from slave
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print(" Distance in INCH");
  lcd.setCursor(7,1);
  lcd.print(INCHReceive);
  delay(1000);
  lcd.clear();
  
}


// slave code
#include // headder file for i2c communication
int CM=0,inch=0,duration=0; // variable decleration
void setup()
{
  Serial.begin(9600); // serial monitor begin
 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
  Serial.println("inch = ");
  Serial.println(inch);
  Serial.println("CM = ");
  Serial.println(CM);
}
 
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.