Challenge

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

//MASTER
#include // Header to use LCD functions
#include // Header to use I2C communication
Adafruit_LiquidCrystal lcd(32);
int distance;
void setup()
{
Serial.begin(9600);
Wire.begin(); //To begin I2C communication
lcd.begin(16,2); //To begin LCD display
lcd.clear();
}

void loop()
{
Wire.beginTransmission(8);
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:");
lcd.print(distance); //To print the received message from slave 1
lcd.print(" inch"); //To display in LCD
delay(50); //delay
Wire.end(); //To end the I2C transmission
}

//Slave
#include // Header to use I2C communication
long movingAvg(long );
const int sig = 2; //Assigning pin7 as sig for readabilty
long duration, distance,inches, cm; //Declaring as integer type
static int avg; //Declaring avg as static int type
void setup()
{
Serial.begin(9600);
//Calling function from master
}

void loop()
{
Wire.begin(8); //To begin I2C communication with address 8
Wire.onRequest(requestEvent);
delay(100);
}

void requestEvent() //Called function
{
int numReads =20;
int sum =0;
pinMode(sig, OUTPUT); //Declaring pin2 as output
digitalWrite(sig, LOW); //Sensor is triggered by pin2 with delay
delayMicroseconds(2);
digitalWrite(sig, HIGH);
delayMicroseconds(5);
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

for(int k=0; k< numReads; k++){
sum += inches;
Serial.println(k);
Serial.println(inches);
delay (1);
}
int distance = sum / numReads;
Wire.write(distance); //Return value to master

}

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.