A blank distance result can mean a tilted object, a target outside the useful geometry, an unfinished response or a broken connection. It cannot establish that a room is empty. Build a small sonar laboratory that keeps those possibilities visible instead of replacing every failure with zero centimetres.
This experiment uses the exact Adafruit US-100 ultrasonic module, product 4019, an original Raspberry Pi Pico RP2040 and official MicroPython 1.26.0. Ultrasonic means sound above human hearing. The module emits a short sound burst and interprets its returning echo. Here its Universal Asynchronous Receiver/Transmitter (UART), a clockless serial link, returns two distance bytes; the Pico does not time an echo pulse or calculate a new temperature correction.
Choose the module before choosing its signal voltage
The US-100 resembles an HC-SR04 but its documented power and serial-mode behavior differ. Adafruit specifies this product for 3–5 V operation and documents a back-mounted mode jumper. Install that jumper with power removed to select UART. Do not copy these direct connections to a 5 V-only HC-SR04 or infer compatibility from two round transducers, the components that convert between electrical signals and sound.
Use Pico 3V3 OUT as the module supply, giving both boards the same 3.3 V logic environment. Logic level means the voltage interpreted as a digital zero or one. The Pico’s general-purpose input/output (GPIO) pins are not 5 V inputs. No level divider is required for this selected module at this selected supply; that statement is not permission to power it from 5 V while assuming an arbitrary board’s serial output is safe.
Prepare the two boards, short wires, a soldered Pico header, a ruler, a large flat card approximately 20 by 20 cm and a stable stand. Universal Serial Bus (USB) supplies the Pico and its console connection. Use a single sensor, a quiet indoor area and a stationary target. No motor, battery, enclosure, water tank or network is needed to learn this particular measurement boundary.
Read the unusual connector labels literally

| Pico net | US-100 label | Purpose |
|---|---|---|
| 3V3 OUT, physical 36 | VCC | Shared 3.3 V supply. |
| GND, physical 38 | Both GND pins | Common power and signal return. |
| GP4, physical 6, UART1 transmit | Trig/TX | Command travels from Pico to sensor. |
| GP5, physical 7, UART1 receive | Echo/RX | Response travels from sensor to Pico. |
These labels deserve attention: Adafruit’s UART wiring guide connects the controller’s TX to the module’s Trig/TX and the controller’s RX to Echo/RX. They are not the usual invitation to cross two devices’ TX/RX labels. Follow the named nets and arrows in this diagram. The connector names are functional labels; confirm the actual board printing before inserting a wire.
Disconnect USB before moving the mode jumper or wiring. Check supply and ground first, then each serial route. Both module ground pins belong to the same return; connect them to the common ground node. Leave the two acoustic openings unobstructed. Do not press, tape or glue anything onto the transducers, and keep the target away from loose wiring that might become an unintended nearer reflector.
Two bytes represent a reported distance, not a protected packet
The chosen serial configuration is 9600 bits per second, eight data bits, no parity and one stop bit, abbreviated 8N1. Parity is an optional extra error-check bit; it is absent here. Including the start bit, each byte occupies ten bit times, approximately 1.0417 ms. A two-byte response therefore needs about 2.0833 ms of serial wire time, in addition to acoustic measurement and module processing. That arithmetic does not establish the total response deadline.
Send the command byte 0x55, where the prefix 0x means hexadecimal notation. The documented response contains the high byte followed by the low byte. Calculate reported millimetres = 256 × high + low. For example, bytes 0x03 and 0xE8 represent 3×256+232=1000 mm. Divide by ten only when converting that reported quantity into centimetres.
This response has no application checksum, header or sequence number. A checksum could help detect accidental corruption; a sequence number could help associate a response with a request. Without them, two plausible bytes cannot prove freshness, identity or absence of corruption. The program labels its accepted result PLAUSIBLE_UART_RESPONSE, keeps freshness_authenticated false and never claims that occupancy is known.
A valid number still depends on the acoustic path

A broad, perpendicular, hard target often gives a more cooperative reflection than a small, soft or tilted target. In a simplified ray drawing, tilting a smooth plate can send much of the reflected energy away from the receiving transducer. Real ultrasonic fields spread, scatter and include multiple paths, so the drawing explains a possible cause rather than specifying a guaranteed beam boundary.
Adafruit lists a 2–450 cm detection range but also describes approximately 10–250 cm as a more useful working region. Start around 30 cm, where a ruler and broad target are easy to arrange. The advertised measuring angle is not a promise that every material or edge is detected uniformly inside a sharp cone. A reflected return might come from the wall behind the card or a nearby desk edge rather than the object you intended.
Keep the conversion appropriate to this interface. UART already returns the module’s millimetre result. The supplied legacy pulse-mode manual discusses internal temperature compensation; applying an unrelated HC-SR04 time-of-flight formula to these serial bytes would be a second, unjustified conversion. The optional US-100 temperature command is not used here and would not identify the complete air temperature along every acoustic path.
Complete bounded session program
Save the full listing as sonar_lab.py on the selected Pico, then run import sonar_lab; sonar_lab.main() from its console. No external driver library is required. The desktop host tests import the same functions without importing hardware modules. The pin configuration appears only inside main().
Download the complete program (ZIP; file: tricky-circuit-batch007-campaigns63-68/code/pico-us100-echo-qualification.py) · Blank observation sheet (ZIP; file: tricky-circuit-batch007-campaigns63-68/code/pico-us100-echo-qualification-observations-blank.csv)
"""US-100 UART lab, original Pico / MicroPython1.26.0.
Two plausible response bytes are not authenticated freshness or room occupancy.
"""
class Sonar:
def __init__(self, uart, ticks_ms, ticks_diff, sleep_ms):
self.uart, self.ticks, self.diff, self.sleep = uart, ticks_ms, ticks_diff, sleep_ms
self.failed = False
self.last = None
def query(self):
if self.failed:
raise ValueError('Session faulted; inspect and restart, no automatic retry')
try:
now = self.ticks()
if self.last is not None:
gap = self.diff(now, self.last)
if gap < 100:
raise ValueError('Need at least 100 ms between completed exchanges')
if self.uart.any():
raise ValueError('Unexpected bytes before request; alignment unknown')
if self.uart.write(b'\x55') != 1:
raise OSError('Request was not fully accepted')
start, previous = self.ticks(), 0
data = bytearray()
for _ in range(256):
age = self.diff(self.ticks(), start)
if age < previous:
raise ValueError('Clock order failed')
previous = age
if age > 250:
raise OSError('Response deadline expired; distance unknown')
chunk = self.uart.read(3)
if chunk is not None:
if not isinstance(chunk, (bytes, bytearray)):
raise ValueError('Invalid UART response type')
data.extend(chunk)
if len(data) > 2:
raise ValueError('Extra response bytes; alignment unknown')
if len(data) == 2:
# A short quiet guard catches immediate trailing bytes only.
self.sleep(5)
if self.uart.any():
raise ValueError('Trailing bytes; alignment unknown')
mm = (data[0] << 8) | data[1]
if not 20 <= mm <= 4500:
raise ValueError('Reported distance outside selected 2..450 cm range')
self.last = self.ticks()
return {'state': 'PLAUSIBLE_UART_RESPONSE', 'reported_mm': mm,
'freshness_authenticated': False, 'occupancy_known': False}
self.sleep(2)
raise OSError('Sample cap reached; clock or response unknown')
except Exception:
self.failed = True
raise
def run(sensor, sleep_ms, emit=print, trials=20):
if type(trials) is not int or not 1 <= trials <= 100:
raise ValueError('Use 1..100 bounded trials')
for trial in range(trials):
try:
row = sensor.query()
except (OSError, ValueError) as error:
emit({'trial': trial, 'state': 'SESSION_FAULT', 'reported_mm': None,
'occupancy_known': False, 'error': str(error)})
return
row['trial'] = trial
emit(row)
sleep_ms(500)
def main():
from machine import Pin, UART
from time import ticks_ms, ticks_diff, sleep_ms
uart = UART(1, baudrate=9600, bits=8, parity=None, stop=1,
tx=Pin(4), rx=Pin(5), timeout=0, timeout_char=0)
try:
sleep_ms(500) # Setup allowance; not a measured readiness certificate.
run(Sonar(uart, ticks_ms, ticks_diff, sleep_ms), sleep_ms)
finally:
uart.deinit()
if __name__ == '__main__':
main()
The program permits one outstanding request. Unexpected bytes before a request cause a session fault rather than being quietly thrown away. It accepts partial arrival of two bytes, refuses extra bytes, rejects a partial write and stops after a 250 ms elapsed-time policy or 256 polls. The constructor requests a zero first-character timeout with timeout=0, while timeout_char governs waits between successive characters. RP2, the MicroPython port used by this RP2040 Pico, clamps that inter-character setting to at least 2 ms at 9600 baud even when timeout_char=0 is requested. After receiving a byte, read(3) may therefore wait briefly for further characters. The program checks elapsed time before each read and then adds a 5 ms quiet guard after receiving two bytes: 250 ms is a receive-loop admission policy, not a wall-clock limit for the completed exchange. The finite poll count avoids a deliberate endless wait, while interpreter, driver and callback delays remain outside a hard real-time guarantee. A slow legitimate response may be refused by this conservative policy.
A five-millisecond quiet guard catches immediate trailing bytes. It cannot prove that a much later old response will never arrive. The 500 ms interval between successful trials reduces overlap without creating a missing sequence field. Once a fault occurs the session latches and stops; inspect the setup and restart deliberately instead of automatically sending another command into unknown alignment.
The software range filter is 20–4500 mm, matching the selected documented range rather than promising that every distance within it will work. An out-of-range value, no response and a one-byte response all leave distance unknown. They do not become a negative distance, a zero-height obstacle or an empty-room signal. Power loss and disconnected acoustic targets are not interchangeable fault diagnoses.
Change one physical variable at a time
- Record the module identity, jumper position, firmware, supply rail and connector mapping. With power disconnected, inspect every wire. Power through Pico USB, confirm approximately 3.3 V at module VCC and place a flat target around 300 mm from the transducer face.
- Run the twenty-trial session with the target fixed. Record the ruler convention, reported millimetres and failures. Do not copy the calculated 1000 mm byte example into a measurement column.
- Repeat at approximately 100, 300 and 600 mm with the same card normal to the sensor. Use a fresh explicit session after any fault. Record setup changes rather than silently merging runs.
- Keep the target centre near the same ruler distance while rotating it through marked angles such as 0°, 15°, 30° and 45°. Do not assume the sensor’s selected reflecting point remains the card centre. Compare refusals and changes in the number, not just the average of successful values.
- Replace the flat card with a soft material and then a narrower target. Look for a return from the background. Keep the sensor and surrounding furniture fixed so the changed target is the intended variable.
- Use the host injections to inspect fragmented, stale, extra and missing serial data. For an unplugged-module trial, remove power before disconnecting it; the remaining program should produce an unknown result rather than a fabricated distance.
The 22 host tests execute the actual session and loop, including every plausible integer distance, fragmented response, response cap, clock wrap, stale data, malformed replies and latched-fault behavior. They do not generate sound or verify physical echo timing. Keep later owner observations in the blank sheet and bench log, separately from these constructed serial cases.
Challenge: the card is visible, but the result vanished after you tilted it. Is the card beyond 4.5 m?
No. A missing serial result cannot distinguish acoustic reflection failure, a delayed response, wiring failure and range. First restore the recorded perpendicular geometry, then inspect voltage and serial behavior. A visually present object does not guarantee a useful ultrasonic return.
Primary documentation and further learning
- Exact Adafruit US-100 product 4019: module operating context, mode jumper and two-byte distance command.
- Manufacturer UART wiring guide: the unusual TX-to-Trig/TX and RX-to-Echo/RX labels.
- Manufacturer-maintained reference driver: command and high/low-byte interpretation; our complete MicroPython program is separately supplied above.
- Pinned MicroPython UART documentation and original Pico pinout.
- Supplier-hosted legacy pulse-mode manual: useful context, not a new bare-chip datasheet or a UART freshness guarantee.
Sources were checked on 20 October 2026. No separate applicable module errata notice was identified; the internal firmware version was not physically established. The existing HC-SR04 overview concerns a different module/interface. This lesson adds a bounded serial session and controlled acoustic geometry rather than replacing that old article. Revisit the electronics lessons for voltage, common-ground and serial-input foundations.



