Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
const int pingPin = 7; // pin num
void setup()
{
Serial.begin(9600); // begins serial communication
}
void loop()
{
float duration; // duration between the transmitter and receiver
float inches, cm; // object distance interms of inches and centimeters
float sum = 0;
float avg;
int i;
pinMode(pingPin, OUTPUT); // pingPin is used as output to send the pulse
digitalWrite(pingPin, LOW); // clears the pingPin
delayMicroseconds(2);
digitalWrite(pingPin, HIGH); //sets pingPin as high
delayMicroseconds(5);
digitalWrite(pingPin, LOW); // sets pingpin as low
pinMode(pingPin, INPUT); // pingpin is used as input to receive the pulse
duration = pulseIn(pingPin, HIGH); // to receive the reflected signal (pulsein - to get sound wave travel time)
inches = (duration/2)/74;
cm = (duration/2)/29.1;
for(i=0; i<10; i++)
{
sum += inches;
avg = sum/10;
}
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm, ");
Serial.print(avg);
Serial.print("avg for in");
Serial.println();
delay(100);
}