Challenge

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

/* Measuring the distance of an object using ultrasonic sensor */

//MASTER
#include // Header to use LCD functions
#include // Header to use I2C communication
LiquidCrystal lcd(2,3,4,5,6,7); //pins connected to LCD
int distance; //variable to print the data from slave

void setup()
{
Serial.begin(9600);
Wire.begin(); //To begin I2C communication
lcd.begin(16,2); //To begin LCD display
lcd.clear();
}

void loop()
{
Wire.requestFrom(8,4); // 8 is address 4 byte
distance=Wire.read(); //To print character by character
lcd.setCursor(0,0); //To move the cursor to the first line
lcd.print(distance); //To print the received message from slave 1
lcd.print(" inches"); //To display in LCD
delay(50); //delay
Wire.end(); //To end the I2C transmission
}


// SLAVE CODE
#include // Header to use I2C communication

int trigPin = 11; // Trigger
int echoPin = 12; // Echo
long duration, cm, inches; //Declare the Variables
long sum=0;
long avg;
int i;

void setup()
{
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
Wire.begin(8); //To begin I2C communication with address 8
Wire.onRequest(distance); //Calling function from master
}

void loop()
{

delay(50); //Delay for 5sec
}

void distance() //Called function
{
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance

cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
inches = (duration/74)/2; //converting time into a distance or 0.0135
Wire.write(inches); //Return value to master
delay(10);
for (i=0; i<5; i++)
{
sum=sum+inches;
avg = sum/5; //Find the Average
}



Serial.print(avg);
Serial.print("Avg, "); //Print the Average Value in Serial Monitor
Serial.print(cm);
Serial.print("cm"); //Print the Distance in centimeter to Serial Monitor
Serial.println();
//Return value to master
delay(10);
}

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.