Challenge

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

// slave code
#include<Wire.h> //library file for I2C communication
int CM = 0;
int inch = 0;
int duration = 0; // variable decleration

void setup()
{

pinMode(12, OUTPUT); // configure digital pin 12 as an output
pinMode(11, INPUT); // configure digital pin 11 as an input
Wire.begin(1); // begin I2C communication
Wire.onRequest(requestEvent); // recevie the req from master

}

void loop()
{
}

void requestEvent() // isr function
{

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 for cm conversion
Wire.write(CM);//write the value in wire
inch = (CM / 2.54); //formula for inch conversion
Wire.write(inch);//write the value in wire

}

// master code
#include<Wire.h> //library file for I2C communication
#include<LiquidCrystal.h> //library file for lcd disply
LiquidCrystal lcd(12,11,5,4,3,2); // Define LCD pins

void setup()
{
lcd.begin(16,2); // initialize LCD dispaly
Wire.begin(); // begin I2C communication

}

void loop()
{

Wire.requestFrom(1,2); // request 2 byte from slave
byte CMReceive = Wire.read();// receive a byte from slave and store
lcd.setCursor(0,0); // set cursor at line one of lcd
lcd.print("Distance in CM");
lcd.setCursor(6,1); // set cursor at line two of lcd
lcd.print(CMReceive); // print data receive from slave
delay(2000); // Wait for 2000 millisecond(s)
lcd.clear();

byte INCHReceive = Wire.read();// receive a byte from slave and store
lcd.setCursor(0,0); // set cursor at line one of lcd
lcd.print("Distance in INCH");
lcd.setCursor(5,1); // set cursor at line one of lcd
lcd.print(INCHReceive); // print data receive from slave
delay(3000); // Wait for 3000 millisecond(s)
lcd.clear();

}

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.