Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
int pingPin = 7;
void setup() {
Serial.begin(9600);
}
void loop() {
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin,LOW);
delay(1000);
digitalWrite(pingPin, HIGH);
delay(3000);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin,HIGH);
inches = secondsToInches(duration);
cm = secondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(1000);
}
long secondsToInches(long seconds)
{
return seconds / 74 / 2;
}
long secondsToCentimeters(long seconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the object we
// take half of the distance travelled.
return seconds / 34 / 2;
}
output