Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

PiCrawler / Sensors & Range

Sensors & Range

Ultrasonic timing, validity, blind spots and the limits of stock feedback.

Sensors: distinguish observations from assumed state

The established stock sensing paths are one forward ultrasonic ranger, a camera and the HAT's battery ADC path. The user-confirmed hardware list does not establish an IMU, foot-contact switches, joint encoders or individual actuator-current sensors. The Robot HAT library containing an ADXL345 class does not mean an accelerometer is mounted in PiCrawler. Its presence is an optional software driver, not stock sensor evidence.

MeasurementInterfaceWhat software receivesWhat it does not measure
Forward distanceD2/D3 GPIO trigger/echo in stock exampleDistance in centimetres or negative failure resultFull obstacle geometry, floor edges, side/rear clearance
Scene imageCSI -> libcamera/Picamera2Frame pixels and optional detectionsGuaranteed range, pose in a room or collision-free route
Battery dividerHAT MCU ADC A4 over I2CApproximate pack voltageState of health, current, remaining runtime or per-cell balance
User buttonsPi GPIO inputsPress/release stateAutomatically enforced motion stop

The stock obstacle example rejects nonpositive range samples, takes a median of valid samples and uses a 15 cm threshold. A failed batch results in no new movement decision in that loop. It samples before a blocking action and therefore does not provide continuous collision supervision. “Forward range is clear” is a narrow observation, not proof that all four swinging legs have safe space.

Battery voltage under load is affected by internal resistance, wiring and simultaneous servo demand. A sudden low-voltage reading can indicate sag even if a rested pack appears charged. Repeated sampling is useful, but an approximate ADC result cannot authorize an unverified charger or a battery replacement. Calibrate voltage telemetry against a suitable meter under supervised conditions before making quantitative claims.

Sensor logs need a timestamp, unit, validity flag and sample age. An old successful image detection must not remain indefinitely true after a camera thread dies. A negative sonar result must not be interpreted as a far-away object. A future multi-sensor controller should define what happens when one input is stale or unavailable, with a conservative bounded command policy.

Source evidence: pc-avoid, hat-modules, hat-adc, hat-device, vi-core, user-evidence.

Ultrasonic ranging: a narrow time-of-flight measurement

The module is triggered by a short digital pulse. It emits an ultrasonic burst and reports an echo interval. Sound travels to a reflecting surface and back, so distance is half the sound-speed-times-duration product. robot_hat.Ultrasonic uses 343.3 m/s and converts the result to centimetres: d = duration_seconds × 343.3 / 2 × 100. Its result is rounded to two decimal places; rounding is not a statement of centimetre accuracy.

The current driver creates D2/D3 pin objects as trigger and echo, pulses trigger for approximately 10 microseconds, then polls echo with wall-clock timing. The default timeout is 0.02 seconds shared by the wait sequence. The nominal round-trip range of sound during 20 ms is about 3.43 m, before trigger/wait overhead. That software budget is distinct from the module page's advertised 2–500 cm range. Linux polling and scheduling make the driver different from a dedicated high-resolution hardware timestamp capture.

_read() returns -1 on timeout and -2 for an invalid edge capture. read(times=10) retries -1 but returns other values, including -2, immediately. It is not a ten-sample mean or median. The current avoidance example adds its own validity filtering, median selection and signal-alarm wrapper. Applications should preserve invalid readings as invalid rather than display them as negative distances or reinterpret zero as infinity.

What the sensor can miss

The echo comes from a surface capable of returning sound toward the transducers. Fabric can absorb energy; an angled flat surface can reflect it elsewhere; small or narrow objects can be missed. Nearby side reflections or multipath can produce a surprising nearer value. Two ultrasonic modules firing together can hear each other's pulses. Temperature changes sound speed and therefore the distance scale. The page contains a “40 Hz” frequency line but also describes an eight-cycle 40 kHz burst; this package does not repeat the first line as the acoustic carrier frequency.

There is no authoritative measured field-of-view for the actual module in this evidence set. Do not draw a calibrated beam cone or assume a point ray. A single reading cannot tell whether a wall spans the robot's path or whether one leg will strike an unseen object. The sensor is forward-facing and does not provide drop-off detection beneath every foot, rear clearance or a room map.

Electrical identity gate

The generic module page describes a 5 V device. That fact does not establish a safe voltage at every echo connector on this assembled robot. Pi GPIO is 3.3 V logic. Preserve the stock harness and verify any carrier/level conditioning before replacing or adding a ranger. Do not connect an arbitrary 5 V HC-SR04 echo straight to a Pi GPIO because the Python pins match the tutorial.

A useful range experiment

With the robot stationary and safe, test a known flat target at measured distances and angles, then compare soft fabric and a narrow post. Record valid/invalid counts, median error and time per call. Next test while servos are stationary versus moving. This separates optical/environmental effects, timing noise and electrical disturbances. It is a stronger foundation for reactive behavior than treating every numerical return as ground truth.

Source evidence: hat-modules, pc-avoid, pc-ultrasonic-doc. Derived timeout range and experimental proposals are engineering calculations, not sensor specifications or bench results.

Sensor-driven behavior and realistic autonomy

Use acquisition → timestamped measurement → interpretation → state → behavior → single motion owner. A distance < threshold inside a long gait loop is insufficient once camera/network/voice can also request movement. Keep tiny examples simple, but introduce explicit states when there are target-loss, obstacle, connection and fault conditions.

Stock ultrasonic opportunities

Distance meter, approach-and-stop, proximity game, distance-zone speed choice and bounded obstacle response are practical stock-hardware projects. Log centimetres and negative failure codes separately. read(times=10) retries timeouts; it is not a ten-sample average. A median of valid samples can reduce outliers but increases decision delay and must retain sample age. The official obstacle example uses 15cm; a custom 20cm threshold is an app policy whose usable margin needs bench qualification.

One forward transducer pair supplies a range-like observation, not a point cloud, map, whole-body collision envelope or cliff detector. Wall-distance regulation facing a broad wall is possible; travel parallel to that wall needs side observation or a deliberate, qualified sensing scan. A forward clearance reading also cannot authorize an unseen rear/side turn. Use a controlled level course with an operator before any exploration claim.

State machine design

StateEntry / maintained conditionMotion policy and exit
IDLEBoot, unarmed, or manual pauseNo new actuator command; arm only after preflight
SEARCHArmed, fresh sensors, target absentBounded reviewed turn/search; stop search on timeout or ambiguity
TARGET_FOUNDStable associated detectionConfirm freshness and range; no automatic approach from one frame
APPROACHTarget centered and fresh range authorizesOne short approved segment; reobserve before another
TOO_CLOSERange below qualified lower thresholdInhibit advance; reverse only if rear safety is independently reviewed
AVOIDApproved clearance strategy with operator/course constraintsBounded turn; return to observation, not blind long movement
LOST_TARGETDetection age expired or association ambiguousCancel pending approach; settle into idle or bounded search policy
ERRORStale critical sensor, exception, lease loss or explicit stopLatched no-new-motion state, log cause, deliberate reset

A Python enum with a small transition function is enough initially. Separate raw values, interpreted events and state transitions so recorded inputs can exercise the decision logic without a robot. Use hysteresis/dwell to avoid oscillation. Timestamp both acquisition and decision; copying a dict does not automatically make its fields an atomic frame snapshot. A worker/process can acquire independently, but it must not become a second motion writer.

New observations and control opportunities

An IMU enables a basic raw logger, stationary bias/axis check, estimated pitch/roll, turn-rate traces, tilt alerts and fall-event annotation. Motion logging is the easy/intermediate first task. Behavioral use can pause future motion after a qualified tilt threshold, with false-trigger analysis. Closed-loop posture correction is advanced research requiring transforms, filtering, bounds, latency measurement and a usable actuator update path. No absolute yaw comes from a six-axis IMU without another heading reference; integrating acceleration is not a ready position sensor.

Two light inputs can drive differential seeking with normalized gain and a range veto. Environment logging is useful when stations are known and sensor heat/settling is characterized. Bump/touch switches add local contact events after mounting/wiring review, but can also snag or trigger too late to protect a swinging leg. ToF coverage and actual foot contact require separate sensor geometry and driver plans; no assumed mounting is stock.

Control theory and sensor fusion

For image centering, a simple normalized error is (x-W/2)/(W/2) using actual image width W. A proportional law can select a bounded turn amount or segment pattern, with deadband and saturation. It does not create a continuous precision yaw actuator. For distance regulation, use fresh error from a standoff setpoint and choose segment length/rate; lag, coarse gait increments and sensor uncertainty can make an aggressive controller oscillate. Add integral/derivative terms only after measuring the response; consider saturation and noisy derivative estimates.

Camera plus range can implement arbitration: camera decides heading, range vetoes advance. That is useful combined sensing, but metric target-distance fusion additionally needs association, sensor extrinsics, timing and uncertainty. A forward sonar echo may belong to a wall behind the pictured person. IMU plus gait command allows a residual/tilt study; it does not measure feet. IMU plus camera can support state estimation only with synchronized frames, calibration and a declared model. Reading two sensors into the same program is not sufficient evidence of sensor fusion.

For localization, counting gait cycles is a baseline drift experiment, not trustworthy odometry. QR identity can define a checkpoint without giving metric pose. Calibrated markers with known dimensions/locations provide a stronger external reference. LiDAR or depth adds environment measurements but still needs where-and-when pose, transforms and leg-obstacle constraints. See ROS2_ROADMAP and p2-known-course before discussing SLAM or Nav2.

Source evidence: hat-modules, pc-avoid, pc-core, vi-core, hat-i2c, opencv-markers, nav2-odom; V1 OPEN_LOOP_VS_CLOSED_LOOP and EXPANSION_AND_UPGRADES.

Continue

Meeting checklist · Source library · Modification atlas · All project proposals