Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Solution :
const int pingPin = 12; //Define the Arduino pin connected to the ultrasonic sensor
int distances[5]; //Array to store the last 5 distance measurements
float average = 0.0; //Variable to store the average
void setup()
{
Serial.begin(9600);
}
void loop()
{
long duration, inches; //Variables to store duration and distance in inches
pinMode(pingPin, OUTPUT); //Set the pingPin as an OUTPUT
digitalWrite(pingPin, LOW); //Send a low pulse to trigger the ultrasonic sensor
delayMicroseconds(2); //Wait for 2 microseconds
digitalWrite(pingPin, HIGH); //Send a high pulse to trigger the ultrasonic sensor
delayMicroseconds(5); //Wait for 5 microseconds
digitalWrite(pingPin, LOW); //Turn off the trigger pulse
pinMode(pingPin, INPUT); //Set the pingPin as an INPUT
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration); // Convert the duration to inches
Serial.print(inches); //Print the distance in inches
Serial.print(" inches : "); //Print a label for the distance
Serial.println(); //Print a newline character
delay(1000); //Delay for 1 second
for (int i = 0; i < 5>
{
distances[i] = inches; //Store the current distance measurement in the array
Serial.println(distances[i]); //Print the stored distance
}
average = (distances[0] + distances[1] + distances[2] + distances[3] + distances[4]) / 5.0;
Serial.print("average : "); //Print a label for the average distance
Serial.print(average); //Print the average distance to the serial monitor
Serial.println(); //Print a newline character
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2; //Convert microseconds to inches
}
Project LInk:
https://www.tinkercad.com/things/h9ppRtyhFvs-project-02/editel?sharecode=DsIfYbanC2_T6UjkvECUSK8rjV-3YI5esRHLT1Xjl8A