Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
// master code
#include <Wire.h>
#define SLAVE_ADDRESS 9 // Address of the slave Arduino
#define TRIGGER_PIN 7 // Pin connected to the trigger of the Ultrasonic sensor
#define ECHO_PIN 7 // Pin connected to the echo of the Ultrasonic sensor
int inches = 0;
int cm = 0;
void setup()
{
Wire.begin(SLAVE_ADDRESS); // Initialize I2C communication as slave
Wire.onRequest(sendDistance); // Register the function to be called when the master requests data
}
void loop()
{
// Nothing to do here since the distance is sent in the sendDistance function
}
// Function to read distance from the Ultrasonic sensor
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
// Function to send distance data when requested by the master Arduino
void sendDistance()
{
// Measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(TRIGGER_PIN, ECHO_PIN);
// Convert to inches by dividing by 2.54
inches = cm / 2.54;
// Send the distance data to the master Arduino
Wire.write(highByte(inches));
Wire.write(lowByte(inches));
}
/////////////
///////////// slave code
#include <Wire.h>
#define SLAVE_ADDRESS 9 // Address of the slave Arduino
#define TRIGGER_PIN 7 // Pin connected to the trigger of the Ultrasonic sensor
#define ECHO_PIN 7 // Pin connected to the echo of the Ultrasonic sensor
int inches = 0;
int cm = 0;
void setup()
{
Wire.begin(SLAVE_ADDRESS); // Initialize I2C communication as slave
Wire.onRequest(sendDistance); // Register the function to be called when the master requests data
}
void loop()
{
// Nothing to do here since the distance is sent in the sendDistance function
}
// Function to read distance from the Ultrasonic sensor
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
// Function to send distance data when requested by the master Arduino
void sendDistance()
{
// Measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(TRIGGER_PIN, ECHO_PIN);
// Convert to inches by dividing by 2.54
inches = cm / 2.54;
// Send the distance data to the master Arduino
Wire.write(highByte(inches));
Wire.write(lowByte(inches));
}