Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
//Master Node
#include <LiquidCrystal.h>
#include <Wire.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); //LCD Module Pins (RS,EN,D4,D5,D6,D7)
int data; //Variable to store received data from slave
void setup()
{
lcd.begin(16, 2); //Initialize the LCD
Wire.begin(); //Initialize I2C
Serial.begin(9600);
}
void loop()
{
Wire.requestFrom(8, 2); //Requesting 2 bytes of data from slave address 8
//Check if the data is available
if (Wire.available())
{
data = Wire.read(); //Read the received data from slave
}
Serial.println(data);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance:");
lcd.setCursor(0, 1);
lcd.print(data); //To display the recieved data from slave
lcd.print(" cm");
delay(100);
}
//Slave Node
#include <Wire.h>
const int sensor_pin = 2; //Sensor pin to 2
int distance = 0; //Variable to store Measured distance
void setup()
{
Wire.begin(8); //Start I2C with slave address 8
Wire.onRequest(requestEvent); //Function to handle I2C data request
Serial.begin(9600);
}
void requestEvent(void)
{
long cm = distance * 0.01715; //Convert sensor value to centimeter(distance * speed of sound/2)
char arr[sizeof(cm)]; //Array to store bytes
memcpy(arr, &cm, sizeof(cm)); //Copy bytes to array
Wire.write(arr, sizeof(arr)); //Send the array via I2C
}
void loop()
{
distance = Distance(); //Variable to store sensor data
delay(500);
}
//Function to take sensor data
long Distance()
{
//To trigger sensor
pinMode(sensor_pin, OUTPUT);
digitalWrite(sensor_pin, LOW);
delay(5);
digitalWrite(sensor_pin, HIGH);
delay(10);
digitalWrite(sensor_pin, LOW);
pinMode(sensor_pin, INPUT); //Setting sensor pin as i/p
return pulseIn(sensor_pin, HIGH); //Measure and return the data
}