Skip to content

UART

Experimental

Tested against simulated devices only so far; the API may change in minor releases.

See Find the baud rate for an introduction.

autobaud

Find the baud rate of a live UART by trying candidates and scoring the output.

Example

from hwntools.uart import autobaud
best = autobaud("/dev/ttyUSB0")[0]
print(best.baud, best.score)

For logic-analyzer captures (instead of a live port) the external baudhound tool is far more accurate; autobaud_from_capture runs it when it is installed.

BaudResult dataclass

BaudResult(baud: int, score: float, sample: bytes)

One tried baud rate: its score_output score and the first 256 bytes received.

score_output

score_output(data: bytes) -> float

Score how much data looks like a text console (0.0 .. ~1.2).

Combines the printable-ASCII ratio, the share of real line breaks and bonus points for typical boot-log words. Garbage from a wrong baud rate scores low.

looks_like_console

looks_like_console(data: bytes) -> bool

Return True when data is unambiguously clean console text.

This is the early-stop test of autobaud. Unlike score_output, whose value depends on the content (digits and punctuation lower it, boot-log words raise it), it only asks whether the bytes decode cleanly: at least CLEAN_MIN_BYTES bytes, at least CLEAN_MIN_PRINTABLE of them printable ASCII, a line break and a few letters. Output read at a wrong baud rate is dominated by framing garbage (0x00, 0x80, 0xf8...), so a dozen clean bytes in a row practically never happen by accident.

autobaud

autobaud(port: str | None = None, bauds: Sequence[int] = COMMON_BAUDS, sample_time: float = 1.5, probe: bytes | None = b'\r\n', opener: Callable[[int], Tube] | None = None, stop_score: float | None = 0.95, stop_on_clean: bool = True) -> list[BaudResult]

Try each baud rate, read for sample_time seconds and rank by score_output.

probe is sent after opening to make an idle console print a prompt (None to stay listen-only; power-cycle the target during the scan instead). opener lets you supply your own tube factory (baud -> Tube); by default port is opened with pyserial. The scan stops early when a rate reaches stop_score or, with stop_on_clean (the default), as soon as a rate yields output that looks_like_console accepts. The second rule matters for short replies such as a bare prompt: their score depends on the text and can stay just under stop_score even at the right rate. Pass stop_score=None, stop_on_clean=False to always try every rate.

autobaud_from_capture

autobaud_from_capture(capture: str | PathLike[str], samplerate: str | int | None = None, **kwargs: Any) -> UartResult | None

Detect the UART settings in a logic-analyzer capture using baudhound.

Returns the most likely target-TX channel's UartResult (.baudrate, .framing, .inverted...) or None if no UART was found. Use hwntools.tools.baudhound.analyze for the full report.