Challenge

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

Project 2-

Arduino -1 code

const int pingPin = 7; //here we used constant pin no. 7 as Signal pin of Ping 28015

void setup() {
Serial.begin(9600); // Initialize serial communication
}

void loop() {
// Send a pulse to initiate measurement


pinMode(pingPin, OUTPUT);//by using pinMode function we are going to read the status of signal pin .This is done to send a brief pulse to the ultrasonic sensor to trigger a measurement.

//Ultrasonic sensors typically require a specific trigger signal to start transmitting ultrasonic pulses. By following this sequence(LOW, HIGH THEN LOW), the Arduino can effectively trigger the ultrasonic sensor to start a distance measurement.
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);

// Measure the duration of the pulse
pinMode(pingPin, INPUT); //This line configures the PingPIN as an input pin. This is done to receive the echo signal from the ultrasonic sensor.
long duration = pulseIn(pingPin, HIGH);//this measures the duration of the pulse received on the pingPin when the ultrasonic sensor sends back an echo.The pulseIn function returns the length of the pulse in microseconds and stores it in the variable duration.

// Convert the duration into distance
// Speed of sound in air at 20°C is approximately 343 meters per second or 0.0343 cm/microsecond
float distance = duration * 0.0343 / 2;

Serial.println(distance);// Send distance data to the second Arduino

delay(100); // Delay for stability
}

Arduino-2 code

const int numReadings = 5; // Number of readings for moving average
float readings[numReadings]; // Array to store the readings
int index = 0; // Index for the readings array
float total = 0; // Total sum of the readings

void setup() {
Serial.begin(9600); // Initialize serial communication
// Initialize the readings array
for (int i = 0; i < numReadings; i++)

{
readings[i] = 0;// make this array intially as all values 0, for making this array empty
}
}

void loop() {
if (Serial.available() > 0)

{

float distance = Serial.parseFloat();// Read distance data from the first Arduino


total = total - readings[index] + distance;// Add the distance reading to the total sum

readings[index] = distance;// Store the distance reading in the readings array

index = (index + 1) % numReadings; // Increment the index for next reading


float movingAverage = total / numReadings;// Calculate the moving average

// Print the smoothed data to the serial monitor
Serial.print("Smoothed Distance: ");
Serial.println(movingAverage);
}
}

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.