Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Project 2
Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Answer:
#define IN_PIN A0
#define WINDOW_SIZE 5
int INDEX = 0;
int VALUE = 0;
int SUM = 0;
int READINGS[WINDOW_SIZE];
int AVERAGED = 0;
//void setup() {
// pinMode(IN_PIN, INPUT);
// Serial.begin(9600);
//}
//void loop() {
// SUM = SUM - READINGS[INDEX]; // Remove the oldest entry from the sum
// VALUE = analogRead(IN_PIN); // 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);
//delay(25);
//}
int inches = 0;
int cm = 0;
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);
}
void setup()
{
Serial.begin(9600);
pinMode(IN_PIN, INPUT);
//Serial.begin(9600);
}
void loop()
{
// measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(7, 7);
// convert to inches by dividing by 2.54
inches = (cm / 2.54);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.println("cm");
delay(100); // Wait for 100 millisecond(s)
SUM = SUM - READINGS[INDEX]; // Remove the oldest entry from the sum
VALUE = analogRead(IN_PIN); // 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("Average value :");
Serial.println(AVERAGED);
delay(25);
}
Output:


