DEV Community

Is this reading real? Validity checks for a 1 kHz rangefinder stream

A free-running rangefinder gives you a lot of numbers and no promises. The LRF50H, one of our 905 nm modules, streams 4-byte 5C frames at 1 kHz by default, so a flight controller or a PLC sees a new distance every millisecond.

Most of them are fine. A few are not, and the few that are not tend to be the ones that matter.

I am Tommy Yu, an engineer at ERDI TECH LTD, the manufacturer of these modules. This post is about the part after the checksum: how I decide whether a decoded 5C value should be used. The evidence comes from a bench capture our factory recorded on 2026-11-06 for the ArduPilot driver work (ArduPilot/ardupilot#34983). Everything below was checked against the model documents and that capture on 2026-11-18.

What the frame gives you

5C lo hi chk chk = ~(lo + hi) & 0xFF, little-endian distance

The manual's own example is 5C 02 11 EC. The unit depends on the model, not on the family:

Model Count is Out-of-range marker Rated range
LRF50H centimetres 65535 0.05 to 50 m at 90% reflectivity, 0.05 to 15 m at 10%
LRF22VB millimetres 20000 0.05 to 20 m at 90% reflectivity, 0.05 to 10 m at 10%

So 5C 02 11 EC is 43.54 m on an H module and 4.354 m on a VB module. Reading the wrong row is a factor of ten.

The checksum is one byte. It catches most line noise, not all of it. A frame that passes was probably received as sent, which is a weaker statement than "the distance is right".

Four outcomes, four counters

I keep these separate, because each one points at a different problem:

  • Skipped bytes. The byte was not 5C, or the checksum failed. This is wiring, logic level or noise. In the 2000 frames I replayed it was zero, but that log only holds frames the vendor tool had already accepted.
  • Out-of-range marker. The module says it saw nothing usable: 65535 on LRF50H, 20000 on LRF22VB. This is a normal answer, not an error.
  • Beyond the configured maximum. The checksum is valid, the value is not the marker, and the distance is bigger than the sensor can measure.
  • Valid.

Class 3 is the one people forget. The factory's LRF50H log, taken against a wall 1.9 m away, has 2000 frames. 1997 of them read between 189 and 204 cm (median 196 cm). Three read 31496, 36977 and 39688, which is 315, 370 and 397 m, on a module rated for 50 m. None of them is the 0xFFFF marker. The vendor tool accepted all three.

I cannot tell you why. The log holds decoded values, not raw bytes, so I cannot say whether the module emitted them or whether corrupted frames happened to pass a one-byte checksum. What I can say is what they do to a naive consumer. Two of the three, at log positions 867 and 875, are eight frames apart. If your consumer averages the last nine frames, the second spike lands in a window that already holds the first one. I computed that mean over this log: it reaches 77.6 m while the wall has not moved.

The rule I use is blunt: anything above the configured maximum is dropped and counted. The ArduPilot driver takes the same view and treats any frame beyond RNGFNDx_MAX as out-of-range instead of averaging it.

Do not use the datasheet's best-case range as the gate. LRF50H is specified to 50 m at 90% reflectivity and 15 m at 10%. A dark target at 20 m is a legitimate reading, and a gate set at 15 m would remove it. Set the gate at the largest number your application can legitimately see, such as the 50 m rating.

A rolling median on top

A gate removes impossible values. A median removes the possible-but-wrong ones the gate cannot see. I keep the last nine frame slots, including the invalid ones, and only output a value when at least five of those slots are valid. Two consequences:

  • A run of out-of-range markers longer than four frames produces None, not the last good distance. A stale number is worse than no number.
  • Up to four bad frames inside the window do not move the output.

On the replay, the median alone also handles those three spikes, because none of them sits in a run longer than four. What it did not do is make the signal quieter. The standard deviation of the valid frames was 2.73 cm and of the filtered output 2.73 cm. The log changes value only 56 times in 2000 lines, and the 189 to 204 cm spread is the module's real scatter at that wall. A median is an outlier filter, not a smoother. If you need smoothing, add it separately and accept its lag; our note on update rate on moving platforms covers what a filter costs on a moving vehicle.

Size the window in time, not in frames. The tool that wrote the log recorded about 91 frames per second for the H module and about 94 for the VB module, and the factory notes say that rate comes from the tool's receive loop, not from the module. Nine slots are 9 ms if your host reads every frame at 1 kHz, and about 99 ms at 91 frames per second.

The code

from collections import deque
from statistics import median

MODELS = {
    # metres per count, out-of-range marker, configured max in metres
    "LRF50H": (0.01, 65535, 50.0),
    "LRF22VB": (0.001, 20000, 20.0),
}

class Stream:
    def __init__(self, model, window=9, min_valid=5):
        self.scale, self.marker, self.max_m = MODELS[model]
        self.win = deque(maxlen=window)
        self.min_valid = min_valid
        self.buf = b""
        self.n = dict(frames=0, skipped_bytes=0, marker=0, beyond_max=0, valid=0)

    def feed(self, data):
        """Return one (instant_m or None, filtered_m or None) per decoded frame."""
        self.buf += data
        out, i = [], 0
        while len(self.buf) - i >= 4:
            if self.buf[i] != 0x5C:
                i += 1; self.n["skipped_bytes"] += 1; continue
            lo, hi, chk = self.buf[i+1], self.buf[i+2], self.buf[i+3]
            if chk != (~(lo + hi)) & 0xFF:
                # drop one byte, look for the next 5C
                i += 1; self.n["skipped_bytes"] += 1; continue
            i += 4
            self.n["frames"] += 1
            raw = lo | (hi << 8)
            m = raw * self.scale
            if raw == self.marker:
                self.n["marker"] += 1; m = None
            elif m > self.max_m:
                self.n["beyond_max"] += 1; m = None
            else:
                self.n["valid"] += 1
            self.win.append(m)
            ok = [x for x in self.win if x is not None]
            out.append((m, median(ok) if len(ok) >= self.min_valid else None))
        self.buf = self.buf[i:]
        return out

The four counters are the useful output. Log them once a second. A rising skipped_bytes rate is a wiring problem and shows up earlier than a wrong distance does. A rising beyond_max with a clean skipped_bytes is the pattern in the factory log.

Self-tests I ran

I ran these before pasting, in a Python script with assertions:

  • The manual frame 5C 02 11 EC decodes to 43.54 on LRF50H and 4.354 on LRF22VB.
  • Two noise bytes in front of a marker frame, a 31496 frame and a 196 frame give None, None, 1.96, with the counters at 3 frames, 2 skipped bytes, 1 marker, 1 beyond-max, 1 valid.
  • A frame split across two reads decodes once the second half arrives.
  • One 314.96 m spike in nine slots of 1.96 m gives a mean of 36.74 m and a median of 1.96 m.
  • The 2000 LRF50H log lines, re-encoded as 5C frames (so the bytes are synthetic), give 1997 valid and 3 beyond-max, at positions 867, 875 and 1210, with valid values between 1.89 and 2.06 m.
  • The 3000 LRF22VB lines (1708 to 1710 mm) give 3000 valid and no events at the 20 m gate.
  • Nine good frames followed by five markers: the filtered output is 1.96 m on the ninth and None on the last.

I have not run this against a live module or a raw byte capture. The factory log is the best evidence we have, and it is decoded values only. A raw capture and a flight-controller log are still the missing pieces for the claim "tested on hardware".

At 460800 baud a 4-byte frame is 40 bit times, so the line can carry 11,520 frames per second. 1 kHz uses about 8.7% of it. The parser is not where you will run out of time.

Where to look next

Driver code and protocol notes (MIT): https://github.com/ErdiTech/erdi-lrf-drivers

LRF50H model page: https://erdilrf.com/models/lrf50h/?utm_source=devto&utm_medium=post&utm_campaign=devto-5c-validity-202611

Paste a raw capture into the browser decoder to check frames and checksums: https://erditech.com/lrf-uart-protocol-decoder/

If you have a raw hex capture of 20 or more frames that includes a bad one, send it to t****@erdimail.com with the model name. I can say more from bytes than from a plot.

Disclosure: I am Tommy Yu, an engineer at ERDI TECH LTD (erdilrf.com), the manufacturer of the modules discussed. Data checked against our model documents and the 2026-11-06 factory bench capture on 2026-11-18.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.