The Ultrasonic Bumper Board is a small electronic board that drives up to four HC-SR04 ultrasonic range sensors and sends the measured distances to the main computer of a robot over a serial line. I designed it in February 2016 for MyzharBot v4, and it is still on board today on MyzharBot v5, as an always-on safety layer.

This page collects the original documentation of the board: the reasons behind it, how the HC-SR04 works, the wiring, the firmware, the binary protocol and the ROS driver.

Why ultrasonic sensors

The optical 3D sensors I used on MyzharBot v3 and v4 have an intrinsic limitation: they cannot perceive obstacles that are too close along the forward direction of motion. The Asus Xtion Pro Live could not see obstacles closer than 50 cm, and the StereoLabs ZED of those years not closer than 1 meter.

This blind zone is not a problem in a static environment, but it is really dangerous in a dynamic one, where other robots, people and children can suddenly appear in front of the robot.

Optical sensors also cannot see transparent obstacles. Stereo cameras and lidars rely on light, and mirrors, glass doors and glass walls reflect it or let it through. Ultrasonic sensors rely on sound reflection instead, and sound bounces back from all of them. HC-SR04 sensors are far less precise than optical sensors, but they cover exactly the cases the optical sensors miss, so the robot can move safely in a dynamic environment.

How the HC-SR04 works

The principle is simple. An ultrasonic emitter sends a 40 kHz sound pulse, the sound wave bounces off an obstacle and comes back to the sensor, where an ultrasonic receiver detects it. The sensor reports the duration T of the round trip, and with the speed of sound vs (about 343 m/s in air at room temperature) the distance D of the obstacle is:

D = vs · T / 2

The division by two is there because the sound travels to the obstacle and back.

The sensor has two signal pins:

  • Trig: a pulse of at least 10 µs starts a measurement; the sensor then emits the 40 kHz burst;
  • Echo: the sensor answers with a pulse whose width is the duration T of the round trip, so the microcontroller has to measure the width of this pulse.

According to the user guide, the echo pulse should be between 150 µs and 25 ms, and 38 ms if no obstacle is detected. In practice, when there is no obstacle or when the sensor is obstructed, the echo duration is quite random, and sometimes longer than 200 ms. This behavior is well described in the analysis Making a better HC-SR04 Echo Locator (archived copy, the original site is offline). The firmware must therefore never trust a single echo blindly: it discards any echo longer than 25 ms, which corresponds to about 4 m.

The board

The sensors are managed by an ST Nucleo32 board (NUCLEO-F303K8), based on the STM32F303K8 microcontroller, which talks to the host over a USART with a simple binary protocol.

I built the prototype on a soldered perfboard. The board can be powered from the micro USB connector of the Nucleo, or from an external stabilized 5 V supply through a dedicated 2-pin connector or through the 4-pin USART connector.

Prototype of the ultrasonic bumper board: an ST Nucleo32 board soldered on a perfboard with the connectors for four HC-SR04 sensors
The Ultrasonic Bumper Board prototype, February 2016

Sensor layout and triggering

The four sensors are placed at the corners of the robot:

  --- Sonar #0 ----------- Sonar #1 ---
  |                                   |
  |                                   |
  |                                   |
  --- Sonar #3 ----------- Sonar #2 ---

Firing all the sensors at the same time would create interference: a sensor could receive the echo of the burst emitted by its neighbor. Firing them one at a time would make the update rate too low. The compromise is to trigger them in diagonal pairs, which point in different directions:

  • sensor #0 and sensor #2 share the same trigger;
  • sensor #1 and sensor #3 share the same trigger.

So only two trigger signals are needed, while each echo needs its own input, for a total of four timers to measure the four echoes.

Pinout

STM32CubeMX pinout of the STM32F303K8 in LQFP32 package, with trigger, echo, USART1 and LED pins highlighted in green
The STM32F303K8 pin configuration in STM32CubeMX
Nucleo32 pin Function Peripheral
PA6 Trigger, sensors #0 and #2 TIM16 CH1, PWM single shot
PA7 Trigger, sensors #1 and #3 TIM17 CH1, PWM single shot
PA8 Echo, sensor #0 TIM1 CH1 input capture direct, CH2 indirect
PA0 Echo, sensor #1 TIM2 CH1 input capture direct, CH2 indirect
PB4 Echo, sensor #2 TIM3 CH1 input capture direct, CH2 indirect
PA2 Echo, sensor #3 TIM15 CH1 input capture direct, CH2 indirect
PA9 USART1 TX USART1
PA10 USART1 RX USART1
PB3 Green LED on the Nucleo GPIO

Two solder bridges on the Nucleo32 must be changed:

  • the board is powered by an external 5 V supply, so SB1 must be opened;
  • to use PA2 as the echo input of sensor #3 you need to open SB2 and SB3, which disables USART2 for the Virtual COM Port of the ST-LINK (see Table 6 of the UM1956 user manual, “STM32 Nucleo-32 boards”).

The firmware

The firmware is based on the STM32CubeF3 HAL library, and the peripherals are configured with the STM32CubeMX tool. The repository contains the CubeMX project and the projects for IAR EWARM and for the free System Workbench for STM32 (OpenSTM32).

The design uses the timers to do the hard work, so the CPU only has to read the results:

  • Trigger: TIM16 and TIM17 are configured as PWM timers in One Pulse mode. Starting the timer produces a single 10 µs pulse on the trigger pin, with no software timing involved.
  • Echo: each echo pin is connected to a timer in Input Capture mode, coupling two channels on the same pin: channel 1 captures the rising edge when the echo starts, channel 2 captures the falling edge when it ends. The value captured on channel 2 is the echo duration, in steps of 10 µs.
  • Validation: in the capture interrupt, an echo longer than 25 ms (about 4 m) is marked as not valid.
  • Heartbeat: TIM6 generates a 100 ms interrupt that toggles the green LED of the Nucleo, so you can see at a glance that the firmware is running.

The main loop is a fixed sequence:

  1. trigger sensors #0 and #2, then wait 49 ms;
  2. trigger sensors #1 and #3, then wait 49 ms;
  3. convert the valid echo durations to distances in meters (D = T · vs / 2, with vs of about 343 m/s), using a special “not valid” value for the others;
  4. send the data frame on USART1 and invalidate all the measures for the next cycle.

The result is a new frame about every 100 ms, so the board emits data at 10 Hz.

USART binary protocol

The board sends data on USART 1, with these parameters:

Parameter Value
Baud rate 115200
Data bits 8
Parity none
Stop bits 1
Hardware handshaking not available

Every frame is 32 bytes long, and all the multi-byte fields are little endian (LSB first):

Offset Type Field Description
0 uint16 Synchronization word 0x5AA5, sent on the wire as the bytes 0xA5 0x5A
2 uint16 Byte count 30, the number of bytes after the synchronization word
4 uint32 Ticks milliseconds elapsed since the board was powered on
8 float Not valid value value assigned to ranges that are not valid (99999.99 in the current firmware)
12 float Range #0 range measured by the sensor on input #0, in meters
16 float Range #1 range measured by the sensor on input #1, in meters
20 float Range #2 range measured by the sensor on input #2, in meters
24 float Range #3 range measured by the sensor on input #3, in meters
28 uint16 Sonar active the number of sonars active on the board
30 uint16 Terminator 0x0D0A, sent on the wire as the bytes 0x0A (line feed) 0x0D (carriage return)

A range is not valid when the obstacle is farther than 4 m or closer than 2 cm, or when no usable echo was received in the cycle. The board has no serial input: it only streams data.

The frame maps directly on this C structure, so on a little endian host a memcpy of 32 bytes is enough to decode it (there is no padding: every field is naturally aligned):

#include <stdint.h>

#define MAX_SONAR 4

typedef struct _data_out
{
    uint16_t ctrl_frame_0;        // Sync word 0x5AA5 (0xA5 0x5A on the wire)
    uint16_t byte_count;          // Number of bytes following [30]
    uint32_t ticks;               // Milliseconds since system start
    float not_valid_val;          // Value used for not valid distances
    float distances[MAX_SONAR];   // Distances in meters
    uint16_t sonar_active;        // Number of sonars connected
    uint16_t ctrl_frame_1;        // Terminator 0x0D0A (LF CR on the wire)
} DataOut;

_Static_assert(sizeof(DataOut) == 32, "DataOut must be 32 bytes");

Decoding the stream in Python

To read the board from any computer, the robust approach is the same used by the ROS driver: search for the synchronization bytes, wait for a full frame, and check the terminator before trusting the data. This is a minimal decoder, written for this page:

import struct

FRAME = struct.Struct("<HHIf4fHH")  # 32 bytes, little endian
SYNC = b"\xa5\x5a"                  # 0x5AA5 on the wire
TERM = 0x0D0A                       # 0x0A 0x0D on the wire

def parse(buf: bytearray):
    """Extract complete frames from buf, return a list of dicts."""
    frames = []
    while True:
        start = buf.find(SYNC)
        if start < 0:
            del buf[:-1]            # keep a possible half sync word
            return frames
        del buf[:start]
        if len(buf) < FRAME.size:
            return frames           # wait for more bytes
        sync, count, ticks, not_valid, r0, r1, r2, r3, active, term = FRAME.unpack_from(buf)
        if count != FRAME.size - 2 or term != TERM:
            del buf[:2]             # false sync, search again
            continue
        del buf[:FRAME.size]
        ranges = [None if r == not_valid else r for r in (r0, r1, r2, r3)]
        frames.append({"ticks": ticks, "ranges": ranges, "active": active})

Feed it with the bytes read from the serial port, for example with pySerial:

import serial

buf = bytearray()
with serial.Serial("/dev/ttyUSB0", 115200, timeout=0.5) as port:
    while True:
        buf += port.read(64)
        for frame in parse(buf):
            print(frame["ticks"], frame["ranges"])

I tested the decoder on synthetic frames built with the same structure, including frames split across two reads and garbage before the synchronization word; I did not run it against the real board for this page.

ROS integration

The ros_ultrasonic_bumper package is the ROS (ROS 1, catkin) driver for the board. The ultrasonic_bumper_node node opens the serial port, decodes the frames as described above, and publishes the four ranges at 10 Hz on the ranges topic, with a custom message (ros_ultrasonic_bumper/ultrasnd_bump_ranges) that contains one standard sensor_msgs/Range for each corner of the robot:

Board input Message field Frame ID
#0 sensor_FL ultraSnd_FL
#1 sensor_FR ultraSnd_FR
#2 sensor_RR ultraSnd_RR
#3 sensor_RL ultraSnd_RL

Each Range message is filled with radiation type ULTRASOUND, a field of view of 30°, and a range from 0 to 4 m.

Not valid measures are remapped to the maximum range (4 m), and the same happens when the serial port times out or the board is not connected. This choice is deliberate: the bumper feeds a speed filter on the robot velocity commands, and a missing board must not block the robot forever.

The node parameters are:

Parameter Default Description
serial_port /dev/ttyUSB0 serial port connected to the board (/dev/ttyTHS2, a Jetson UART, in the launch file)
baudrate 115200 serial baud rate
timeout_msec 500 serial read timeout in milliseconds
simul false publish random ranges, to test the rest of the system without the board

In this video, one of the first integration tests on MyzharBot v4: two sensors mounted on the front panel of the robot, with the ros_ultrasonic_bumper node publishing the ranges and rqt_plot showing them in real time, to check the response time of the system.

MyzharBot/ROS - Ultrasonic Bumper - ROS Integration test Plays from YouTube, which may set cookies. Privacy · Watch on YouTube

Still on board: MyzharBot v5

Ten years later the Ultrasonic Bumper Board is still on duty. On MyzharBot v5 the ultrasonic sensors sit below the power control panel and are always on. The robot now relies on stereo cameras and lidars, but the physics has not changed: mirrors, glass doors and glass walls reflect light or let it through, while sound bounces back from all of them. The ultrasonic sensors are the last safety net before the robot hits something the other sensors missed.

The ROS driver described above is for ROS 1. MyzharBot v5 runs ROS 2, and a ROS 2 driver for the board is in progress.