Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Overview of the Project:
In this project the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (28015 Ping) and also smoothen the sensor data using moving average filter”.
Goals:
- Measuring the distance in terms of inches of an object using Ultrasonic Distance Sensor (28015 Ping).
- The sensor data is smoothened by using Moving average filter technique to eliminate the high frequency variations from the sensor data.
//master
#include <Wire.h> // Header to use I2C communication
#include <LiquidCrystal.h> //Header to use LCD functions
LiquidCrystal lcd(11, 12, 2 ,3, 4, 5); //pins connected to LCD
void setup()
{
Wire.begin(); //To begin I2C communication
lcd.begin(16,2); //To begin LCD display
Serial.begin(9600);
}
void loop()
{
Wire.requestFrom(8,1); // 8 is address 1 byte
byte inches=Wire.read(); //To print character by character
lcd.setCursor(0, 0);
lcd.print(inches);//to print inches in LCD
lcd.print(" inches");
lcd.setCursor(0, 1);
}
//slave
#include <Wire.h> //Header to use I2C communication
// this constant won't change. It's the pin number of the sensor's output:
const int pingPin = 7;
long duration[5], inches,i; //Declaring as integer type
static int avg;
void setup() {
Wire.begin(8);
// initialize serial communication:
Serial.begin(9600);
Wire.onRequest(distance);//Goes to the "void distance" code and begin the request
}
void loop() {
delay(100);
}
void distance() //Called function
{
for(i=0;i<5;i++)
{
pinMode(pingPin, OUTPUT); //Declaring pin2 as output
digitalWrite(pingPin, LOW);//Sensor is triggered by pin2 with delay
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);//Declaring pin2 as input
duration[i] = pulseIn(pingPin, HIGH);//To read the pulse
}
//moving avarage filter
avg=(duration[0]+duration[1]+duration[2]+duration[3]+duration[4])/5;
inches = (avg/74)/2;// convert the time into a distance
Serial.print(inches);
Serial.print(" inches");
Serial.println();
//Inside the wire.write is the data to be sent to the master upon request
Wire.write(inches);
delay(1000);
}
