Challenge

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

AIM:-Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter.

  • CODE:-
  • MATSER CODE:-

#include //To use LCD functions
#include //To use I2C communication
LiquidCrystal lcd(2,7,8,9,10,11); //initializing data pins
int distance;//variable to print the data from slave
void setup()
{

Wire.begin();//To begin I2C communication
lcd.begin(16,2);//To begin LCD display
lcd.clear(); //To clear LCD
}
void loop()
{
Wire.requestFrom(1,1);// address 1 and request 1 byte
distance=Wire.read(); //store data in variable
lcd.setCursor(0,0);//Move cursor to the first line
lcd.print(distance);//To print the received message from slave 1
lcd.print(" inches");
delay(50);
Wire.end();//End the transmission
}

 

  • SLAVE CODE:-

#include//To use I2C communication
int sig = 3;//Ultrasonic Sig pin
int duration, inches;//Variables used for calculation

void setup()
{
Wire.begin(1);//To begin I2C communication with address 8
Wire.onRequest(distance);//Call 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
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 in inches
Wire.write(inches);//Return value to master
delay(10);
}

  • RESULT:-

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.