This is the chapter where the robot gets its software framework and learns to move its wheels. You install ROS 2 Humble, then write the small Python module that speaks the controller board's language, and then build the base driver: the one program that owns the board, turns velocity commands into wheel speeds, and decides fifty times a second whether the wheels may turn at all. It ends with the robot on its stand, wheels in the air, timing each of the software stops.
Plan a long day for it. The ROS part takes about two hours. Writing and testing the board module takes two or three hours, and the driver four to six, plus an hour of stand tests. Nothing touches the wheels until the last part of the chapter, and that part needs you at the robot.
ROS 2 is the framework every robot program in this guide is built on: the base driver, the LiDAR reader, navigation, and later the AI that runs the robot. It isn't an operating system, despite the name. It's a set of libraries and tools that let many small programs work together.
Each of those programs is called a node. A node is one process, or part of one, with a name such as rosorin_board_driver or rosorin_lidar_reader. Nodes talk by publishing messages on named topics. The LiDAR reader, for example, publishes a sensor_msgs/msg/LaserScan message on the topic /scan ten times a second, and any node that subscribes to /scan receives it. Neither side knows the other exists. They only agree on the topic name and the type of message. That is what makes it easy to swap one part of the robot for another later.
ROS 2 doesn't move the messages itself. It hands them to a layer underneath called DDS. On Humble the default is eProsima Fast DDS, version 2.6 on this robot. DDS finds the other side by itself: every process announces its publishers and subscribers on the network, and processes with matching topics connect to each other. This is called discovery. On one computer DDS sends data through shared memory when it can, and through UDP network packets otherwise.
Discovery reaches every computer on your network, not just the robot. To keep separate robots or experiments apart, ROS uses a number called the domain ID, set with the environment variable ROS_DOMAIN_ID. It is 0 when unset. Processes only discover others with the same number.
ROS 2 installs into /opt/ros/humble, not into /usr. Your shell doesn't find the ros2 command or the ROS Python packages until you run source /opt/ros/humble/setup.bash, which adds them to PATH, PYTHONPATH and a few ROS variables, for example ROS_DISTRO=humble. This is called sourcing. The packages you build yourself later live in a folder called a workspace, here ~/ros2_ws, and the workspace has its own install/setup.bash. Sourcing it after the system one lays your packages over the system ones, which ROS calls an overlay. The order matters: whatever is sourced last wins.
You install Humble because it is the ROS 2 release made for Ubuntu 22.04, and that is what NVIDIA's Jetson Linux R36.4.3 runs. Only the base packages go on the robot, with no desktop tools, because the robot has no screen.
The robot's package sources include NVIDIA's own repository for the r36.4 channel. That channel already offers newer versions of NVIDIA's packages than the R36.4.3 you built in chapter 3. Look for yourself, from your laptop:
curl -sfL https://repo.download.nvidia.com/jetson/t234/dists/r36.4/main/binary-arm64/Packages.gz | gunzip | awk '/^Package: /{p=$2} /^Version: /{if (p ~ /^nvidia-l4t-(bootloader|kernel|core|init)$/) print p, $2}' | sort -u
On my robot it listed nvidia-l4t-bootloader, core, init and kernel in versions 36.4.0, 36.4.3, 36.4.4 and 36.4.7. A normal apt-get upgrade would install 36.4.7. That means a new kernel, so every driver module from chapter 5 would stop loading, and a bootloader package that rewrites the module's boot flash. So before anything else is installed, every NVIDIA package on the robot gets frozen at the version it has. Updating NVIDIA's software is a separate job for another day, with its own backup.
One more package to stay away from: nvidia-jetpack. It looks like the obvious way to get CUDA and TensorRT. On this robot it would pull in the 36.4.7 packages and replace the OpenCV that ROS 2 Humble uses, removing 19 packages. Chapter 8 installs CUDA, cuDNN and TensorRT one package at a time instead. Check that it isn't there:
dpkg-query -W nvidia-jetpack
It must say no packages found matching nvidia-jetpack, now and at the end of every later chapter.
The install follows the official docs.ros.org procedure for Humble ("Ubuntu (deb packages)") and adds the freeze. The locale and Ubuntu's universe repository that the procedure asks for are already set on the system you built.
The script starts by checking that it runs as root, sets DEBIAN_FRONTEND=noninteractive so that package scripts don't stop to ask questions, and remembers the first line of /etc/nv_tegra_release, NVIDIA's release line, to compare at the end.
Then it freezes NVIDIA's packages. dpkg-query lists every nvidia-l4t-* package dpkg has ever heard of, each with a status code in front: ii for installed, hi for installed and held, un for known but not installed. The awk filter keeps only ii and hi, and apt-mark hold freezes them. A held package is never upgraded, removed or replaced by apt until you unhold it. The filter matters: an earlier copy of this script tried to hold a package that wasn't installed and stopped with E: Can't select installed nor candidate version.
Next it runs apt-get update and apt-get upgrade. With the holds in place, that only upgrades Ubuntu's own packages.
Then it adds the ROS repository. The ROS project ships its repository address and signing key as a small package, ros2-apt-source. The script installs curl itself, so the robot has it from here on, then asks GitHub for the newest release number, builds the file name for Ubuntu jammy, downloads it and installs it. That creates /etc/apt/sources.list.d/ros2.sources, pointing at packages.ros.org.
Last, it installs ros-humble-ros-base, the core of ROS 2 without graphical tools, and ros-dev-tools, the build tools. Among those are colcon, which builds your packages later in this chapter, and pytest. Then it prints the versions, proves NVIDIA's release line didn't change, runs the ros2 command once in a fresh shell, and lists failed system services. There should be none.
Here is the complete ~/setup/install_ros2.sh. It is also scripts/install_ros2.sh in the repository:
#!/bin/bash
# ROS 2 Humble (ros-base + dev tools) per docs.ros.org Humble "Ubuntu (deb packages)".
# L4T packages held at the installed version (golden image baseline). Run: sudo bash ~/setup/install_ros2.sh
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "run with sudo"; exit 1; }
export DEBIAN_FRONTEND=noninteractive
L4T_BEFORE=$(head -1 /etc/nv_tegra_release)
echo "== hold L4T packages"
# only installed packages (dpkg also lists known-but-not-installed ones, e.g. nvidia-l4t-ccp-generic)
apt-mark hold $(dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 'nvidia-l4t-*' | awk '$1 ~ /^[ih]i$/ {print $2}') >/dev/null
echo "held: $(apt-mark showhold | grep -c '^nvidia-l4t-')"
echo "== apt update + upgrade (Ubuntu packages; L4T held)"
apt-get update -q
apt-get -y -q upgrade
echo "== ros2-apt-source"
apt-get install -y -q curl
V=$(curl -s https://api.github.com/repos/ros-infrastructure/ros-apt-source/releases/latest | grep -F '"tag_name"' | awk -F'"' '{print $4}')
[ -n "$V" ] || { echo "could not read ros-apt-source version"; exit 1; }
CODENAME=$(. /etc/os-release && echo "${UBUNTU_CODENAME:-${VERSION_CODENAME}}")
curl -fL -o /tmp/ros2-apt-source.deb "https://github.com/ros-infrastructure/ros-apt-source/releases/download/${V}/ros2-apt-source_${V}.${CODENAME}_all.deb"
dpkg -i /tmp/ros2-apt-source.deb
echo "== install ros-humble-ros-base + ros-dev-tools"
apt-get update -q
apt-get install -y -q ros-humble-ros-base ros-dev-tools
echo "== verify"
dpkg-query -W -f='${Package} ${Version}\n' ros-humble-ros-base ros-dev-tools ros2-apt-source
L4T_AFTER=$(head -1 /etc/nv_tegra_release)
[ "$L4T_BEFORE" = "$L4T_AFTER" ] && echo "L4T unchanged: $L4T_AFTER" || echo "WARNING L4T CHANGED: $L4T_AFTER"
bash -c 'source /opt/ros/humble/setup.bash && ros2 --help >/dev/null && echo "ros2 CLI OK" && printenv ROS_DISTRO'
systemctl --failed --no-legend
echo "ROS2_DONE"
Copy the script from your laptop. Laptop commands in this chapter reach the robot as rosorin, the cable alias from chapter 5. With the cable out, use rosorin-wifi instead.
scp -q ~/CCode/rosorin-pro/scripts/install_ros2.sh rosorin:setup/
The script upgrades several hundred packages before it installs ROS. If your SSH session drops in the middle, apt can be left half done, so run it in the background on the robot and watch the log:
nohup sudo bash ~/setup/install_ros2.sh > ~/setup/install_ros2.log 2>&1 &
tail -f ~/setup/install_ros2.log
On my robot it took about 10 minutes: 525 packages upgraded and 340 ROS packages installed. The log starts with held: 45 and ends like this:
ros-dev-tools 1.0.3
ros-humble-ros-base 0.10.0-1jammy.20260916.125240
ros2-apt-source 1.3.0~jammy
L4T unchanged: # R36 (release), REVISION: 4.3, GCID: 38968081, BOARD: generic, EABI: aarch64, DATE: Wed Jan 8 01:49:37 UTC 2025
ros2 CLI OK
humble
ROS2_DONE
Nothing between humble and ROS2_DONE means no failed services. The script installs whatever ros2-apt-source and Humble packages are newest on the day you run it, so your version numbers can be newer than mine. If it stops with could not read ros-apt-source version, GitHub answered with nothing, either because there's no network or because of GitHub's limit on anonymous requests. Run it again later. If you ever see WARNING L4T CHANGED, something upgraded NVIDIA's packages. Stop there. Your set from chapter 5 holds the system as it was, but as chapter 5 says, writing a set back onto the robot has never been tested.
The upgrade replaced libraries that running programs still use, so reboot:
test -f /var/run/reboot-required && { echo "REBOOT REQUIRED by:"; cat /var/run/reboot-required.pkgs 2>/dev/null; } || echo "no reboot required"
sudo systemctl reboot
Mine listed libc6, libssl3, network-manager, evolution-data-server and gnome-shell, and the robot was back on SSH in under a minute. After the reboot, test -f /var/run/reboot-required && echo "reboot still required" || echo "no reboot pending" should print no reboot pending, the root should still be the partition you installed to in chapter 4, the kernel 5.15.148-tegra, and head -1 /etc/nv_tegra_release should still say REVISION: 4.3.
ros-base comes without the demo programs, so use the ros2 command line itself as a publisher and as a listener. Open two SSH sessions to the robot. In the first, publish the text hello five times a second on a topic called /probe:
source /opt/ros/humble/setup.bash
ros2 topic pub -r 5 /probe std_msgs/msg/String "{data: hello}"
std_msgs/msg/String is the message type. It has one field, data, holding text, and "{data: hello}" fills it in YAML. In the second session, wait for one message and print it:
source /opt/ros/humble/setup.bash
ros2 topic echo --once /probe
The listener prints this and exits:
data: hello
---
Stop the publisher with Ctrl-C. The ros2 command starts a small background helper, the ROS 2 daemon, that remembers what it has discovered. Stop it when you're done with ros2 daemon stop. The same test also works as one command, which is how I ran it:
source /opt/ros/humble/setup.bash
ros2 topic pub -r 5 /probe std_msgs/msg/String "{data: hello}" >/dev/null 2>&1 & P=$!
sleep 4; timeout 8 ros2 topic echo --once /probe; kill $P 2>/dev/null
ros2 daemon stop >/dev/null 2>&1
The test publishes over and over and the listener waits up to 8 seconds for a reason. Discovery takes a moment, and a message sent once right after a publisher starts can be lost because the listener hasn't been found yet. For the same reason, one empty result from a ros2 command proves nothing. Run it again before you look for a fault. If messages arrive only sometimes, and it gets worse after you log out, systemd-logind is deleting your user's shared-memory files when your last session closes. Chapter 4 sets RemoveIPC=no to stop that.
Two habits will save you trouble with SSH. A background job started inside ssh rosorin '... &' ignores Ctrl-C and kill -INT, so stop it with a plain kill, as the block above does. And pkill -f probe inside an SSH command can match and kill your own SSH session, because its command line contains the same word. Kill by process number.
The robot's ~/.bashrc is the stock Ubuntu one and doesn't source ROS. Every command in this guide sources the setup files explicitly, and so does every service. That keeps it obvious which ROS layers a program sees. The base service you write later in this chapter sources the system ROS and then your workspace, in that order, and chapter 9 adds a third workspace between them. A package in a later layer hides the same package in an earlier one.
Every robot service also sets its domain explicitly with Environment=ROS_DOMAIN_ID=0. In your SSH shell the variable is unset, which also means domain 0, so your commands see the services. Check it in a fresh shell:
source /opt/ros/humble/setup.bash; printenv ROS_DISTRO; echo "ROS_DOMAIN_ID=${ROS_DOMAIN_ID:-unset}"
It prints humble and ROS_DOMAIN_ID=unset.
Be aware what domain 0 means. The robot's DDS isn't limited to the robot itself. Any other computer on your network running ROS 2 in domain 0 discovers the robot's topics and can publish to them, including the topic that drives the wheels. The robot talks to your PC over HTTP, never over DDS, so there's no reason for your PC to share the domain. If you run ROS on any other machine, give it a different domain ID unless you mean to talk to the robot.
These come from the same ROS repository, and from NVIDIA's for ffmpeg. Install them now, so that later chapters only build and configure. The ROS ones use --no-install-recommends, which tells apt to install only what a package needs and not the extras it merely recommends. That keeps the robot to what is used.
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q ffmpeg v4l-utils
sudo apt-get install -y --no-install-recommends ros-humble-control-msgs
sudo apt-get install -y --no-install-recommends ros-humble-robot-localization
sudo apt-get install -y --no-install-recommends ros-humble-slam-toolbox
sudo apt-get install -y --no-install-recommends ros-humble-navigation2 ros-humble-nav2-bringup
sudo apt-get install -y ros-humble-web-video-server
apt-mark showhold | grep -c nvidia-l4t
The whole block took about two and a half minutes. The installs added 4, 1, 6, 203, 74 and 2 new packages, each line ending with 0 to remove, and the last line printed 45: the holds are still there. Here's what each one is for. ffmpeg and v4l-utils are video tools for testing a camera. control-msgs holds the arm's trajectory messages, which the base driver imports; without it the driver dies at its first start with No module named 'control_msgs'. robot-localization is the filter that fuses wheel odometry and the IMU in chapter 9. slam-toolbox is the map tool of chapter 9, and it pulls in the Qt libraries, which is why it brings 203 packages; chapter 9 has no tested way to make a map of your own room with it. navigation2 and nav2-bringup are navigation, chapter 10. web-video-server lets you watch camera topics in a browser.
On my robot the versions were Nav2 1.1.20, slam_toolbox 2.6.10, robot_localization 3.5.4, web_video_server 3.1.0 and ffmpeg 7:4.4.2-nvidia. Check yours:
dpkg-query -W -f='${Package} ${Version}\n' ros-humble-navigation2 ros-humble-nav2-bringup ros-humble-slam-toolbox ros-humble-robot-localization ros-humble-web-video-server ffmpeg v4l-utils
Nav2's version matters later. Chapter 10 applies a fix to one Nav2 package, and the fix refuses to run unless that package is exactly 1.1.20. If apt has moved on by the time you read this, that fix needs checking again.
If any of these installs wants to upgrade an nvidia-l4t-* package or remove packages, stop and read apt's list before you answer. And never run apt autoremove on the robot: after a removal it offers to remove initramfs-tools, which NVIDIA's boot setup needs.
Try the web video server once. Start it:
ros2 run web_video_server web_video_server --ros-args -p port:=8080 -p address:=0.0.0.0
From a second session, curl localhost:8080 should answer with <html><head><title>ROS Streamable Topic List</title>. Stop the server with Ctrl-C. Nothing starts it at boot; it only runs when you start it by hand.
This step fixes the worst performance fault my robot ever had. To understand it you need to know how Fast DDS decides whether two processes can use shared memory.
Two DDS processes on the same computer can exchange messages through shared memory: one writes into a block of RAM, files under /dev/shm, and the other reads it. That's fast and costs almost no CPU. Processes on different computers have to use UDP packets. To decide which case applies, Fast DDS 2.6 gives each process a host id, made from a hash of the computer's IPv4 addresses at the moment the process starts. Two processes with the same host id use shared memory. Two with different ids believe they are on different computers and send UDP packets to each other over the loopback interface. For messages with guaranteed delivery, each side also sends acknowledgements and resends, and on a busy robot that turns into a storm.
That is exactly what happened to me. The base service started 4 seconds before the Wi-Fi had its address. Its nodes got one host id, and everything started later got another. Between the two groups every message went over UDP on loopback: 65,000 packets a second, 5,900 kernel receive-buffer overflows a second, and a load average of 30 with all eight cores at 85 to 95 percent. Restarting the early services so that all processes shared one id brought loopback traffic down to 330 packets a second.
Putting After=network-online.target in a service doesn't help here, because the service that would make that target wait is disabled on this system. The lasting fix is a short script that runs before the first ROS process at boot and waits until the list of addresses stops changing.
Once a second, for at most 45 seconds, the script builds one line from every IPv4 address except loopback, as interface=address pairs sorted and joined by commas. It counts how many seconds in a row that line has stayed the same. Six unchanged seconds means the network has settled: it prints the list and lets the service start. After 45 seconds it gives up and starts anyway, because the robot has to work with no Wi-Fi at all. It always exits 0, so it can delay the service but never stop it.
This is ~/setup/wait_addresses.sh:
#!/bin/bash
# Runs before the first ROS process (rosorin-base ExecStartPre). Fast DDS 2.6 gives each process a host id = MD5 of the
# machine's IPv4 addresses AT PROCESS START (src/cpp/utils/Host.hpp); processes with different ids do not use shared
# memory with each other and fall back to UDP on loopback. 2026-10-05: base started 4 s before Wi-Fi had its address
# -> two groups -> 65,000 packets/s, 5,900 kernel receive-buffer overflows/s, load average 30.
# Waits until the address list has been the same for 6 s (at most 45 s; the robot must also start without Wi-Fi).
prev=""; same=0
for i in $(seq 1 45); do
cur=$(ip -4 -o addr show | awk '$2!="lo"{print $2"="$4}' | sort | paste -sd,)
if [ -n "$cur" ] && [ "$cur" = "$prev" ]; then same=$((same+1)); else same=0; fi
[ $same -ge 6 ] && { echo "addresses stable after ${i}s: $cur"; exit 0; }
prev=$cur; sleep 1
done
echo "addresses not stable after 45 s (now: ${cur:-none}) - starting anyway"; exit 0
The script gets hooked into the base service by an installer that writes a systemd drop-in: a small file in /etc/systemd/system/rosorin-base.service.d/ whose lines are added to the service without editing the service file. ExecStartPre runs the wait before the service's own command, and TimeoutStartSec=120 gives the start enough time to include 45 seconds of waiting. This is ~/setup/install_dds_hostid_fix.sh:
#!/bin/bash
# rosorin-base waits for a stable IPv4 address list before any ROS process starts (scripts/wait_addresses.sh).
# Run on the robot: sudo bash ~/setup/install_dds_hostid_fix.sh
# Rollback: sudo rm -r /etc/systemd/system/rosorin-base.service.d/10-wait-addresses.conf; sudo systemctl daemon-reload
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "run with sudo"; exit 1; }
mkdir -p /etc/systemd/system/rosorin-base.service.d
cat > /etc/systemd/system/rosorin-base.service.d/10-wait-addresses.conf <<'UNIT'
[Service]
ExecStartPre=/bin/bash /home/burgerbarn/setup/wait_addresses.sh
TimeoutStartSec=120
UNIT
systemctl daemon-reload
systemctl cat rosorin-base | grep -A3 "10-wait-addresses"
Copy both files from your laptop:
scp -q ~/CCode/rosorin-pro/scripts/wait_addresses.sh ~/CCode/rosorin-pro/scripts/install_dds_hostid_fix.sh rosorin:setup/
Try the wait script on the robot:
bash ~/setup/wait_addresses.sh
Mine printed addresses stable after 7s: enP8p1s0=ROBOT_WIRED_IP/24,wlP1p1s0=ROBOT_WIFI_IP/24, Ethernet and Wi-Fi. Your list shows whatever interfaces your robot has at that moment. Don't run the installer yet. The base service doesn't exist until later in this chapter, and the installer would stop at its last line with No files found for rosorin-base.service. You run it right after installing the service.
The wheels, the arm servos, the IMU, the battery sensor, the buzzer and the gamepad receiver all hang off one STM32 controller board. The Jetson reaches every one of them through a single USB serial line, /dev/ttyACM0. The rest of this part teaches that line from zero, and you build rrc_protocol.py, the 70-line module that every later piece of driver code uses.
Why write it yourself? The factory software drove the board through Hiwonder's own node, and it had a bug that could silently disable all motor commands. It also rewrote the servo settings at every start. The protocol below was decoded from bytes captured on this robot, with Hiwonder's code read only as a reference, and checked against 788 of 788 captured frames. Nothing from the vendor runs on the board's side of this build.
A serial port sends bytes one bit after another over a wire, at an agreed speed called the baud rate, in bits per second. Linux shows each serial port as a file under /dev: you open it, read bytes and write bytes. USB devices of the communications class appear as /dev/ttyACM0, /dev/ttyACM1 and so on. The file belongs to the group dialout, so you need that group to open it, and chapter 3 gave it to your user. There's no message structure on a serial line, only a stream of bytes. Both ends must agree how to cut it into messages, and that agreement is the protocol.
Before you write anything to the board, know two things. First, the board has no stop watchdog. I once sent it one motor command and then nothing, and the wheels kept turning for the whole 5 seconds of the test until a zero arrived. Second, a motor frame with one wrong byte is a command to drive. So from the moment this chapter writes to the board, the robot sits on its stand with all four wheels off the ground, and your hand stays near the power switch. Reading is harmless, and that's where you start.
Check that the board is there:
lsusb | grep 1a86:55d4
ls -l /dev/ttyACM0
id -nG
On my robot:
Bus 001 Device 004: ID 1a86:55d4 QinHeng Electronics USB Single Serial
crw-rw---- 1 root dialout 166, 0 ... /dev/ttyACM0
and id -nG lists dialout among your groups. If there's no ttyACM0, the board isn't powered or its USB cable is loose. It uses the kernel's standard cdc_acm driver, so unlike the LiDAR it needs no extra module.
By default Linux treats a serial port as a text terminal. It echoes input, turns carriage returns into newlines and reacts to control characters such as Ctrl-C. For binary data every one of those changes corrupts bytes. Raw mode turns all of it off, so each byte arrives exactly as the board sent it.
Set the port to 1,000,000 baud in raw mode, record 2 seconds of what the board sends, and print the first bytes in hex:
mkdir -p ~/learn && cd ~/learn
stty -F /dev/ttyACM0 1000000 raw -echo && timeout 2 cat /dev/ttyACM0 > rrc.bin
stat -c "%s bytes in 2s" rrc.bin
xxd rrc.bin | head -6
Mine recorded 6934 bytes in 2 seconds. The first time I captured, the dump started like this:
00000000: aa55 0718 0000 253d 0000 6ebd 0098 713f .U....%=..n...q?
00000010: 0040 f8bf 0020 1bc0 0000 103d 8caa 5508 .@... .....=..U.
00000020: 0700 0000 0000 0000 8daa 5507 1800 0025 ..........U....%
00000030: 3d00 006e bd00 9871 3f00 80f2 bf00 e01b =..n...q?.......
00000040: c000 0088 3d12 aa55 0718 0000 253d 0000 ....=..U....%=..
00000050: 6ebd 0098 713f 0040 edbf 0060
Your bytes will differ, because the readings change, and your capture can start in the middle of a message. Find the first aa55. From there the pattern aa55 0718 repeats every 29 bytes, with a shorter aa55 0807 block in between. The board sends all of this unasked; nothing was written to it. If you get 0 bytes in 2s or Device or resource busy, another program holds the port, and sudo fuser -v /dev/ttyACM0 names it. If xxd is missing, it is its own package on Ubuntu 22.04: sudo apt-get install -y xxd.
To read those bytes you need two ideas. A byte is 8 bits, a number from 0 to 255, written in hex as two digits from 00 to ff. Numbers bigger than one byte take several bytes, and both ends must agree on their order. This board sends the least significant byte first, which is called little-endian. The two bytes 7e 31 therefore mean 0x317e, which is 12670. A 4-byte decimal number, a float32, uses the IEEE 754 format, also little-endian: 00 98 71 3f is 0x3f719800, which is 0.9437. Python's struct module does these conversions. '<H' is a little-endian unsigned 16-bit integer, '<f' a little-endian float32, and '<6f' six of them.
A frame is one message cut out of the byte stream. A receiver that starts listening in the middle of a message needs a way to find the next start, so this board marks every start with the two bytes AA 55. Then it says what the message is and how long it is, and it ends with a checksum. Every frame, in both directions, has this layout:
AA 55 | function (1 byte) | length n (1 byte) | payload (n bytes) | CRC-8/MAXIM over function, length, payload
Here's the first frame of the capture above, taken apart:
aa 55 start marker
07 function 7 = IMU report
18 length 0x18 = 24 payload bytes
00 00 25 3d accel x float32 = 0.0403 g
00 00 6e bd accel y float32 = -0.0581 g
00 98 71 3f accel z float32 = 0.9437 g
00 40 f8 bf gyro x float32 = -1.9395 deg/s
00 20 1b c0 gyro y float32 = -2.4238 deg/s
00 00 10 3d gyro z float32 = 0.0352 deg/s
8c CRC-8/MAXIM of "07 18" + the 24 payload bytes
The next frame, aa 55 08 07 00 00 00 00 00 00 00 8d, is a gamepad report, function 8, with 7 zero bytes: no controller input. The byte rate adds up. An IMU frame is 29 bytes at about 110 a second, a gamepad frame 12 bytes at 20 a second, and a battery frame 8 bytes once a second. That's about 3,440 bytes a second, which matches the capture.
The board streams three reports by itself. Function 0 is the system report: when its payload starts with 04, the next two bytes are the battery voltage in millivolts, as <H, and it comes about once a second. Function 7 is the IMU, six float32 numbers as <6f: acceleration on three axes in g and rotation rate on three axes in degrees per second, about 110 times a second. Function 8 is the gamepad, as <HB4b: a bit mask of the buttons, the hat switch, and four stick axes, about 20 times a second. Function 6 reports key presses on the board itself, but those keys can't be reached on the assembled robot. Function 5 carries servo commands and replies in both directions, for the arm in chapter 7. The Jetson sends two more. Function 2 is the buzzer, <HHHH: frequency in Hz, on time in milliseconds, off time in milliseconds, and repeat count. Function 3 is the motors: a 01, the motor count, and then for each motor its wire id from 0 to 3 as <B and a speed in revolutions per second as <f. The factory code knows a few more functions, for LEDs, a display and other servos, but nothing in this build uses them.
The module lives where its ROS 2 package gets built later in this chapter. Create the folders and the empty package marker:
mkdir -p ~/ros2_ws/src/rosorin_base/rosorin_base ~/ros2_ws/src/rosorin_base/test
touch ~/ros2_ws/src/rosorin_base/rosorin_base/__init__.py
Create ~/ros2_ws/src/rosorin_base/rosorin_base/rrc_protocol.py with the complete file below. The next sections go through it part by part, each with a short script that runs that part on bytes captured from the board.
"""Controller-board (STM32) serial protocol, as verified on this robot (docs/hardware.md).
Frame: 0xAA 0x55 | function | length | payload[length] | crc
crc = CRC-8/MAXIM (poly 0x31 reflected -> 0x8C, init 0) over function, length, payload.
"""
import struct
FUNC_SYS = 0
FUNC_IMU = 7
FUNC_GAMEPAD = 8
SYS_BATTERY = 0x04
def crc8_maxim(data: bytes) -> int:
c = 0
for b in data:
c ^= b
for _ in range(8):
c = (c >> 1) ^ 0x8C if c & 1 else c >> 1
return c
def encode_frame(func: int, payload: bytes) -> bytes:
body = bytes([func, len(payload)]) + bytes(payload)
return b'\xaa\x55' + body + bytes([crc8_maxim(body)])
class FrameParser:
"""Incremental parser: feed() bytes, get back (function, payload) for CRC-valid frames."""
def __init__(self):
self.buf = bytearray()
self.crc_errors = 0
def feed(self, data: bytes):
self.buf += data
out = []
while True:
i = self.buf.find(b'\xaa\x55')
if i < 0:
del self.buf[:-1]
return out
if i:
del self.buf[:i]
if len(self.buf) < 5:
return out
n = self.buf[3]
if len(self.buf) < 5 + n:
return out
body = bytes(self.buf[2:4 + n])
crc = self.buf[4 + n]
if crc == crc8_maxim(body):
out.append((body[0], body[2:]))
del self.buf[:5 + n]
else:
self.crc_errors += 1
del self.buf[:2]
def decode_imu(payload: bytes):
"""-> (ax, ay, az) in g, (gx, gy, gz) in deg/s."""
ax, ay, az, gx, gy, gz = struct.unpack('<6f', payload)
return (ax, ay, az), (gx, gy, gz)
def decode_battery_mv(payload: bytes):
"""-> battery millivolts, or None if not a battery report."""
if len(payload) == 3 and payload[0] == SYS_BATTERY:
return struct.unpack('<H', payload[1:])[0]
return None
Compare your file with the repository from your laptop:
cd ~/CCode/rosorin-pro
ssh rosorin cat ros2_ws/src/rosorin_base/rosorin_base/rrc_protocol.py | diff - ros2/rosorin_base/rosorin_base/rrc_protocol.py && echo same
It should print same. Anything else lists the lines where your file differs.
The top of the file is the header. The docstring is the frame format from the previous section. FUNC_SYS, FUNC_IMU and FUNC_GAMEPAD are the function numbers of the three reports the board streams, and SYS_BATTERY is the first payload byte of a battery report.
The scripts you write in ~/learn import the module from the package folder. Each one starts with the same two lines:
import sys
sys.path.insert(0, '/home/burgerbarn/ros2_ws/src/rosorin_base') # where rrc_protocol.py lives
A checksum is a small number computed from the bytes of a message and sent with it. The receiver computes it again, and if the two differ, a byte was damaged or lost, and the frame is thrown away. A plain sum misses many errors: two swapped bytes have the same sum. A CRC, short for cyclic redundancy check, mixes every bit into the result through shifts and XORs, so swaps and most bursts of damaged bits change it. There are many CRC variants. They differ in the polynomial, which decides which bits get mixed, the start value, and the bit order. This board uses CRC-8/MAXIM: 8 bits, polynomial 0x31 processed least significant bit first, which turns it into 0x8C, and start value 0.
That is all crc8_maxim does. For each byte, it XORs the byte into the running value c, then eight times shifts c one bit to the right, and whenever the bit that falls out is 1, it XORs in 0x8C. The CRC covers the function, the length and the payload, not the AA 55 start marker.
Try it on a battery report captured from the board. Create ~/learn/crc_check.py:
import sys
sys.path.insert(0, '/home/burgerbarn/ros2_ws/src/rosorin_base') # where rrc_protocol.py lives
from rosorin_base.rrc_protocol import crc8_maxim
body = bytes.fromhex('0003047e31') # function 0, length 3, payload 04 7e 31 (battery, captured from the board)
c = 0
for b in body: # the same steps as crc8_maxim, printed after each byte
c ^= b
for _ in range(8):
c = (c >> 1) ^ 0x8C if c & 1 else c >> 1
print(f'after {b:02x}: crc {c:02x}')
print('crc8_maxim(body) =', hex(crc8_maxim(body)))
print('check value =', hex(crc8_maxim(b'123456789')))
cd ~/learn && python3 crc_check.py
You should see exactly this:
after 00: crc 00
after 03: crc e2
after 04: crc 34
after 7e: crc 38
after 31: crc 9c
crc8_maxim(body) = 0x9c
check value = 0xa1
9c is the CRC the board sends after a battery report with the payload 04 7e 31. The 0xa1 for the text 123456789 is the published check value of CRC-8/MAXIM. When an implementation gives that value, its polynomial, bit order and start value are right. A wrong check value usually means 0x31 was used where 0x8C belongs, or the shift went left. No module named 'rosorin_base' means the sys.path line names another folder, or __init__.py is missing.
encode_frame puts a frame together: body is the function, the length and the payload, and the frame is AA 55, the body and the CRC of the body. Create ~/learn/encode_check.py, which builds the battery frame and the motor frame that stops all four wheels:
import struct
import sys
sys.path.insert(0, '/home/burgerbarn/ros2_ws/src/rosorin_base')
from rosorin_base.rrc_protocol import encode_frame
print('battery:', encode_frame(0, bytes.fromhex('047e31')).hex(' '))
# motor frame: sub-command 0x01, 4 motors, then (wire id 0..3, speed float32) per motor; all zero = STOP
stop = encode_frame(3, bytes([0x01, 4]) + b''.join(struct.pack('<Bf', i, 0.0) for i in range(4)))
print('stop: ', stop.hex(' '))
print('matches test_motion.py:', stop.hex() == 'aa5503160104000000000001000000000200000000030000000007')
cd ~/learn && python3 encode_check.py
battery: aa 55 00 03 04 7e 31 9c
stop: aa 55 03 16 01 04 00 00 00 00 00 01 00 00 00 00 02 00 00 00 00 03 00 00 00 00 07
matches test_motion.py: True
The stop frame is byte for byte the one in the package's motion tests, the frame that stopped the wheels the first time they ever turned under this code. Function 03, length 0x16, which is 22: sub-command 01 for "set speeds", 04 motors, and then four times a wire id from 00 to 03 and a float32 speed of 00 00 00 00.
A read from the port returns whatever bytes have arrived: half a frame, three frames and a bit, or a run of bytes from the middle of a frame you missed. The parser keeps a buffer and cuts whole, checked frames out of it.
FrameParser starts with an empty buffer and a CRC error count of 0. Each call to feed() appends the new bytes to the buffer and then loops. It looks for AA 55. If there's none, it throws the buffer away except its last byte, which might be the AA of a marker whose 55 hasn't arrived yet. Otherwise it throws away anything before the marker. A frame is at least 5 bytes, so with fewer it waits for more data. Then it reads the length and waits until the whole frame is there. It computes the CRC of function, length and payload and compares it with the byte after the payload. If they match, it returns the function and payload and removes the frame from the buffer. If they don't match, it counts a CRC error, removes only the two marker bytes, and searches again.
That last rule is the important one. AA 55 can also occur inside a payload, since a float can contain those two bytes. A parser that trusts the first marker it sees, or skips a whole "frame" after a bad one, loses real frames or invents fake ones. Dropping only the two marker bytes keeps the next real marker in the buffer.
Feed the parser the first 92 bytes of the capture. Create ~/learn/parse_capture.py:
import sys
sys.path.insert(0, '/home/burgerbarn/ros2_ws/src/rosorin_base')
from rosorin_base.rrc_protocol import FrameParser
# the first 92 bytes read from /dev/ttyACM0 (the xxd dump above)
CAPTURE = bytes.fromhex(
'aa5507180000253d00006ebd0098713f0040f8bf00201bc00000103d8c'
'aa550807000000000000008d'
'aa5507180000253d00006ebd0098713f0080f2bf00e01bc00000883d12'
'aa5507180000253d00006ebd0098713f0040edbf0060')
p = FrameParser()
for func, payload in p.feed(CAPTURE):
print('function', func, 'length', len(payload), payload.hex(' '))
print('crc errors:', p.crc_errors, '| bytes waiting for the rest of a frame:', len(p.buf))
bad = bytearray(CAPTURE)
bad[28] ^= 0xFF # damage the CRC byte of the first frame
p = FrameParser()
print('damaged:', [func for func, _ in p.feed(bytes(bad))], '| crc errors:', p.crc_errors)
cd ~/learn && python3 parse_capture.py
function 7 length 24 00 00 25 3d 00 00 6e bd 00 98 71 3f 00 40 f8 bf 00 20 1b c0 00 00 10 3d
function 8 length 7 00 00 00 00 00 00 00
function 7 length 24 00 00 25 3d 00 00 6e bd 00 98 71 3f 00 80 f2 bf 00 e0 1b c0 00 00 88 3d
crc errors: 0 | bytes waiting for the rest of a frame: 22
damaged: [8, 7] | crc errors: 1
Two IMU frames and a gamepad frame come out whole. The last 22 bytes are the start of a fourth frame that the capture cut off, and the parser keeps them and waits. With the first frame's CRC damaged, that frame is dropped and counted, and the parser still finds the next two.
An IMU, short for inertial measurement unit, measures acceleration along three axes with an accelerometer and the rotation rate around three axes with a gyroscope. The board's IMU is an MPU6050. At rest the accelerometer reads gravity, about 1 g pointing up. The gyroscope should read zero, but it doesn't: each axis has an offset, called its bias. On my robot the gyro read about -1.9, -2.2 and +0.05 degrees per second while standing still, and the bias was different after the next boot. The driver measures it at every start and subtracts it.
The last two functions of the module are the decoders. decode_imu unpacks the 24 bytes as six little-endian floats, and decode_battery_mv reads the two bytes after the battery marker byte as a little-endian 16-bit number. It returns None for any system report that isn't a battery report, so callers can test for it. decode_imu returns the board's own units, g and degrees per second. ROS messages use m/s^2 and rad/s, and the driver converts them.
Create ~/learn/decode_check.py:
import sys
sys.path.insert(0, '/home/burgerbarn/ros2_ws/src/rosorin_base')
from rosorin_base.rrc_protocol import decode_battery_mv, decode_imu
print('battery mV:', decode_battery_mv(bytes.fromhex('047e31')))
print('other sys report:', decode_battery_mv(bytes.fromhex('0101')))
(ax, ay, az), (gx, gy, gz) = decode_imu(bytes.fromhex('0000253d00006ebd0098713f0040f8bf00201bc00000103d'))
print(f'accel g: {ax:+.4f} {ay:+.4f} {az:+.4f}')
print(f'gyro deg/s: {gx:+.4f} {gy:+.4f} {gz:+.4f}')
cd ~/learn && python3 decode_check.py
battery mV: 12670
other sys report: None
accel g: +0.0403 -0.0581 +0.9437
gyro deg/s: -1.9395 -2.4238 +0.0352
12670 mV is 12.67 V, with the charger plugged in. The accelerometer's total comes to about 0.946 g, not 1.000 g: the raw IMU is off by about 5 percent. The driver applies a calibration file that fixes it.
A unit test is a small function that calls your code with known input and checks the result. The three tests for this module use a real battery frame from the robot, a damaged frame, and a frame split across two reads. Create ~/ros2_ws/src/rosorin_base/test/test_rrc_protocol.py:
from rosorin_base.rrc_protocol import FrameParser, crc8_maxim, decode_battery_mv
def frame(func, payload):
body = bytes([func, len(payload)]) + payload
return b'\xaa\x55' + body + bytes([crc8_maxim(body)])
def test_battery_frame_from_robot():
# real frame captured 2026-09-26: func 0, payload 04 7e 31
p = FrameParser()
out = p.feed(frame(0, bytes.fromhex('047e31')))
assert out == [(0, bytes.fromhex('047e31'))]
assert decode_battery_mv(out[0][1]) == 12670
def test_bad_crc_rejected_and_resync():
good = frame(8, bytes(7))
bad = bytearray(good); bad[-1] ^= 0xFF
p = FrameParser()
out = p.feed(bytes(bad) + b'\x00\x13' + good)
assert out == [(8, bytes(7))] and p.crc_errors == 1
def test_split_across_reads():
f = frame(7, bytes(24))
p = FrameParser()
assert p.feed(f[:10]) == []
assert p.feed(f[10:]) == [(7, bytes(24))]
The first test feeds in the real battery payload and expects the same payload and 12670 mV back. The second sends a gamepad frame with a broken CRC, two junk bytes and then a good copy, and expects only the good copy and exactly one CRC error. The third feeds the first 10 bytes of an IMU frame, expects nothing, then feeds the rest and expects the frame. Run them:
cd ~/ros2_ws/src/rosorin_base
python3 -m pytest -q test/test_rrc_protocol.py
It ends with 3 passed. Run it from that folder with python3 -m pytest, as shown. The -m form puts the current folder on Python's import path so rosorin_base is found, and the system has no plain pytest command.
Now open the real port from Python. ~/learn/rrc_read.py reads for a few seconds, prints each battery report and one IMU reading a second, and counts frames per function. Its open_raw_readonly is the same function the driver package's read-only node uses. Create ~/learn/rrc_read.py:
"""Read the controller board for a few seconds and print what it reports. Read-only: never writes to it."""
import collections
import fcntl
import os
import sys
import termios
import time
sys.path.insert(0, '/home/burgerbarn/ros2_ws/src/rosorin_base')
from rosorin_base.rrc_protocol import FUNC_IMU, FUNC_SYS, FrameParser, decode_battery_mv, decode_imu
def open_raw_readonly(dev, baud):
fd = os.open(dev, os.O_RDONLY | os.O_NOCTTY)
fcntl.ioctl(fd, termios.TIOCEXCL) # single owner: further opens get EBUSY
a = termios.tcgetattr(fd)
a[0] = 0 # iflag
a[1] = 0 # oflag
a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
a[3] = 0 # lflag
a[4] = a[5] = baud
a[6][termios.VMIN] = 1
a[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, a)
return fd
secs = float(sys.argv[1]) if len(sys.argv) > 1 else 5.0
fd = open_raw_readonly('/dev/ttyACM0', termios.B1000000)
parser, count, t0, shown = FrameParser(), collections.Counter(), time.time(), 0
while time.time() - t0 < secs:
for func, payload in parser.feed(os.read(fd, 512)):
count[func] += 1
if func == FUNC_SYS and decode_battery_mv(payload) is not None:
print('battery', decode_battery_mv(payload), 'mV')
elif func == FUNC_IMU and len(payload) == 24 and time.time() - t0 >= shown:
(ax, ay, az), (gx, gy, gz) = decode_imu(payload)
print(f'imu accel g {ax:+.3f} {ay:+.3f} {az:+.3f} gyro deg/s {gx:+.2f} {gy:+.2f} {gz:+.2f}')
shown += 1 # one IMU line per second
os.close(fd)
print('frames per second by function:', {f: round(n / secs, 1) for f, n in sorted(count.items())},
'| crc errors:', parser.crc_errors)
The way it opens the port matters. O_RDONLY means this script can't write to the board, so it can't move anything. O_NOCTTY stops the port from becoming the script's controlling terminal, which could send it signals. TIOCEXCL is exclusive mode: any later open of the port by another process fails until this one closes it. Setting the input, output and local flags to 0 gives raw mode, CS8 | CREAD | CLOCAL means 8 data bits, receiver on and modem lines ignored, both speeds are B1000000, and VMIN 1, VTIME 0 makes os.read wait until at least one byte is there.
cd ~/learn && python3 rrc_read.py 5
On my robot it printed lines like these:
imu accel g +0.039 -0.068 +0.943 gyro deg/s -2.30 -3.06 +0.04
battery 12663 mV
...
frames per second by function: {0: 1.0, 7: 112.6, 8: 20.4} | crc errors: 1
The IMU should be close to 110 frames a second, the accelerometer's z about +0.94 g with the robot level, and the gyro a couple of degrees per second off zero at rest. The battery value depends on the charge: 12.6 to 12.7 V on the charger, around 11 V after a couple of hours unplugged.
You may see 1 or 2 CRC errors, like I did. I traced mine: every one came from the very first read after opening the port, which can start with a frame cut short by bytes left over from before the open. In the following 10 seconds there were none in about 1,320 frames. That's normal. CRC errors that keep coming while the read runs are a real fault, and the first thing to check is a second program reading the port.
Start a 20 second read in one SSH session:
cd ~/learn && python3 rrc_read.py 20
While it runs, try to open the port from a second session:
python3 -c "import os; os.open('/dev/ttyACM0', os.O_RDONLY|os.O_NOCTTY)" 2>&1 | tail -1
It fails with:
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM0'
This lock exists because of a fault that reported nothing. Once, a measuring script and a forgotten copy of a reader both had the port open. Neither failed. Each got part of the byte stream, and the measuring script counted 60 IMU frames a second instead of 110. Only the rate gave it away. Since then every program in this build opens the board exclusively, and a second opener fails at once. If you ever see the IMU at around 60 a second, look for a second reader with fuser.
Writing needs the port opened read-write. ~/learn/rrc_send.py sends one of three sets of frames: a beep, two "buzzer off" frames, or the stop frame three times. Create it:
"""Send frames to the controller board. Usage: rrc_send.py beep | off | stop"""
import fcntl
import os
import struct
import sys
import termios
import time
sys.path.insert(0, '/home/burgerbarn/ros2_ws/src/rosorin_base')
from rosorin_base.rrc_protocol import encode_frame
FUNC_BUZZER = 2
FUNC_MOTOR = 3
STOP = encode_frame(FUNC_MOTOR, bytes([0x01, 4]) + b''.join(struct.pack('<Bf', i, 0.0) for i in range(4)))
assert STOP.hex() == 'aa5503160104000000000001000000000200000000030000000007' # test/test_motion.py
FRAMES = {
# buzzer payload <HHHH: frequency Hz, on ms, off ms, repeat. Never an off time of 0 (the stuck buzzer).
'beep': [encode_frame(FUNC_BUZZER, struct.pack('<HHHH', 1800, 90, 100, 1))],
# the two frames that silenced the stuck buzzer
'off': [encode_frame(FUNC_BUZZER, struct.pack('<HHHH', 0, 0, 0, 0)),
encode_frame(FUNC_BUZZER, struct.pack('<HHHH', 1000, 0, 0, 0))],
'stop': [STOP, STOP, STOP],
}
frames = FRAMES[sys.argv[1]]
fd = os.open('/dev/ttyACM0', os.O_RDWR | os.O_NOCTTY)
fcntl.ioctl(fd, termios.TIOCEXCL)
a = termios.tcgetattr(fd); a[0] = a[1] = a[3] = 0; a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL; a[4] = a[5] = termios.B1000000
termios.tcsetattr(fd, termios.TCSANOW, a)
for f in frames:
os.write(fd, f)
print('sent', f.hex(' '))
time.sleep(0.05)
os.close(fd)
The buzzer can stick on, and that's why the off entry exists. Once, the driver sent tones with an off time of 0, and afterwards the buzzer sounded without stopping. It only stopped when the driver was stopped and two raw frames were written: (0, 0, 0, 0) and then (1000, 0, 0, 0). The likely cause is that the firmware loops on an off time of 0, but I haven't proven that. Since then every tone uses a 100 ms off time, like the factory examples.
Put the robot on its stand for this, and be at the robot so you can hear it. Before you send the beep, open a second session and type cd ~/learn && python3 rrc_send.py off without pressing Enter, so it's ready if the tone doesn't stop. Then:
cd ~/learn && python3 rrc_send.py beep
It prints the frame and the robot gives one short tone that stops by itself:
sent aa 55 02 08 08 07 5a 00 64 00 01 00 fa
The payload 08 07 is 1800 Hz, 5a 00 is 90 ms on, 64 00 is 100 ms off, and 01 00 means once. That's the same frame the driver writes for its own tones. If the tone doesn't stop, press Enter in the second session. The off command prints aa 55 02 08 00 00 00 00 00 00 00 00 d8 and aa 55 02 08 e8 03 00 00 00 00 00 00 c6. If you hear nothing and get no error, run python3 rrc_read.py 2: the board doesn't answer buzzer frames, but if reports still arrive, the link is fine.
The stop frame commands 0 revolutions per second on all four motors, but it is still a motor frame, and it's the first one this build writes. The robot stays on its stand with all four wheels free, and your hand is on the power switch. With the wheels already still, nothing visible happens, and that's what you want. If any wheel turns, switch the robot off.
For comparison, here is the frame that drove the wheels in my very first motion test, 0.3 revolutions per second on all four. It's only for reading, not for sending. 9a 99 99 3e is 0.3 as a float32:
aa 55 03 16 01 04 00 9a 99 99 3e 01 9a 99 99 3e 02 9a 99 99 3e 03 9a 99 99 3e 46
Send the stop frame three times, then read the board:
cd ~/learn && python3 rrc_send.py stop
python3 rrc_read.py 2
The script prints the same line three times:
sent aa 55 03 16 01 04 00 00 00 00 00 01 00 00 00 00 02 00 00 00 00 03 00 00 00 00 07
No wheel moves. rrc_read.py 2 still prints IMU and battery values; mine ended with {0: 1.0, 7: 113.5, 8: 20.5} | crc errors: 0. Writing to the board didn't disturb its reports. If the script stops at the start with an AssertionError, the stop frame it built isn't the one from the tests: don't send anything, and compare rrc_protocol.py with the repository again.
Writing raw frames by hand stops here. From now on only the driver writes to the port, and a separate small program sends this stop frame whenever the driver is gone.
The board driver is the robot's safety layer. Because the board keeps the last wheel speed forever, every way this software can fail has to end in a stop frame. Before any code wrote to the board, I set down the rules it follows, and everything that comes next implements one of them.
The driver is the only process that opens /dev/ttyACM0, with the exclusive lock. The wheels listen to one input only, the cmd_vel topic, and if more than one program publishes on it, the driver stops and refuses. After any start, motion stays off until an explicit enable call. If no command arrives for 0.3 seconds, the speed goes to zero. Speed and acceleration are limited. An emergency stop latches, and only an explicit reset clears it. If the driver dies for any reason, a stop frame follows at once, a second one comes from systemd, and the restarted driver comes back disabled. And the driver never writes to the arm servos' memory.
A deadman stops the machine when the controlling signal goes quiet. The commands have to keep coming, here at least every 0.3 seconds, and silence means stop. It covers a crashed planner, a lost network link or a hung script. An e-stop, short for emergency stop, is a stop that someone or something asks for. Latched means it stays in force after the request ends: a single true on the estop topic stops the wheels until someone deliberately resets it, and even then the wheels stay disabled until they're enabled again.
ROS 2 code is organised in packages. A package is a folder with a package.xml, which gives its name, version and dependencies, and build instructions. A workspace is a folder with a src/ subfolder full of packages, here ~/ros2_ws. colcon builds every package in src/ into install/, and sourcing install/setup.bash makes them visible to the ros2 command on top of the system ROS. This one is an ament_python package: a Python package with a setup.py. Building it copies the modules, creates one small program per entry point, and installs the data files, such as launch files and configuration, where ROS tools can find them by the package's name.
You already have rrc_protocol.py and its test in ~/ros2_ws/src/rosorin_base. The finished package also holds the motion logic, the gyro bias code and the stop tool, which you type in this chapter, and the driver itself plus parts that later chapters explain, which you copy. Create the remaining folders and the package marker:
mkdir -p ~/ros2_ws/src/rosorin_base/{resource,launch,systemd}
touch ~/ros2_ws/src/rosorin_base/resource/rosorin_base
The empty file resource/rosorin_base is how ROS finds the package by name once it's installed.
setup.py lists every launch file, configuration file and program of the finished package, and the driver imports the arm modules. For the build to work now, those files have to exist. Copy them from your clone of the repository on your laptop:
cd ~/CCode/rosorin-pro/ros2/rosorin_base
scp -r config bt urdf rosorin:ros2_ws/src/rosorin_base/
scp launch/nav.launch.py launch/nav_slam.launch.py launch/slam.launch.py rosorin:ros2_ws/src/rosorin_base/launch/
scp rosorin_base/board_driver.py rosorin_base/arm.py rosorin_base/arm_model.py rosorin_base/coin_d6.py \
rosorin_base/lidar_reader.py rosorin_base/board_reader.py rosorin_base/gamepad_teleop.py \
rosorin_base/rf2o_fix.py rosorin_base/vslam_odom.py rosorin_base/depth_gate.py \
rosorin_base/nav_supervisor.py rosorin_base/learned_limits.py rosorin:ros2_ws/src/rosorin_base/rosorin_base/
scp test/test_motion.py test/test_gyro_bias.py test/test_arm.py test/test_coin_d6.py test/coin_d6_sample.bin \
test/test_gamepad_teleop.py rosorin:ros2_ws/src/rosorin_base/test/
If scp says No such file or directory, a target folder on the robot is missing; run the mkdir above first. Three of the copied configuration files matter now. config/imu_calibration.yaml is the accelerometer calibration. config/arm_limits.yaml holds the arm's limits and poses and the wheel speed limit, max_linear: 0.35. config/robot_model.json is the arm geometry the driver loads at start for its collision check.
Create ~/ros2_ws/src/rosorin_base/package.xml:
<?xml version="1.0"?>
<package format="3">
<name>rosorin_base</name>
<version>0.1.0</version>
<description>ROSOrin base drivers written from the documented controller-board protocol. No vendor code.</description>
<maintainer email="you@example.com">burgerbarn</maintainer>
<license>MIT</license>
<exec_depend>rclpy</exec_depend>
<exec_depend>control_msgs</exec_depend>
<exec_depend>python3-numpy</exec_depend>
<exec_depend>sensor_msgs</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>robot_localization</exec_depend>
<exec_depend>slam_toolbox</exec_depend>
<exec_depend>navigation2</exec_depend>
<exec_depend>std_msgs</exec_depend>
<exec_depend>std_srvs</exec_depend>
<exec_depend>tf2_ros</exec_depend>
<exec_depend>robot_state_publisher</exec_depend>
<exec_depend>launch_ros</exec_depend>
<test_depend>python3-pytest</test_depend>
<export><build_type>ament_python</build_type></export>
</package>
exec_depend lists what has to be installed to run the package, and you installed all of it earlier in this chapter. test_depend is what the tests need. colcon doesn't check any of them, so a missing one only shows when the program starts. Put your own e-mail address in the maintainer line, without angle brackets. Angle brackets make the file invalid XML, and then colcon quietly builds the package as plain Python and ROS can't find it by name.
Create ~/ros2_ws/src/rosorin_base/setup.cfg:
[develop]
script_dir=$base/lib/rosorin_base
[install]
install_scripts=$base/lib/rosorin_base
This puts the generated programs in install/rosorin_base/lib/rosorin_base/, the folder where ros2 run and ros2 launch look for a package's programs.
Create ~/ros2_ws/src/rosorin_base/setup.py:
from setuptools import setup
setup(
name='rosorin_base',
version='0.1.0',
packages=['rosorin_base'],
data_files=[
('share/ament_index/resource_index/packages', ['resource/rosorin_base']),
('share/rosorin_base', ['package.xml']),
('share/rosorin_base/launch', ['launch/base.launch.py', 'launch/slam.launch.py', 'launch/nav.launch.py', 'launch/nav_slam.launch.py']),
('share/rosorin_base/config', ['config/imu_calibration.yaml', 'config/arm_limits.yaml', 'config/ekf.yaml', 'config/slam.yaml', 'config/nav2.yaml', 'config/collision_monitor.yaml', 'config/robot_model.json', 'config/rf2o.yaml', 'config/nvblox.yaml', 'config/explore.yaml']),
('share/rosorin_base/bt', ['bt/navigate_no_backup.xml']),
('share/rosorin_base/urdf', ['urdf/rosorin.urdf']),
],
install_requires=['setuptools'],
entry_points={'console_scripts': ['board_reader = rosorin_base.board_reader:main',
'lidar_reader = rosorin_base.lidar_reader:main',
'board_driver = rosorin_base.board_driver:main',
'stop_motors = rosorin_base.stop_motors:main',
'gamepad_teleop = rosorin_base.gamepad_teleop:main',
'rf2o_fix = rosorin_base.rf2o_fix:main',
'vslam_odom = rosorin_base.vslam_odom:main',
'depth_gate = rosorin_base.depth_gate:main',
'nav_supervisor = rosorin_base.nav_supervisor:main',
'nav_wait = rosorin_base.nav_supervisor:wait_main']},
)
packages names the folder of Python modules. Each entry in data_files pairs a target folder under install/rosorin_base/ with a list of source files: the package marker goes into ROS's package index, and package.xml, the launch files, the configuration, the behaviour tree and the robot description go under share/rosorin_base/, where code finds them by package name. Files not listed here aren't installed. In entry_points, each line name = module:function becomes a program called name that calls function(). This chapter uses board_driver, stop_motors and lidar_reader.
motion.py holds all of the motion logic as plain Python, with no ROS and no serial port. That makes it testable on any computer. The driver only feeds it inputs and the clock.
ROS describes how a robot should move with three numbers in a geometry_msgs/Twist message: linear.x is the forward speed in m/s, linear.y the sideways speed in m/s, positive to the left, and angular.z the turn rate in rad/s, positive counter-clockwise seen from above. They're measured in the robot's own frame, called base_link, with x forward, y left and z up. The topic for it is cmd_vel.
The robot has mecanum wheels. A mecanum wheel has small rollers around its rim at 45 degrees, so each wheel pushes the robot partly forward and partly sideways. By choosing the four wheel speeds, the robot can drive forward, slide sideways, turn on the spot, or any mix of those. Kinematics is the formula from the body velocity (vx, vy, wz) to the four wheel speeds. For this chassis, with k = (wheelbase + track) / 2 = (0.17706 + 0.17165) / 2 m: motor1 = vx - vy - wz k, motor2 = vx + vy - wz k, motor3 = -(vx + vy + wz k), and motor4 = -(vx - vy + wz k), each in m/s at the wheel rim. Dividing by the wheel circumference, pi times 0.08 m, gives revolutions per second, the unit the board takes.
The file starts with two helpers. clamp limits a value to plus or minus a limit. ramp moves the current value toward a target by at most one step, so that called every tick, it turns a jump in the command into a slope. joy_to_twist maps gamepad sticks to a velocity for an optional teleop node. integrate_pose advances a pose by a body velocity, for the wheel odometry: it turns the body velocity into a step in the world using the heading halfway through the time step, and keeps the heading between -pi and pi.
mecanum_rps is the formula above, with the signs of motors 3 and 4 applied at the end. Forward at 0.2 m/s gives [0.796, 0.796, -0.796, -0.796] revolutions per second. Turning at 1.0 rad/s gives -0.694 on all four, because the motors on one side are mounted mirrored, so the same sign on the wire turns the two sides opposite ways. Sliding left at 0.2 m/s gives [-0.796, 0.796, -0.796, 0.796]. motor_frame builds the motor frame, and STOP_FRAME is the stop frame, the same bytes you built by hand earlier.
MotionGate decides every tick what body velocity the wheels get. Its rule: speeding up is gradual, stopping is immediate. Its limits default to 0.2 m/s and 1.0 rad/s, with 0.5 m/s^2 and 2.0 rad/s^2 of acceleration and a 0.3 second deadman. It starts disabled and with no e-stop.
It has a handful of inputs. set_cmd stores the latest command and when it arrived, and manual=True marks a gamepad command. sensed records when the LiDAR last delivered a scan. trip latches an e-stop: it keeps the first reason, disables motion and zeroes the current speed at once. reset clears the latch and nothing else, so motion stays disabled. enable(True) is refused while an e-stop is latched, and enable(False) zeroes the speed.
block_reason says why the wheels are blocked, checking in this order: a latched e-stop, then disabled, then cmd timeout if there's no command yet or the last one is older than the deadman, and last no scan. That last one is the scan gate: with it on, a command from software is blocked unless the LiDAR delivered a scan within the last 0.5 seconds. I added it when I found that the stock Nav2 collision monitor in Humble passes commands through unchanged when the LiDAR goes silent. I measured 0.2 m/s in and 0.2 m/s out with a wall at the robot's nose. The scan gate isn't latched; motion resumes when scans come back. Gamepad commands are exempt, because a person holding the pad is watching and must be able to move a robot whose LiDAR has died.
step is one tick. Any block reason gives zero at once, with no ramp. Otherwise the command is clamped to the limits and the current speed moves toward it by at most acceleration times the time step. At 50 Hz and 0.5 m/s^2 that's 0.01 m/s per tick.
Create ~/ros2_ws/src/rosorin_base/rosorin_base/motion.py with the complete file:
"""Pure motion logic (no ROS, no I/O) - see docs/motion_safety.md."""
import math
import struct
from rosorin_base.rrc_protocol import crc8_maxim
FUNC_MOTOR = 3
def clamp(v, lim):
return max(-lim, min(lim, v))
def ramp(cur, tgt, max_step):
return cur + clamp(tgt - cur, max_step)
def joy_to_twist(axes, max_lin, max_ang, deadzone=0.1):
"""Gamepad axes, raw order (lx, ly, rx, ry, ...) each raw/127 -> (vx, vy, wz). Factory default layout."""
lx, ly, rx = (0.0 if abs(v) < deadzone else max(-1.0, min(1.0, v)) for v in axes[:3])
return ly * max_lin, -lx * max_lin, -rx * max_ang
def integrate_pose(x, y, th, vx, vy, wz, dt):
"""Advance a planar pose by body velocity over dt (midpoint heading)."""
h = th + wz * dt / 2.0
c, s = math.cos(h), math.sin(h)
x += (vx * c - vy * s) * dt
y += (vx * s + vy * c) * dt
th = math.atan2(math.sin(th + wz * dt), math.cos(th + wz * dt))
return x, y, th
def mecanum_rps(vx, vy, wz, wheel_d=0.08, wheelbase=0.17706, track=0.17165):
"""Body velocity (m/s, m/s, rad/s) -> wheel rps for motors 1..4 (factory layout/signs)."""
k = (wheelbase + track) / 2.0
m1 = vx - vy - wz * k
m2 = vx + vy - wz * k
m3 = vx + vy + wz * k
m4 = vx - vy + wz * k
c = math.pi * wheel_d
return [m1 / c, m2 / c, -m3 / c, -m4 / c]
def motor_frame(rps):
"""rps for motors 1..4 -> board frame (func 3, sub 0x01, wire ids 0..3)."""
payload = bytes([0x01, len(rps)]) + b''.join(struct.pack('<Bf', i, float(r)) for i, r in enumerate(rps))
body = bytes([FUNC_MOTOR, len(payload)]) + payload
return b'\xaa\x55' + body + bytes([crc8_maxim(body)])
STOP_FRAME = motor_frame([0.0, 0.0, 0.0, 0.0])
class MotionGate:
"""Decides the commanded body velocity each tick. Safety stops are immediate (no ramp)."""
def __init__(self, max_lin=0.2, max_ang=1.0, acc_lin=0.5, acc_ang=2.0, timeout=0.3, sense_timeout=0.0):
self.max_lin, self.max_ang = max_lin, max_ang
self.acc_lin, self.acc_ang = acc_lin, acc_ang
self.timeout = timeout
# Sensing gate (2026-10-02): commands from software (cmd_vel) move the wheels only while the obstacle sensor
# is alive. On Humble the Nav2 collision monitor IGNORES a stale scan and passes commands through unchanged
# (measured, scripts/tests/nav2_isolated_checks.sh), and the contact reflex runs off LiDAR odometry, so a
# silent LiDAR removed every guard at once. 0 = off. Not latched: motion resumes when the sensor is back.
# Gamepad commands (manual=True) are exempt: a person holding the pad is looking.
self.sense_timeout = sense_timeout
self.sense_t = None
self.enabled = False # disabled at start (rule 3)
self.estop = None # None or reason string (latched, rule 6)
self.cmd = (0.0, 0.0, 0.0)
self.cmd_t = None
self.cmd_manual = False
self.cur = (0.0, 0.0, 0.0)
def set_cmd(self, vx, vy, wz, now, manual=False):
self.cmd = (vx, vy, wz)
self.cmd_t = now
self.cmd_manual = manual
def sensed(self, now):
"""The obstacle sensor delivered data (the LiDAR published a scan)."""
self.sense_t = now
def trip(self, reason):
if self.estop is None:
self.estop = reason
self.enabled = False
self.cur = (0.0, 0.0, 0.0)
def reset(self):
self.estop = None # motion stays disabled until enabled again
def enable(self, on):
if on and self.estop is not None:
return False
self.enabled = on
if not on:
self.cur = (0.0, 0.0, 0.0)
return True
def block_reason(self, now):
if self.estop is not None:
return 'estop: ' + self.estop
if not self.enabled:
return 'disabled'
if self.cmd_t is None or now - self.cmd_t > self.timeout:
return 'cmd timeout'
if self.sense_timeout > 0 and not self.cmd_manual and (
self.sense_t is None or now - self.sense_t > self.sense_timeout):
return 'no scan'
return None
def step(self, now, dt):
if self.block_reason(now) is not None:
self.cur = (0.0, 0.0, 0.0)
return self.cur
vx, vy, wz = self.cmd
tgt = (clamp(vx, self.max_lin), clamp(vy, self.max_lin), clamp(wz, self.max_ang))
self.cur = (ramp(self.cur[0], tgt[0], self.acc_lin * dt),
ramp(self.cur[1], tgt[1], self.acc_lin * dt),
ramp(self.cur[2], tgt[2], self.acc_ang * dt))
return self.cur
The motion tests you copied check that STOP_FRAME is exactly the byte string that stopped the wheels, that a motor frame passes your own parser, the kinematics signs, no motion before enable and zero 0.31 seconds after the last command, clamping and a first tick of 0.01 m/s, that an e-stop refuses enable and reset leaves the gate disabled, the pose integration, and the scan gate. Run them:
cd ~/ros2_ws/src/rosorin_base
python3 -m pytest -q test/test_motion.py
It ends with 9 passed.
The gyro reads a couple of degrees per second while standing still, and that offset is its bias. The driver measures it at start, from the first 3 second window in which the robot stands still. That isn't enough on its own. The leftover bias wanders by about 0.01 degrees per second over tens of seconds, and before I handled it the heading estimate drifted 11.4 degrees in about 8 minutes. So a second piece keeps following the bias whenever the robot is commanded to stand still.
StartupCalibration gives the first bias. It collects samples for 3 seconds. If every axis's standard deviation is at most 0.3 degrees per second, the window was still, and its mean is the bias. Otherwise the window is dropped, counted in failed, and the next 3 seconds are tried. That retry matters. My first version tried one window only. Then one day the robot was carried while it booted, the only window failed, and the bias stayed at 0 for the whole boot. The heading drifted 2.1 degrees in 43 seconds at rest. With the retry, the same robot drifted 0.15 degrees in 62 seconds.
GyroBiasTracker follows the bias from then on. It is told when the commanded velocity became zero, and once it has stayed zero for 1 second, every gyro sample that reads within 0.5 degrees per second of the current bias moves the bias toward the reading by a small fraction, with a time constant of 20 seconds. A push or a turn by hand reads far more than 0.5 degrees per second and is ignored, and while driving the bias is frozen. That same rule is why the retry above is needed: starting from a bias of 0, the tracker rejects a real bias of 2 degrees per second and never learns it.
Create ~/ros2_ws/src/rosorin_base/rosorin_base/gyro_bias.py:
"""Gyro bias tracking while the robot is commanded still, and the startup calibration (pure logic, no ROS).
Startup calibration gives the initial bias; the residual wanders (measured 2026-09-27: +-0.01 deg/s
over tens of seconds -> EKF heading drift equal to the gyro integral). While the commanded velocity
has been zero for `settle` s AND every axis reads within `max_dev` of the current bias (rejects
the robot being pushed/turned by hand), the bias follows the reading with time constant `tau`.
"""
import statistics
class StartupCalibration:
"""The bias from the first still window (secs long, every axis' std <= max_std). A window that is not still is
dropped and the next one tried (the robot was carried at boot, the single window
failed, the bias stayed 0 and GyroBiasTracker - which learns only within max_dev of the bias - never took over;
the heading drifted ~3 deg/min standing still and things placed in the map swung ~1 m)."""
def __init__(self, secs=3.0, max_std=0.3):
self.secs, self.max_std = secs, max_std
self.samples, self.t0, self.failed, self.done = [], None, 0, False
def add(self, g, now):
"""g: raw gyro (deg/s, 3 axes). -> (bias, stds): bias when a still window just ended (then done), stds when
any window just ended, else (None, None)."""
if self.done:
return None, None
if self.t0 is None:
self.t0 = now
self.samples.append(tuple(g))
if now - self.t0 < self.secs:
return None, None
stds = [statistics.pstdev(c[i] for c in self.samples) for i in range(3)]
if max(stds) <= self.max_std:
self.done = True
return [statistics.mean(c[i] for c in self.samples) for i in range(3)], stds
self.failed += 1
self.samples, self.t0 = [], None
return None, stds
class GyroBiasTracker:
def __init__(self, bias=(0.0, 0.0, 0.0), tau=20.0, settle=1.0, max_dev=0.5):
self.bias = list(bias)
self.tau, self.settle, self.max_dev = tau, settle, max_dev
self.still_since = None
self.last_t = None
def set_commanded_still(self, still, now):
if not still:
self.still_since = None
elif self.still_since is None:
self.still_since = now
def tracking(self, now):
return self.still_since is not None and now - self.still_since >= self.settle
def update(self, g, now):
"""g: raw gyro (deg/s, 3 axes). Returns bias-corrected gyro."""
dt = 0.0 if self.last_t is None else now - self.last_t
self.last_t = now
if self.tracking(now) and dt > 0 and all(abs(x - b) <= self.max_dev for x, b in zip(g, self.bias)):
a = min(dt / self.tau, 1.0)
self.bias = [b + a * (x - b) for x, b in zip(g, self.bias)]
return tuple(x - b for x, b in zip(g, self.bias))
cd ~/ros2_ws/src/rosorin_base
python3 -m pytest -q test/test_gyro_bias.py
The current test file has five tests. They check that the bias moves only when the robot is commanded still and settled, that a turn by hand or driving leaves it alone, that a moving first window gives no bias and the next still one gives the true bias, that a still first window gives the bias once and nothing after, and that the tracker alone never learns a 2 degree per second bias from 0. When I ran this step on the robot, gyro_bias.py only had the tracker and the test file only its two tests, and it printed 2 passed. The start-up retry and its three tests came later, after the carried-at-boot drift above, and I haven't run the current files through pytest on the robot.
stop_motors writes the stop frame to the board directly, without ROS. It runs whenever the driver is gone: from the launch file the moment the driver exits, and from systemd after the service stops.
It takes the device and a wait time from its arguments, defaulting to /dev/ttyACM0 and 30 seconds. Then it tries to open the port every 0.2 seconds for up to that long. The port can be busy for a moment while the dying driver closes it, or gone while the board's USB reconnects. Once open, it sets raw mode at 1,000,000 baud, writes STOP_FRAME three times, closes the port and prints how long it took.
There's no exclusive lock here on purpose. stop_motors must not lock out the driver that systemd starts 3 seconds later. The reverse does hold: while the driver owns the port, stop_motors can't open it. It's a tool for when the driver is gone, not a second way in.
Create ~/ros2_ws/src/rosorin_base/rosorin_base/stop_motors.py:
"""Write the stop frame directly to the board (systemd ExecStopPost; also usable by hand)."""
import os
import sys
import termios
import time
from rosorin_base.motion import STOP_FRAME
WAIT_S = 30.0 # board USB drop (tested 2026-09-28: gone ~3 s, re-enumerates as ttyACM0); board has no
# stop watchdog, so keep trying until it is back. After this, systemd restarts the
# service (RestartSec=3) and this runs again; board_driver also sends STOP at start.
def main():
dev = sys.argv[1] if len(sys.argv) > 1 else '/dev/ttyACM0'
wait = float(sys.argv[2]) if len(sys.argv) > 2 else WAIT_S
t0, warned = time.monotonic(), False
while True: # port may be closing, or the device re-enumerating
try:
fd = os.open(dev, os.O_RDWR | os.O_NOCTTY)
break
except OSError as e:
if time.monotonic() - t0 > wait:
print(f'stop_motors: cannot open {dev} for {wait:.0f} s: {e}', file=sys.stderr)
sys.exit(1)
if not warned and time.monotonic() - t0 > 1.0:
print(f'stop_motors: {dev} unavailable ({e}); retrying up to {wait:.0f} s', file=sys.stderr)
warned = True
time.sleep(0.2)
a = termios.tcgetattr(fd)
a[0] = a[1] = a[3] = 0
a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
a[4] = a[5] = termios.B1000000
termios.tcsetattr(fd, termios.TCSANOW, a)
for _ in range(3):
os.write(fd, STOP_FRAME)
os.close(fd)
print(f'stop_motors: stop frame sent x3 (after {time.monotonic() - t0:.1f} s)')
The 30 seconds come from a test where I dropped the board's USB on purpose, with the robot on its stand and the wheels disabled. The driver's next write failed and it exited. With a 1 second wait, stop_motors gave up while the device was still gone. With 30 seconds, an 8 second drop got its stop frame the moment the device returned. What stays true: while the board's USB is gone, nothing can stop the wheels.
board_driver.py is about 1,130 lines, and you copied it rather than typing it. About half of it is the arm, which chapter 7 explains. Open it on your laptop next to this section, at ros2/rosorin_base/rosorin_base/board_driver.py.
The driver is a node called rosorin_board_driver. It starts by declaring its parameters. A parameter is a named setting of a node, declared in code with a default, such as declare_parameter('cmd_timeout', 0.3), and overridable at start from a launch file or a YAML file without changing code. ros2 param get <node> <name> reads the value a running node uses. The ones that matter for driving are the port, /dev/ttyACM0, the control rate of 50 Hz, the speed limits, the accelerations, the 0.3 second deadman and the 0.5 second scan gate. The code's default speed limit is 0.2 m/s, but config/arm_limits.yaml sets max_linear to 0.35, and that's what runs. The accelerometer calibration comes from config/imu_calibration.yaml, and buzzer tones stay off unless pad_sounds is set to true. Keep each setting in one place: a launch file's parameters silently override the code default, and a YAML file later in the list overrides both.
Then it sets up its topics. It publishes the IMU on imu/data_raw about 110 times a second, in SI units with the gyro bias removed, the battery voltage on battery once a second, wheel odometry on wheel/odom 50 times a second, the gamepad on gamepad, and a JSON summary of everything it knows about itself on ~/state 10 times a second. A name starting with ~/ is private to the node, so ~/state becomes /rosorin_board_driver/state. It listens on cmd_vel for velocity commands, on scan only to note when a LiDAR scan arrived, and on estop, where true latches the e-stop.
It also offers two services. A service is a request with a reply, for things that happen once, where a topic is for a stream. ~/enable takes a std_srvs/SetBool, with data: true or false, and answers with success and a message. ~/reset_estop takes a std_srvs/Trigger, which has no arguments, and clears the latch while leaving motion disabled.
Then it owns the port: the same raw settings as your rrc_read.py, but read-write and exclusive. The first frame it writes is STOP_FRAME, so whatever the wheels were doing before, they stop now. It starts a thread that reads the board, a 50 Hz control timer and two 10 Hz timers, and logs owning /dev/ttyACM0; motion DISABLED until ~/enable.
Every 20 milliseconds the control loop checks how many programs publish on cmd_vel, and more than one trips the e-stop. It handles the gamepad modes and any arm motion, asks the gate for the allowed velocity, publishes wheel odometry, tells the gyro tracker whether the robot is commanded still, turns the velocity into four wheel speeds, and writes a motor frame when they change and at least every 0.2 seconds when they don't. A trip latches the gate, writes STOP_FRAME at once instead of waiting for the next tick, holds the arm, and logs E-STOP latched: with the reason.
Enabling does more than flip the gate. The wheels are never enabled with the arm anywhere but the drive pose, with the camera tilted down at the floor ahead. So ~/enable true takes the arm over, moves it there in one slow move, reads it back, and refuses with refused: arm is not in the drive pose if it didn't get there. That move can take a few seconds before the call answers. Keep your hands and anything else clear of the arm whenever you enable the wheels.
The read thread waits for bytes, feeds the parser, and sends each frame where it belongs: IMU and battery to their topics, servo replies to the arm code, and gamepad frames to the e-stop logic. The gamepad is meant to be the physical e-stop. In the code, any button except MODE trips it on its very first frame, because a quick tap lasts only one frame at the pad's 20 reports a second. MODE cycles between locked, drive and arm. Holding MODE for 2 seconds while an e-stop is latched clears it, and motion stays disabled. None of this was tested on this build (see "Doesn't work yet").
For the IMU, the first samples go to the start-up calibration. Nothing is published during the first 3 second window. When a still window ends, its mean becomes the bias, and the log says gyro bias (deg/s) followed by the three values. If the first window wasn't still, the log warns once with robot not stationary during gyro calibration, the gyro is published uncorrected, and later windows are tried until one is still. After that every sample goes through the tracker, and the accelerometer through its calibration.
Odometry is the robot's own estimate of how far it has moved, added up from small steps. This board has no wheel encoders: nothing reports how far a wheel actually turned. So wheel/odom adds up the commanded velocity after the gate, what the wheels were told rather than what they did. It's wrong whenever a wheel slips, and on the stand. Chapter 9 fuses it with the gyro and adds separate odometry from the LiDAR and the camera. Sideways motion is scaled by 0.765, because on the floor a commanded slide moved the robot only 73 to 79 percent as far as commanded.
The battery code publishes the voltage and detects the charger. The voltage alone doesn't tell you whether the charger is in, but plugging and unplugging showed as a jump of +249 mV and -226 mV with the wheels off, so the driver looks for a step of at least 190 mV. On a clean exit, the driver writes the stop frame twice, stops the read thread and closes the port.
All your files are in place except launch/base.launch.py, which comes next. setup.py installs it, so create it empty for now:
touch ~/ros2_ws/src/rosorin_base/launch/base.launch.py
Build:
source /opt/ros/humble/setup.bash
cd ~/ros2_ws
colcon build --packages-select rosorin_base
ls install/rosorin_base/lib/rosorin_base/
colcon ends with Summary: 1 package finished, in about 2.6 seconds on my robot, and the folder holds the ten programs named in setup.py:
board_driver board_reader depth_gate gamepad_teleop lidar_reader nav_supervisor nav_wait rf2o_fix stop_motors vslam_odom
Then source install/setup.bash; ros2 pkg prefix rosorin_base should print /home/burgerbarn/ros2_ws/install/rosorin_base. If it says Package 'rosorin_base' not found, package.xml isn't valid XML; look at the maintainer line. Edits in src/ change nothing until you build again, because colcon copies the files into install/.
Compare the files you typed with the repository, from your laptop:
cd ~/CCode/rosorin-pro/ros2/rosorin_base
for f in package.xml setup.cfg setup.py rosorin_base/rrc_protocol.py rosorin_base/motion.py rosorin_base/gyro_bias.py rosorin_base/stop_motors.py; do
ssh rosorin cat ros2_ws/src/rosorin_base/$f | diff -q - $f >/dev/null && echo "same $f" || echo "DIFFERS $f"
done
On my robot, with the older gyro_bias.py, this printed seven lines starting with same. With the file in this chapter, gyro_bias.py shows DIFFERS: the repository's copy has a date and a few more words in the StartupCalibration docstring, which this chapter leaves out. Then ssh rosorin cat ros2_ws/src/rosorin_base/rosorin_base/gyro_bias.py | diff - rosorin_base/gyro_bias.py must show only 15c15 and that docstring line. If your maintainer e-mail isn't the repository's, package.xml shows DIFFERS too, and ssh rosorin cat ros2_ws/src/rosorin_base/package.xml | diff - package.xml must show only 6c6 and the two maintainer lines. Anything else in either diff is a typing error.
Run the whole test folder:
cd ~/ros2_ws/src/rosorin_base
python3 -m pytest -q test/
Every test must pass. On my robot, with the older gyro files, it printed 33 passed. The current test folder adds the three start-up calibration tests, and I haven't run it on the robot.
A launch file starts a set of nodes with their parameters in one command, ros2 launch <package> <file>. In ROS 2 it's a Python file with a generate_launch_description() function, and it can react to events, such as starting something when a process exits.
The finished launch file also starts the robot model, the odometry filter and the LiDAR odometry, which aren't built yet; chapters 7 and 9 add those parts. Write it without them now. The LiDAR reader is in from the start, because the scan gate blocks every software command until /scan arrives. Chapter 7 explains the reader, and chapter 5 made /dev/lidar.
Create ~/ros2_ws/src/rosorin_base/launch/base.launch.py:
"""ROSOrin base: controller board (IMU, battery, gated motion) + COIN-D6 LiDAR + static TF.
If board_driver exits for any reason: stop_motors runs immediately (stop frame), then the whole
launch shuts down; systemd ExecStopPost writes the stop frame again as a backup (motion_safety.md).
Mount geometry from the factory URDF (reference data, docs/hardware.md)."""
import os
from ament_index_python.packages import get_package_prefix, get_package_share_directory
from launch import LaunchDescription
from launch.actions import ExecuteProcess, RegisterEventHandler, Shutdown
from launch.event_handlers import OnProcessExit
from launch_ros.actions import Node
def static_tf(name, xyz, rpy, parent, child):
return Node(package='tf2_ros', executable='static_transform_publisher', name=name,
arguments=['--x', xyz[0], '--y', xyz[1], '--z', xyz[2],
'--roll', rpy[0], '--pitch', rpy[1], '--yaw', rpy[2],
'--frame-id', parent, '--child-frame-id', child])
def generate_launch_description():
share = get_package_share_directory('rosorin_base')
calib = os.path.join(share, 'config', 'imu_calibration.yaml')
arm_limits = os.path.join(share, 'config', 'arm_limits.yaml')
board = Node(package='rosorin_base', executable='board_driver', name='rosorin_board_driver',
parameters=[{'device': '/dev/ttyACM0', 'imu_frame_id': 'imu_link'}, calib, arm_limits])
stop_motors = os.path.join(get_package_prefix('rosorin_base'), 'lib', 'rosorin_base', 'stop_motors')
on_board_exit = RegisterEventHandler(OnProcessExit(
target_action=board,
on_exit=[ExecuteProcess(cmd=[stop_motors], output='screen', name='stop_motors',
on_exit=Shutdown(reason='board_driver exited'))]))
return LaunchDescription([
board,
on_board_exit,
Node(package='rosorin_base', executable='lidar_reader', name='rosorin_lidar_reader',
respawn=True, respawn_delay=2.0, # a crashed reader comes back by itself (the scan gate holds the wheels)
parameters=[{'device': '/dev/lidar', 'frame_id': 'laser',
'clockwise': True}]), # native angles run CW: floor test 2026-09-28, docs/hardware.md
# factory pro/lidar.urdf.xacro lidar_joint; native angles published as-is, mount yaw pi
static_tf('tf_base_laser', ['0.048156', '0.0000756', '0.106748'], ['0', '0', '3.14159265'],
'base_link', 'laser'),
# factory pro/imu.urdf.xacro imu_joint
static_tf('tf_base_imu', ['-0.027258', '-0.0000564', '0.048046'], ['0', '-0.0087266', '1.5707'],
'base_link', 'imu_link'),
])
board is the driver node, with its port and IMU frame name and the two YAML files as parameters. on_board_exit is the important part: when the driver's process exits, for any reason including being killed, it runs stop_motors, and when that finishes, it shuts down the whole launch. Without it, a killed node inside a launch doesn't end the launch, so systemd doesn't notice the crash. My first crash test, before this handler existed, stopped the wheels only through systemd, 1.17 seconds after the kill. With it, the stop frame followed the kill after about 0.13 seconds. The LiDAR reader restarts 2 seconds after a crash, and meanwhile the scan gate holds the wheels. The two static transforms say where the LiDAR and the IMU sit on the body. The driver stamps its IMU messages with imu_link, so that one is needed now.
Build again and start it in the foreground, in one SSH session:
source /opt/ros/humble/setup.bash
cd ~/ros2_ws && colcon build --packages-select rosorin_base
source ~/ros2_ws/install/setup.bash
ros2 launch rosorin_base base.launch.py
Keep the robot still for the first 3 seconds, while the gyro calibrates. In a second SSH session:
source /opt/ros/humble/setup.bash
source ~/ros2_ws/install/setup.bash
ros2 node list
for t in scan imu/data_raw; do timeout 6 ros2 topic hz $t 2>&1 | grep -m1 "average rate" | sed "s|^|$t |"; done
timeout 5 ros2 topic echo --once battery 2>&1 | grep -E "^voltage"
timeout 6 ros2 run tf2_ros tf2_echo base_link imu_link 2>&1 | grep -m2 -E "Translation|RPY \(degree"
timeout 5 ros2 topic echo --once /rosorin_board_driver/state --field data
On my robot:
/rosorin_board_driver
/rosorin_lidar_reader
/tf_base_imu
/tf_base_laser
scan average rate: 10.006
imu/data_raw average rate: 110.531
voltage: 12.654...
- Translation: [-0.027, -0.000, 0.048]
- Rotation: in RPY (degree) [-0.000, -0.500, 89.994]
The state shows the wheels off, starting with {"enabled": false, "estop": null, ...} and including "blocked": "disabled" and "scan_age": 0.08. A scan_age under 0.5 means the scan gate is open. In the launch session the driver logs owning /dev/ttyACM0; motion DISABLED until ~/enable and then a gyro bias (deg/s) line with three values; mine were -2.301, -3.009 and 0.078.
If the driver says Device or resource busy, one of your ~/learn scripts still holds the port. If ros2 node list comes back empty right after the start, wait a few seconds and ask again. If the state says "blocked": "no scan" and there's no /scan rate, the LiDAR reader isn't publishing; check /dev/lidar. If topics vanish when your last SSH session closes while the launch keeps running, that's the RemoveIPC setting from chapter 4.
Stop the launch with Ctrl-C in its own session, then check nothing is left:
pgrep -af "lib/rosorin_base|static_transform_publisher" || echo "all stopped"
It should print all stopped. On the way out you'll probably see KeyboardInterrupt tracebacks from the driver and the LiDAR reader. They're harmless. Ctrl-C reaches every node twice, once from the terminal and once from the launch, and the driver has already written its stop frame twice by then. Under systemd, set up next, it doesn't happen. If processes are left over, kill them by process number, not with pkill -f inside an SSH command.
systemd starts the base at boot, restarts it when it dies, and runs a command after it stops. Three settings decide how it stops. KillSignal=SIGINT stops it with the signal ROS treats as Ctrl-C. KillMode=mixed sends that signal only to the main process, ros2 launch, which passes it on to its nodes. The default sends it to every process at once, so each node gets it twice. And ExecStopPost= is a command run after the service stopped, for any reason, including a crash.
Create ~/ros2_ws/src/rosorin_base/systemd/rosorin-base.service. This version sources only the system ROS and your workspace; chapter 9 adds a third workspace to both command lines.
[Unit]
Description=ROSOrin base (board driver with gated motion, LiDAR, static TF)
After=network-online.target
Wants=network-online.target
[Service]
User=burgerbarn
Environment=ROS_DOMAIN_ID=0
ExecStart=/bin/bash -c 'source /opt/ros/humble/setup.bash && source /home/burgerbarn/ros2_ws/install/setup.bash && exec ros2 launch rosorin_base base.launch.py'
KillSignal=SIGINT
KillMode=mixed
TimeoutStopSec=10
# stop frame after ANY stop/crash of the unit (board has no watchdog)
ExecStopPost=/bin/bash -c 'source /opt/ros/humble/setup.bash && source /home/burgerbarn/ros2_ws/install/setup.bash && exec /home/burgerbarn/ros2_ws/install/rosorin_base/lib/rosorin_base/stop_motors'
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
User=burgerbarn runs it as you, not root, so the files it writes are yours. ROS_DOMAIN_ID=0 is the domain every program on the robot uses. In ExecStart, exec replaces bash with ros2 launch, so systemd's signal reaches the launch directly. Don't use ros2 run here: it doesn't pass SIGINT on, so the node keeps running until systemd kills it 10 seconds later. ExecStopPost runs stop_motors after every stop or crash, as the backup to the launch file's handler. Restart=always with RestartSec=3 brings a dead driver back after 3 seconds, disabled, and it writes the stop frame as it starts.
The install scripts live in ~/setup on the robot. Copy the ones this chapter uses from your laptop:
cd ~/CCode/rosorin-pro
ssh rosorin mkdir -p setup
rsync -a scripts/install_base_service.sh scripts/rollback_base_service.sh scripts/install_dds_hostid_fix.sh \
scripts/wait_addresses.sh scripts/motion_test.py scripts/stop_proof.py rosorin:setup/
install_base_service.sh copies the unit from your package to /etc/systemd/system/, enables it for boot, starts it, and shows its status after 8 seconds:
sudo bash ~/setup/install_base_service.sh
Mine showed Created symlink ..., then Active: active (running) since ...; 8s ago, Tasks: 65 (limit: 18452), Memory: 116.7M, and the four processes: the launch, the driver, the LiDAR reader and the transforms. To undo it, there's sudo bash ~/setup/rollback_base_service.sh.
Now add the drop-in from earlier in this chapter, so the service waits until the robot's addresses stop changing:
sudo bash ~/setup/install_dds_hostid_fix.sh | tail -3
bash ~/setup/wait_addresses.sh
sudo systemctl restart rosorin-base
[Service]
ExecStartPre=/bin/bash /home/burgerbarn/setup/wait_addresses.sh
TimeoutStartSec=120
addresses stable after 7s: enP8p1s0=ROBOT_WIRED_IP/24,wlP1p1s0=ROBOT_WIFI_IP/24
systemctl is-active rosorin-base should say active after the restart. To undo the drop-in later: sudo rm -r /etc/systemd/system/rosorin-base.service.d/10-wait-addresses.conf; sudo systemctl daemon-reload.
Three clean stops in a row, counting Python tracebacks and leftover processes:
for i in 1 2 3; do
sudo systemctl stop rosorin-base; sleep 1
e=$(journalctl -u rosorin-base --since "-4 s" --no-pager | grep -cE "Traceback|KeyboardInterrupt|SIGKILL")
l=$(pgrep -f "lib/rosorin_base|static_transform_publisher" | wc -l)
echo "stop $i: python tracebacks=$e leftovers=$l"
sudo systemctl start rosorin-base; sleep 8
done
systemctl is-active rosorin-base
stop 1: python tracebacks=0 leftovers=0
stop 2: python tracebacks=0 leftovers=0
stop 3: python tracebacks=0 leftovers=0
active
Now kill the driver the hard way, with the wheels disabled, and read what followed. The address wait delays every start of the service by 7 seconds or more, so if the first line prints board_driver pid with no number, the driver isn't running yet. Wait a few seconds and run the block again.
P=$(pgrep -f "^/usr/bin/python3 /home/burgerbarn/ros2_ws/install/rosorin_base/lib/rosorin_base/board_driver"); echo "board_driver pid $P"
T=$(date "+%H:%M:%S"); sudo kill -KILL $P; sleep 25
journalctl -u rosorin-base --since "$T" --no-pager | grep -E "process has died|Shutdown|stop_motors|Stopped|Started|Scheduled restart|owning" | sed "s/^.*rosorin //" | cut -c1-120
systemctl is-active rosorin-base
The journal tells the whole chain in order. On my robot the key lines were these:
process has died [pid 10472, exit code -9 ...
[stop_motors-5] stop_motors: stop frame sent x3 (after 0.0 s)
process[stop_motors-5] was required: shutting down
bash[10726]: stop_motors: stop frame sent x3 (after 0.0 s)
Scheduled restart job, restart counter is at 1
Stopped ...
Started ...
owning /dev/ttyACM0; motion DISABLED until ~/enable
active
The driver died with exit code -9, the kill. The launch's own stop_motors sent the stop frame at once and shut the launch down. systemd's ExecStopPost sent it a second time. Then systemd restarted the service, and the new driver came up owning the port with motion disabled.
Reboot once and check that the base comes up by itself:
sudo systemctl reboot
After a minute, from a new SSH session:
systemctl is-active rosorin-base; echo "failed units: $(systemctl --failed --no-legend | wc -l)"
source /opt/ros/humble/setup.bash
for t in scan imu/data_raw; do timeout 6 ros2 topic hz $t 2>&1 | grep -m1 "average rate" | sed "s|^|$t |"; done
journalctl -u rosorin-base -b --no-pager | grep -E "gyro bias|not stationary|owning" | sed "s/.*\]: //"
Mine was back on SSH 45 seconds after the reboot and printed active, failed units: 0, scan average rate: 10.009, imu/data_raw average rate: 110.888, the owning line and a gyro bias line. The base journal also had addresses stable after 12s, which you'll see on every boot from now on.
This is where the wheels turn for the first time under the driver's control, and you need to be at the robot for all of it. Put the robot on its stand with all four wheels free in the air, and unplug the charger. Clear everything out of the arm's reach, because every wheel enable moves the arm to the drive pose first. Keep your hand near the power switch for the whole section. The power switch stops everything, even a hung board. If a wheel keeps turning after any stop, switch the robot off.
Nothing else may publish on cmd_vel during these tests. On a fresh build nothing does. Also expect the arm to tuck itself about 2 minutes after its last movement while the wheels are disabled. After the driver restarts, as it does in the kill and service tests below, the new driver doesn't know the arm is holding a pose, so the arm stays in the drive pose. Tuck it with ros2 service call /rosorin_board_driver/arm/tuck std_srvs/srv/Trigger, and watch it move.
The first enable is the driver's first arm motion: the arm moves to the drive pose. Watch the arm, then run:
source /opt/ros/humble/setup.bash; source ~/ros2_ws/install/setup.bash
timeout 30 ros2 service call /rosorin_board_driver/enable std_srvs/srv/SetBool "{data: true}" 2>&1 | grep -o "message='[^']*'"
journalctl -u rosorin-base --since "-1min" -o cat | grep "to DRIVE" | tail -1 | sed 's/.*arm to DRIVE/arm to DRIVE/'
timeout 20 ros2 service call /rosorin_board_driver/enable std_srvs/srv/SetBool "{data: false}" 2>&1 | grep -o "message='[^']*'"
message='enabled'
arm to DRIVE: {1: 493, 2: 780, 3: 207, 4: 167, 5: 503, 10: 499} -> {1: 493, 2: 793, 3: 51, 4: 160, 5: 499, 10: 499} in 1.3 s (single command, fast)
message='disabled'
The numbers are each arm servo's position before and after. My arm didn't start from the tucked position, so yours will start from different numbers but should end at the same ones. The arm moves to the drive pose and the wheels don't turn: enabling allows motion, it doesn't command any. If you get refused: arm is not in the drive pose, the arm couldn't reach the pose; read journalctl -u rosorin-base -n 30. If you get refused: e-stop latched (...), something tripped it earlier. Remove the cause, then run ros2 service call /rosorin_board_driver/reset_estop std_srvs/srv/Trigger.
scripts/motion_test.py is the harness I used for the very first stand tests. Each step reads the driver's state, sends commands, prints the state, and always ends with the wheels disabled. forward, rotate and estop turn the wheels for the first time. Watch the wheels during each step with your hand at the power switch.
source /opt/ros/humble/setup.bash; source ~/ros2_ws/install/setup.bash
python3 ~/setup/motion_test.py disabled
python3 ~/setup/motion_test.py forward
python3 ~/setup/motion_test.py rotate
python3 ~/setup/motion_test.py estop
These are the lines that matter, trimmed. The state line also carries arm, gyro and gamepad fields; read enabled, estop, blocked and body_vel.
start: {'enabled': False, 'estop': None, 'blocked': 'disabled', 'body_vel': [0.0, 0.0, 0.0]}
>> 3 s of forward 0.1 m/s while DISABLED (wheels must stay still)
after: {'enabled': False, 'estop': None, 'blocked': 'disabled', 'body_vel': [0.0, 0.0, 0.0]}
enable(True) -> True enabled
>> FORWARD 0.1 m/s for 3 s, then silence (deadman)
>> silence
after silence: {'enabled': True, 'estop': None, 'blocked': 'cmd timeout', 'body_vel': [0.0, 0.0, 0.0]}
enable(False) -> True disabled
>> ROTATE +0.5 rad/s (counter-clockwise from above) for 3 s
after: {'enabled': True, 'estop': None, 'blocked': 'cmd timeout', 'body_vel': [0.0, 0.0, 0.0]}
>> ESTOP published
latched: {'enabled': False, 'estop': 'estop topic', 'blocked': 'estop: estop topic', 'body_vel': [0.0, 0.0, 0.0]}
enable(True) -> False refused: e-stop latched (estop topic)
reset: e-stop cleared (was: estop topic); motion still disabled
after reset: {'enabled': False, 'estop': None, 'blocked': 'disabled', 'body_vel': [0.0, 0.0, 0.0]}
What you should see on the robot: nothing moves in disabled. In forward all four wheels turn forward and stop by themselves when the commands end. In rotate the left wheels turn backward and the right ones forward, the right sense for counter-clockwise. In estop the wheels stop while commands keep coming, and the driver refuses to enable again until the reset.
My first disabled run printed ABORT: no driver state received (DDS problem) - not sending anything and the second one passed. Right after the driver starts or restarts, the harness can't see it for a few seconds. Wait and run it again. If it keeps happening, go back to the checks in the launch section. If the state shows 'multiple cmd_vel publishers', something else publishes on cmd_vel, such as a forgotten ros2 topic pub, and ros2 topic info /cmd_vel shows the count.
scripts/stop_proof.py measures stops physically. It spins the wheels at up to 0.35 m/s and 1.0 rad/s, kills the LiDAR reader and the driver, and stops the service while the wheels turn: these are the first wheel motions at these speeds. It records the board's IMU while the wheels spin and through each stop. Spinning wheels shake the robot, and the gyro's x and y axes show it. "Stopped" means the vibration fell to the still level and stayed there, not what the software state says. For the two tests that kill the driver, it reads the IMU straight from the port while the driver is gone.
First see what spinning and still look like on your stand:
source /opt/ros/humble/setup.bash; source ~/ros2_ws/install/setup.bash
timeout 120 python3 ~/setup/stop_proof.py characterize
It prints one line per phase: idle, enabled and still, forward at 0.1, 0.2 and 0.35 m/s, and rotating at 1.0 rad/s, with still phases between. Read these numbers carefully, because the judge in the next step counts anything below 0.0035 as still. On one stand my robot read about 0.0016 to 0.0025 still and 0.006 to 0.010 at 0.35 m/s, well apart. On the softer stand I used later, the same robot read 0.0008 to 0.0012 still, 0.0036 at 0.2 m/s, 0.0046 at 0.35 m/s, and only 0.0028 rotating. A stop only counts as PASS if the spinning level before it was above 0.0035, so a damping stand gives you FAILs, not false PASSes. But a stop time is only meaningful when the spinning level is well above 0.0035.
Then the stop paths. The deadman, the estop topic and enable false, each at three speeds; the scan gate, which kills the LiDAR reader while commands keep coming and then checks that the wheels resume by themselves when the reader comes back; and a hard kill of the driver:
timeout 240 python3 ~/setup/stop_proof.py prove deadman,estop,disable,scanloss,kill
On the stiffer stand, one run printed:
driver state at start: {'enabled': False, 'estop': None, 'plugged': False}
deadman (silence), fwd 0.2 spinning 0.0053 -> still from 0.55 s on; worst after 0.0023 over 4.5 s PASS
estop topic, fwd 0.2 spinning 0.0056 -> still from 0.40 s on; worst after 0.0033 over 4.6 s PASS
enable false, fwd 0.2 spinning 0.0047 -> still from 0.35 s on; worst after 0.0033 over 4.7 s PASS
deadman (silence), fwd 0.35 spinning 0.0072 -> still from 0.75 s on; worst after 0.0034 over 4.3 s PASS
estop topic, fwd 0.35 spinning 0.0066 -> still from 0.50 s on; worst after 0.0032 over 4.5 s PASS
enable false, fwd 0.35 spinning 0.0071 -> still from 0.75 s on; worst after 0.0032 over 4.3 s PASS
deadman (silence), rot 1.0 spinning 0.0048 -> still from 0.50 s on; worst after 0.0025 over 4.5 s PASS
estop topic, rot 1.0 spinning 0.0041 -> still from 0.25 s on; worst after 0.0031 over 4.8 s PASS
enable false, rot 1.0 spinning 0.0055 -> still from 0.30 s on; worst after 0.0028 over 4.8 s PASS
LiDAR silent (scan gate), fwd 0.35 spinning 0.0058 -> still from 0.95 s on; worst after 0.0026 over 1.4 s PASS
LiDAR back: wheels released by themselves vibration 0.0066 (spinning > 0.0035) PASS
kill: board IMU read directly from 0.04 to 3.54 s after the command
driver kill, fwd 0.35 spinning 0.0067 -> still from 0.55 s on; worst after 0.0030 over 3.0 s PASS
RESULT: 12/12 passed
end state: {'enabled': False, 'estop': None}
On the softer stand all 12 passed as well, with 0.75 to 1.20 seconds for the forward stops, 1.35 seconds for the scan gate and 1.00 second for the kill. Every line must say PASS. Your times will differ by a few tenths.
Last, systemctl stop rosorin-base while the wheels turn. The script starts the service again afterwards:
timeout 200 python3 ~/setup/stop_proof.py prove service
Mine printed service: board IMU read directly from 0.06 to 3.55 s after the command, then driver service, fwd 0.35 spinning 0.0053 -> still from 1.05 s on; worst after 0.0025 over 2.5 s PASS and RESULT: 1/1 passed. The service was active again afterwards, with the wheels disabled.
These stop times run from the trigger until the wheels are physically still. They include the deadman's 0.3 second wait, the wheels running down, and the judge's 0.05 second steps. The 0.13 seconds for the crash path earlier is a different number: the time until the stop frame was sent. If the kill test is followed by no IMU data while spinning up (driver gone?), the driver wasn't back yet when the next test started; run that test on its own, as with service above.
The gamepad e-stop hasn't been tested on this build. The harness has a gamepad step, where you press any button except MODE during 15 seconds of forward motion and the driver should latch an e-stop. I skipped it, so I can't tell you it works. The physical gamepad is meant to be the e-stop that doesn't depend on DDS, so treat the robot as having no tested gamepad stop, and count on the power switch.
The stand test can't always see a rotation stop. On my softer stand the three rotation lines read spinning 0.0036-0.0039 -> still from 0.00-0.05 s and passed, but with a spinning level that close to the threshold the judge couldn't tell spinning from still, so those passes say nothing about how fast the wheels stopped. The script hasn't been changed. Compare your characterize levels with 0.0035 before you trust any rotation time.
The start-up retry in gyro_bias.py and its three tests haven't been through pytest on the robot. The driver that uses it did run there: when I restarted the base with it, it logged a bias of -2.211, -2.685 and 0.064 degrees per second, and the heading moved 0.15 degrees in 62 seconds at rest. A start where the first window fails and a later one succeeds hasn't been tried on the robot with the new code.
colcon test reports 0 tests for this package, because the tests aren't registered with colcon. Use python3 -m pytest as this chapter does.
Some failures aren't covered by any test. A wheel stalled against something, and a hung board firmware, have never been tested. While the board's USB is gone, nothing can stop the wheels, which keep their last speed until it returns; only the power switch helps then. The estop topic needs DDS working. And once, during an exploration run on the floor, the robot kept rolling after every software stop until I cut the power. The stand tests had passed before that run and passed again after it, and I still don't know the cause. That's why the wheels stay on the stand until the floor tests in chapter 9.
You're ready for the next chapter when apt-mark showhold | grep -c nvidia-l4t prints 45, head -1 /etc/nv_tegra_release still says REVISION: 4.3, and dpkg-query -W nvidia-jetpack finds nothing; the publish and echo test prints data: hello; Nav2, slam_toolbox and robot_localization are installed; python3 -m pytest -q test/ in ~/ros2_ws/src/rosorin_base passes every test and your typed files are same as the repository's; rosorin-base is active after a reboot, with addresses stable, owning /dev/ttyACM0 and a gyro bias line in its journal; /imu/data_raw runs at about 110 Hz and /scan at about 10 Hz; a hard kill of the driver logs stop_motors: stop frame sent x3 and the service comes back by itself; stop_proof.py printed RESULT: 12/12 passed and 1/1 on the stand; and the wheels are disabled with the robot still on its stand.