Ultrasonic distance calculator and moving average filter
For an HC-SR04 or Parallax PING))) sensor on an Arduino or AVR: turn the echo time into a distance at your air temperature, see what /58, /74 or 0.034 in your code assumes, simulate a moving average, median or exponential filter on noisy readings, and check a pasted sketch for the mistakes found in 1,136 student reports. Free, runs in your browser.
HC-SR04 and PING))) datasheets · Arduino reference · ATmega32 datasheet · Smith, DSP Guide ch. 15 · Updated 20 Nov 2026
The temperature sets the real speed of sound; the conversion is the line in your code that turns the echo time into a distance. An Indian room or lab is often near 30 °C.
"Reading every" is your delay() plus the time a ping takes. Missed echoes come back as the value you set (pulseIn returns 0). The seed changes the random noise, not the statistics.
It opens on a typical report sketch. The checker reads the code as text, looking for the patterns below; it does not compile or run it. Nothing you paste leaves your browser.
- At 30 °C sound travels at 349.1 m/s (dry air). "duration / 74 / 2" assumes 343.2 m/s, true at 19.9 °C, so it reads 1.7% short here.
- Stored as an integer, 38.71 in is cut to 38 (2.54 cm steps). Use float and round only when you print.
- AVR timer at 8 MHz / 1: one count = 0.125 µs = 0.00218 cm. This echo is 45,832 counts; it overflows every 8.192 ms (143 cm).
- Distance in cm = count / 458.32 at this temperature and clock.
- Leave over 60 ms between pings (HC-SR04 datasheet): at most about 16 readings a second.
What is the ultrasonic sensor and moving average filter project?
It is project 2 of Skill-Lync's Fundamentals of Embedded Systems course: measure the distance of an object with an ultrasonic sensor (the Parallax PING))) 28015 in 178 of the reports) and smooth the readings with a moving average filter, on an Arduino Uno or in Tinkercad's simulator. A second version, in the AVR and embedded PG programs, measures the HC-SR04's echo with a timer on an ATmega32 or ATmega328P at register level. Skill-Lync read all 1,136 public reports on 20 Nov 2026: 590 of the first and 546 of the second.
The sensor sends a burst of 40 kHz sound and holds its echo pin high until the echo comes back, so the pulse width is the round-trip time:
where c is the speed of sound in dry air at temperature T in °C (331.4 m/s at 0 °C, 343.3 m/s at 20 °C, 349.1 m/s at 30 °C). At 30 °C an object 1 m away gives an echo of 5,729 µs, 58.3 µs per cm at 20 °C and 57.29 µs per cm at 30 °C. The HC-SR04 datasheet gives 2 cm to 4 m, a 15° measuring angle and about 3 mm accuracy, and suggests a measurement cycle over 60 ms; the PING))) covers 2 cm to 3 m, with echoes from 115 µs to 18.5 ms.
Which conversion constant is right: 0.034, 58 or 74?
Each one is a speed of sound in disguise, and each is right at one temperature. These are the ones the reports use:
| In the code | Unit | Assumes (m/s) | Right at | At 30 °C, an object at 1 m reads | Where it comes from |
|---|---|---|---|---|---|
| duration * 0.034 / 2 | cm | 340.0 | 14.4 °C | 97.4 cm | most tutorials (340 m/s) |
| duration * 0.0343 / 2 | cm | 343.0 | 19.5 °C | 98.3 cm | tutorials quoting 343 m/s |
| duration / 58 | cm | 344.8 | 22.6 °C | 98.8 cm | HC-SR04 datasheet (µs / 58 = cm) |
| duration / 58.2 | cm | 343.6 | 20.6 °C | 98.4 cm | many HC-SR04 sketches |
| duration / 29 / 2 | cm | 344.8 | 22.6 °C | 98.8 cm | Arduino Ping example |
| duration / 2 / 29.1 | cm | 343.6 | 20.6 °C | 98.4 cm | many HC-SR04 sketches |
| 0.01723 * duration | cm | 344.6 | 22.2 °C | 98.7 cm | readUltrasonicDistance() sketches, often from Tinkercad |
| duration / 74 / 2 | in | 343.2 | 19.9 °C | 98.3 cm | Arduino Ping example (inches) |
| duration * 0.0135 / 2 | in | 342.9 | 19.3 °C | 98.2 cm | inch version of 343 m/s |
| count / 466.47 (8 MHz, no prescaler) | cm | 343.0 | 19.5 °C | 98.3 cm | ElectronicWings ATmega32 code |
So all of them land within 1.5% of each other, and at 30 °C every one reads short: by 1.2 to 2.6 cm at 1 m. The speed of sound rises about 0.6 m/s per °C, so a constant chosen for 20 °C reads about 1.7% short in a 30 °C room. Humidity matters less: even at 100% relative humidity sound is only 0.375% faster at 20 °C and 0.684% faster at 30 °C (Bohn 1988). If you need better than 2%, measure the temperature and compute c in the code, or calibrate against a ruler. The most common constants in the reports: /74 for inches (182 reports, the Arduino Ping example), 0.01723 from readUltrasonicDistance() sketches (102), 0.0343 (77), /29 (73) and 0.034 (47).
How does a moving average filter smooth sensor data?
It replaces each reading with the average of the last N readings:
You do not have to add N numbers every time. Keep a running sum: add the newest reading and subtract the one that just left the window. That needs the last N readings in an array (a circular buffer):
Two numbers describe what you get. Random noise falls by the square root of N, and the output lags the input by (N − 1)/2 readings:
Steven Smith's DSP Guide calls the moving average optimal for "reducing random white noise while keeping the sharpest step response", and also "an exceptionally bad low-pass filter": it is a smoothing filter, not a way to remove a particular frequency. After a step it reaches the new value exactly N − 1 readings later. In the default simulation (σ = 1 cm noise, a reading every 100 ms, N = 5, 2% missed echoes read as 0), the 5-point average cuts the noise from 1.01 to 0.40 cm and catches up with a 40 cm move in 0.4 s:
The dips are the missed echoes. One 0 among five readings of 100 cm pulls the average down by 20 cm, for five readings (20.0 cm worst here). A moving median of the same five readings ignores a single 0 completely (worst 1.6 cm), at the price of a little more noise (0.57 cm):
An exponential filter (y += α(x − y), α = 2/(N + 1) = 0.33) needs no array and gives about the same noise (0.41 cm), but it remembers a glitch longer (37.6 cm worst) and takes 0.9 s to come within 1 cm after the move. The best order for an ultrasonic sensor: throw away 0 and out-of-range readings, then filter. The simulator tab lets you try your own N, noise and reading rate.
What goes wrong in the reports
Of the 590 moving-average reports, 501 include Arduino code. Only about 98 of them keep a buffer of the last N readings, a true moving average. The rest:
- The sum is never reset (115 reports). "sum = sum + inches; avg = sum / 5;" with sum declared once at the top. Every pass of loop() adds another reading, and nothing ever takes one out, so the 'average' climbs without end: after 40 readings of 100 cm with N = 5 it shows 800. Hand-checked on a random 8 of the 115: all 8 have the bug.
- The same reading added N times (about 56). A for loop runs "sum = sum + inches" five times without a new reading inside it. Without a reset that is the bug above; with one it is no filter at all.
- No timeout on pulseIn (446). pulseIn(echo, HIGH) waits up to one second and returns 0 if no complete pulse arrives. Those 0s then go straight into the average. Pass a timeout (30,000 µs covers 5 m) and skip the 0s.
- Integer maths (181 store the average in an int or long). "inches = duration / 74 / 2" in a long cuts every reading to whole inches, 2.54 cm steps, from a sensor that resolves 3 mm; then total / N cuts again. With whole-centimetre readings and N = 5 the average reads low by 0.91 cm on average, on top of the constant's error. At 30 °C and 1 m the sample sketch prints 38 inches, 3.5 cm short.
- A slow loop. The last delay() in the loop is 1,000 ms in 114 reports, 100 ms in 99 and 250 ms in 85. With delay(1000) and N = 5 the window spans 5 s and the average lags 2 s: fine for a water tank, too slow for a parking sensor.
- A buffer that starts at zero. A global array is zero at start-up, so the first outputs of a circular-buffer filter are too small: with N = 5 the first output is a fifth of the distance (the simulator's "int maths, buffer starts at 0" filter shows it). Fill the buffer with the first good reading in setup().
The Check tab flags each of these in a pasted sketch. On the 115 never-reset reports it catches 114, and it flags no report outside that list.
A moving average sketch that avoids all of these
Float readings, a timeout, missed echoes skipped, the buffer filled before the first output and a running sum. Change C for your temperature (20.05 × √(273.16 + T)), N for your noise and lag.
const byte TRIG = 9, ECHO = 10;
const int N = 5; // average of the last 5 readings
const float C = 349.1; // speed of sound at 30 °C, m/s
float buf[N];
float total = 0;
int idx = 0;
float readCm() { // one ping; -1 if no usable echo
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
unsigned long us = pulseIn(ECHO, HIGH, 30000UL);
if (us == 0) return -1;
float cm = us * C * 1e-4 / 2;
return (cm < 2 || cm > 400) ? -1 : cm;
}
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
float first;
do { first = readCm(); delay(60); } while (first < 0); // wait for a first good echo
for (int i = 0; i < N; i++) buf[i] = first; // start the window full
total = first * N;
}
void loop() {
float x = readCm();
if (x >= 0) { // skip missed echoes instead of averaging them in
total += x - buf[idx]; // add the newest, drop the oldest
buf[idx] = x;
idx = (idx + 1) % N;
}
Serial.println(total / N, 1);
delay(60); // datasheet: measurement cycle over 60 ms
}The AVR version: timer counts, volatile and the clock
Of the 546 HC-SR04 reports, 374 measure the echo with a timer on an ATmega32 or ATmega328P, and 231 of those use the ElectronicWings ATmega32 code: Timer1 input capture with no prescaler at 8 MHz, one count every 0.125 µs, an overflow interrupt every 8.192 ms, and
which assumes
and is right (its comment says 343 m/s). One count is 0.0021 cm, far finer than the sensor. Three things in it are worth knowing:
- The overflow counter is not volatile. TimerOverflow is changed in the interrupt and read in main(), but it is declared a plain int. The compiler may keep it in a register and miss the interrupt's update. It only matters past the first overflow, an echo longer than 8.192 ms, about 140 cm. 246 of the 374 AVR reports change a variable in an ISR without volatile.
- 65535 × overflows (116 reports) should be 65536: a 16-bit timer has 65,536 counts. It costs one count per overflow, 0.0021 cm, so it never matters.
- The clock has to really be 8 MHz. The ATmega32 datasheet: "The device is shipped with CKSEL = '0001' and SUT = '10'. The default clock source setting is therefore the 1MHz Internal RC Oscillator." On a chip whose fuses were never changed, the code runs at 1 MHz and every distance reads 8 times short (12.5 cm for 100 cm). Factory calibration of the internal oscillator is within ±3% at 1 MHz, 5 V and 25 °C, so even with the right clock the distance can be a few per cent off; an external crystal fixes both. 136 reports define F_CPU 8000000 and one mentions the fuses.
Set the clock and prescaler in the Calculate tab to see the counts, overflows and resolution for yours.
What this calculator does not cover
- The beam and the target. Soft, small or angled objects, objects at the edge of the 15° cone and echoes off nearby walls give wrong or missing readings that no filter fixes.
- Temperature gradients and wind. The speed of sound uses one temperature for the whole path.
- Kalman and other model-based filters. They need a model of how the object moves; the moving average, median and exponential filters here do not.
- The code check is pattern matching. It reads the text of the sketch, so unusual variable names or code split across files can hide a mistake or flag a false one.
Reading a sensor, timing a pulse and filtering noise is the core loop of embedded work, from parking sensors to battery management. It is a project in Skill-Lync's embedded courses.
- Fundamentals of Embedded Systems
- AVR Bare Metal Programming (HC-SR04 with an ATmega328P)
- PG Program in Embedded Systems for EV Applications
Frequently asked questions
What is the formula for HC-SR04 distance?
Distance = speed of sound × echo pulse time ÷ 2, because the pulse goes to the object and back. With the echo in microseconds and the answer in centimetres, that is duration × 0.0343 / 2 at 20 °C, or duration / 58 from the datasheet. At 30 °C sound travels at 349.1 m/s, so 1 m gives an echo of 5,729 µs.
Why do we divide by 58 for an ultrasonic sensor?
58 µs is how long sound takes to go 1 cm and come back at about 345 m/s (2 cm ÷ 0.0345 cm/µs). The HC-SR04 datasheet gives µs / 58 = cm and µs / 148 = inches. It is right at about 22.6 °C; at 30 °C the true divisor is 57.29.
Why does my moving average keep increasing?
Because the sum is never cleared and the oldest reading is never taken out. Code like "sum = sum + inches; avg = sum / 5;" adds every reading forever, so after 40 readings of 100 cm the 'average' reads 800. A moving average keeps the last N readings in an array, adds the newest and subtracts the oldest. 115 of the 501 public reports with Arduino code on this project have this bug.
What window size N should I use for a moving average filter?
Big enough to cut the noise, small enough that the lag is acceptable. Random noise falls by √N (5 readings: 0.45×, 10 readings: 0.32×), and the average lags by (N − 1)/2 readings. At one reading every 100 ms, N = 5 lags 0.2 s; with delay(1000), as in 114 reports, the same N lags 2 s.
Why does my ultrasonic sensor read 0 or jump?
A 0 is a missed echo: pulseIn returns 0 when no complete pulse arrives within its timeout, and an HC-SR04 with nothing in range holds its echo high for about 38 ms. Soft, angled or very close objects (under 2 cm) reflect badly. Throw such readings away before the filter: one 0 among five readings of 100 cm pulls a moving average down by 20 cm.
Is a moving average or a median filter better for ultrasonic sensors?
For random noise, the moving average: it gives the smallest noise for a given window. For dropouts and spikes, the median: it ignores a single bad reading completely. In the default simulation here (2% of readings are 0), a 5-point moving average still drops by up to 20.0 cm on a glitch and a 5-point median by 1.6 cm. A common combination is both: a median of 3 to 5 readings, then a moving average.
Related on Skill-Lync
- Free lessons: Fundamentals of Embedded Systems
- Student project: ultrasonic sensor with a moving average filter
- Embedded systems courses compared and embedded engineer salaries in India
- Electrical and electronics project ideas
- Curve fitting calculator (calibrate a sensor against reference points)
- All free engineering tools
Sources
- ElecFreaks, "Ultrasonic Ranging Module HC-SR04" datasheet (as hosted by SparkFun): 2 cm to 4 m, 15°, 10 µs trigger, 8-cycle 40 kHz burst, "uS / 58 = centimeters or uS / 148 = inch", "we suggest to use over 60ms measurement cycle".
- Itead Studio HC-SR04 datasheet (2010): "If no obstacle is detected, the output pin will give a 38ms high level signal."
- Parallax, "PING))) Ultrasonic Distance Sensor (#28015)" v1.5: 2 cm to 3 m, echo pulse 115 µs to 18.5 ms, 200 µs before the next measurement.
- Arduino Ping example (arduino-examples, 06.Sensors/Ping): microseconds / 74 / 2 for inches, microseconds / 29 / 2 for centimetres. Arduino reference: pulseIn() default timeout one second, returns 0 if no complete pulse; int on ATmega boards is 16-bit (−32,768 to 32,767).
- Engineering ToolBox, "Air: speed of sound": c = 20.05 √(273.16 + T) m/s for dry air, 343.3 m/s at 20 °C. HyperPhysics: 343 m/s at 20 °C, 331.4 m/s at 0 °C.
- D. A. Bohn, "Environmental effects on the speed of sound", Journal of the Audio Engineering Society 36(4), 1988, Table 2: humidity raises c by 0.375% at 20 °C and 0.684% at 30 °C at 100% RH.
- S. W. Smith, The Scientist and Engineer's Guide to Digital Signal Processing, chapter 15 (dspguide.com): noise reduction equal to the square root of the number of points; optimal for white noise with the sharpest step response; a poor low-pass filter. J. O. Smith, Spectral Audio Signal Processing, "Running Sum Lowpass Filter": delay of (N − 1)/2 samples.
- Microchip, ATmega32 datasheet (2503Q-AVR-02/11): shipped with the 1 MHz internal RC oscillator selected; factory calibration within ±3% at 5 V, 25 °C, 1 MHz.
- ElectronicWings, "Ultrasonic Module HC-SR04 interfacing with AVR ATmega16/ATmega32": F_CPU 8 MHz, Timer1 input capture, count = ICR1 + (65535 × TimerOverflow), distance = count / 466.47.
- Skill-Lync, all 1,136 public ultrasonic-sensor reports (590 moving-average, 546 HC-SR04), read 20 Nov 2026: conversions, filters, types, delays, timer code.
- Skill-Lync, scripts/verify/ultrasonic.py: recomputes every constant, the timer numbers and the filter simulation in Python (same random numbers), checks noise falls as 1/√N, the integer bias and the step response, and writes the numbers this page checks itself against at build time.