Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Code:
//Slave
#include
int sig = 2; //Assigning pin2 as sig for readabilty
int duration, inches, cm;
static int avg;
void setup()
{
Serial.begin(9600);
Wire.begin(8);
Wire.onRequest(distance);
}
void loop()
{
delay(50);
}
void distance()
{
pinMode(sig, OUTPUT);
digitalWrite(sig, LOW);
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
cm = 0.01723 * duration;; //converting time into a distance
Wire.write(cm); //Return value to master
delay(5);
}
// C++ code
//MASTER
#include
#include
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();
lcd.setCursor(0,0);
lcd.print(distance);
lcd.print(" cm");
delay(50);
Wire.end();
}