Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
// C++ code
//including the libraries
#define TRIG 3
#define ECHO 2
#include<Wire.h>
// declaring the variables
int duration;
int distance;
int average=0;
void setup()
{
pinMode(TRIG, OUTPUT);//taking pin 3 as output
pinMode(ECHO,INPUT);//taking pin 2 as input
Serial.begin(9600);//serial communication begins
Wire.begin();//I2C communication begins here
}
void loop()
{
digitalWrite(TRIG,HIGH);//trigger pin taken as high
delayMicroseconds(10);//given few delay
digitalWrite(TRIG,LOW);//trigger pin taken as low
duration=pulseIn(ECHO,HIGH);//time is obtained
distance=duration*(0.034/2);//distance is calculated
//data is transmitted to slave
Wire.beginTransmission(8);
Wire.write(distance);//distance is send to slave
Wire.endTransmission();
Wire.requestFrom(8,1);//data is requested from slave
average=Wire.read();//slave data is stored
//data is printed on the serial monitor
Serial.print("The distance is : ");
Serial.print(distance);
Serial.println();
Serial.print("Distance from average filter is ");
Serial.print(average);
Serial.println();
}
//slave
#include<Wire.h>
#define WINDOW_SIZE 5
int INDEX = 0;
int VALUE = 0;
int SUM = 0;
int READINGS[WINDOW_SIZE];
int AVERAGED = 0;
void setup() {
Wire.begin(8);
Serial.begin(9600);
Wire.onRequest(RequestEvent);
Wire.onReceive(ReceiveEvent);
}
void loop() {
delay(25);
}
void ReceiveEvent(int howMany)
{
SUM = SUM - READINGS[INDEX]; // Remove the oldest entry from the sum
VALUE = Wire.read(); // Read the next sensor value
READINGS[INDEX] = VALUE; // Add the newest reading to the window
SUM = SUM + VALUE; // Add the newest reading to the sum
INDEX = (INDEX+1) % WINDOW_SIZE; // Increment the index, and wrap to 0 if it exceeds the window size
AVERAGED = SUM / WINDOW_SIZE; // Divide the sum of the window by the window size for the result
Serial.print(VALUE);
Serial.print(",");
Serial.println(AVERAGED);
}
void RequestEvent(){
Wire.write(AVERAGED);
}