ROS 2 and sensor and actuator interfacing
UAT 463 Smart Robotics and Automation
Lesson
By the end of this module you will be able to
- Design the node graph of a mobile manipulator and choose the communication type (topic, service, action) that suits each kind of data
- Explain and calculate how the executor and callback groups affect the regularity of a control loop
- Look up a transform at a message stamp with tf2 and assess the error of different lookup policies
- Set compatible QoS and choose a command timeout from the false-stop rate and the stopping distance
- Use the node life cycle to control the start-up sequence
- Decode an encoder, estimate gyro bias and choose a PWM frequency
- Assess the load of CAN, Modbus RTU and EtherCAT for six joints
- Divide real-time work between the MCU and the onboard computer, and check the deadlines of periodic tasks with the Liu and Layland bound and with response times
Why this matters
The first three modules showed how a robot should perceive, decide and control. This module asks how the software and the wires that join them must behave so that the designed numbers survive. For example, the 1 kHz loop of module 3 works only if its timer is not blocked by 48 ms of image processing. The 79 ms latency budget of module 1 can be compensated only if the transform is looked up at the message stamp. And the encoder that gives the speed to the PI must be decoded correctly without losing counts.
UAT 308 Module 3 already taught QoS and pairing data by time. This module extends it in three ways: (1) ROS 2 at architecture level (executors, tf2, life cycle, ros2_control), (2) the electrical and data connection of sensors and actuators, and (3) calculating the load of the bus you choose. Every example uses the battery-swap cell of MM-1, and all numbers are assumed. The executor results are a model of the scheduling rules that the documentation describes, not a measurement on real ROS 2.
The ROS 2 architecture of MM-1
ROS 2 splits a program into nodes that communicate in three ways. A topic is a continuous many-to-many data channel, such as camera images. A service is one request and one reply. An action is a long-running task with a goal, feedback on progress, a result, and the ability to be cancelled (ROS 2 Actions documentation). Underneath is DDS, where nodes discover one another and which exposes QoS settings to suit the task (Macenski et al., 2022).
In MM-1, a goal-directed task that takes time, such as “swap the battery at pad P2”, is an action called by a leaf of the behavior tree from module 2. Continuous data such as images and parcel poses are topics, and asking the PLC for permission to enter the area is a service. All coordinate transforms are the job of tf2, which keeps a tree of coordinate frames over time (Figure 1).
Executors and callback groups: is the control loop blocked?
Nodes do not run by themselves. An executor picks the callbacks that are ready (a message has arrived, a timer has expired) and runs them on executor threads. A single-threaded executor (SingleThreadedExecutor) runs one callback at a time; a multi-threaded one (MultiThreadedExecutor) can run callbacks in parallel subject to callback groups, which come in two kinds: mutually exclusive, whose callbacks must not run at the same time, and reentrant, whose callbacks may (ROS 2 documentation on executors and callback groups). Two points the documentation stresses and that are often forgotten: a callback with no group specified goes into the node’s default group, which is mutually exclusive, so if everything is in one group a multi-threaded executor behaves like a single thread; and callbacks in different groups may always run in parallel.
One more thing is that an executor takes ready work round-robin rather than first-in-first-out, and messages not yet taken stay in the middleware under the QoS queue policy. A timer that is blocked and misses several periods does not catch up: the rcl source moves the next call time forward by as many periods as needed (RCL, rcl_timer_call), so the missed periods are skipped altogether.
Example 1 A 100 Hz control timer and a 48 ms image detector
The control timer has a 10 ms period and takes 0.5 ms, while image detection (module 1) receives 30 fps and takes 48 ms per image, with a depth-1 queue. Compare three setups: a single thread, two threads with everything in the default group, and two threads with the camera in its own group. The model uses the rules above (round-robin pick-up, mutually exclusive groups run one callback at a time, and skipped periods as in rcl). Simulate 10 s.
import numpy as np
# a model of the executor rules: ready callbacks are taken round-robin and a mutually exclusive group runs one callback at a time
def simulate(threads, groups, T=10.0):
period, t_ctl = 0.010, 0.0005 # the 100 Hz control timer takes 0.5 ms
fps, t_cam = 30.0, 0.048 # camera at 30 fps, detection takes 48 ms (module 1)
nxt, queue, arrivals = period, [], [k / fps for k in range(int(T * fps))]
free_at = [0.0] * threads # time when each thread becomes free
busy_group = {} # group -> end time of its running callback
rr, ctl_starts, late, cam_done, cam_age, trace = 0, [], [], 0, [], []
t = 0.0
while t < T:
while arrivals and arrivals[0] <= t: queue = [arrivals.pop(0)] # depth-1 queue: a new image replaces the old one
ready = []
if t >= nxt: ready.append("ctl")
if queue: ready.append("cam")
ready = [e for e in ready if busy_group.get(groups[e], 0.0) <= t]
thread = min(range(threads), key=lambda i: free_at[i])
if ready and free_at[thread] <= t:
pick = ready[rr % len(ready)]; rr += 1
if pick == "ctl":
late.append(t - nxt); ctl_starts.append(t)
nxt += period
if nxt <= t: nxt += (1 + int((t - nxt) / period)) * period # skip missed periods as rcl_timer_call does
end = t + t_ctl
else:
cam_age.append(t + t_cam - queue[0]); queue = []; cam_done += 1
end = t + t_cam
free_at[thread] = end; busy_group[groups[pick]] = end; trace.append((pick, thread, t, end))
continue
wake = [x for x in free_at if x > t] + [x for x in busy_group.values() if x > t] + ([nxt] if nxt > t else []) + arrivals[:1]
t = min(wake) if wake else T
simulate.trace = trace # keep the callback sequence for plotting
gaps = np.diff(ctl_starts)
return len(ctl_starts) / T, gaps.max() * 1000, np.mean(late) * 1000, cam_done / T, np.mean(cam_age) * 1000
print("executor setup | control Hz | longest gap ms | mean lateness ms | camera Hz | image age ms")
for name, n, g in (("single thread", 1, {"ctl": 0, "cam": 0}),
("2 threads, one group (default)", 2, {"ctl": 0, "cam": 0}),
("2 threads, camera in its own group", 2, {"ctl": 0, "cam": 1})):
print("%-43s | %10.1f | %14.1f | %16.2f | %9.1f | %12.1f" % ((name,) + simulate(n, g)))
executor setup | control Hz | longest gap ms | mean lateness ms | camera Hz | image age ms
single thread | 20.5 | 48.5 | 43.59 | 20.7 | 64.7
2 threads, one group (default) | 20.5 | 48.5 | 43.59 | 20.7 | 64.7
2 threads, camera in its own group | 100.0 | 10.0 | 0.00 | 20.9 | 63.9
A single thread cuts the control loop that should run at 100 Hz to only 20.5 Hz, because after running the timer once the executor takes an image that occupies it for 48 ms. The longest gap between timer runs is 48.5 ms and the timer runs 43.6 ms late on average. Interestingly, two threads with everything in the default group give exactly the same numbers as one thread, since a single group forbids parallel work. When the camera moves to its own group, the control loop returns to 100.0 Hz with a longest gap of 10.0 ms and no lateness, while the camera still processes 20.9 images per second as before (the rest are dropped by the depth-1 queue, as UAT 308 analysed). The lesson is that heavy work must not share a group or a thread with the control loop, and that a system with truly strict real-time needs thread priorities and an executor designed for real time, which the executor documentation says the standard rclcpp executors are not suited to when execution times and order must be exact.
tf2 and time: look up the transform at the capture time
tf2 keeps the transforms of each frame with timestamps in a buffer (10 s by default). A lookup with time 0 means “the latest available”, which is not the capture time. If you ask for a specific time, tf2 interpolates between the two samples that bracket it, shifting position linearly and rotating with slerp (the TimeCache::interpolate source), and raises an extrapolation error if the time is outside the stored range, so you must allow a timeout for the newest transform to reach the buffer (ROS 2 documentation on tf2 and time). This feature is what makes the latency compensation of module 1 practical.
Example 2 The base is driving a curve while a parcel detection arrives 79 ms late
The MM-1 base drives a curve, its speed ramping to 0.30 m/s and its yaw rate swinging ±0.4 rad/s (assumed). A parcel stands still in the odom frame. The image is captured at its stamp, but the detection arrives 79 ms later. Compare the error of the parcel position in the odom frame under three policies: use the latest pose when the result arrives, use the nearest tf sample before the stamp with no interpolation, and interpolate at the stamp, at tf rates of 10, 20 and 50 Hz.
from scipy.spatial.transform import Rotation, Slerp
# the MM-1 base drives a curve: speed ramps to 0.30 m/s and yaw rate swings +-0.4 rad/s (assumed)
dt = 1e-3
tt = np.arange(0, 20, dt)
v = 0.30 * (1 - np.exp(-tt / 0.5))
yaw = np.cumsum(0.4 * np.sin(2 * np.pi * tt / 4.0)) * dt
pos = np.c_[np.cumsum(v * np.cos(yaw)) * dt, np.cumsum(v * np.sin(yaw)) * dt] # the true base pose in the odom frame
def pose_at(t):
k = min(int(round(t / dt)), len(tt) - 1); return pos[k], yaw[k]
def to_world(p_base, p, th): return p + np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]]) @ p_base
parcel_w = np.array([2.5, 1.8]) # a parcel standing still in the odom frame (assumed)
LATENCY = 0.079 # age of the image when the detection arrives (module 1)
def lookup(samples, t, how):
# samples = the published tf stamps
if how == "latest": # like lookupTransform with time 0
s = samples[samples <= t][-1]; return pose_at(s)
i = np.searchsorted(samples, t); a, b = samples[i - 1], samples[i] # samples on both sides of the requested time are needed
if how == "nearest-before": return pose_at(a)
w = (t - a) / (b - a) # interpolate: linear translation, slerp rotation
(pa, ya), (pb, yb) = pose_at(a), pose_at(b)
sl = Slerp([0, 1], Rotation.from_euler("z", [[ya], [yb]]))
return pa + w * (pb - pa), sl(w).as_euler("xyz")[2]
def world_error(ts, p, th2, p_in_base): return 1000 * np.linalg.norm(to_world(p_in_base, p, th2) - parcel_w)
rng = np.random.default_rng(6)
stamps = rng.uniform(2.0, 18.0, 400) # 400 image capture times
seen = [] # what the camera saw at capture (parcel in the base frame)
for ts in stamps:
pb, th = pose_at(ts)
seen.append(np.linalg.solve(np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]]), parcel_w - pb))
latest = [world_error(ts, *pose_at(ts + LATENCY), pb) for ts, pb in zip(stamps, seen)] # use the newest pose when the result arrives
print("latest pose on arrival (any tf rate): mean %.2f mm, p99 %.2f mm" % (np.mean(latest), np.percentile(latest, 99)))
results = {}
print("tf rate Hz | nearest sample before stamp (mean / p99 mm) | interpolated at stamp (mean / p99 mm)")
for f in (10, 20, 50):
samples = np.arange(0, 20, 1 / f)
row = []
for how in ("nearest-before", "interpolated"):
e = [world_error(ts, *lookup(samples, ts, how), pb) for ts, pb in zip(stamps, seen)]
row += [np.mean(e), np.percentile(e, 99)]
results[f] = row
print("%10d | %22.2f / %6.2f | %19.2f / %5.2f" % (f, *row))
latest pose on arrival (any tf rate): mean 41.62 mm, p99 87.90 mm
tf rate Hz | nearest sample before stamp (mean / p99 mm) | interpolated at stamp (mean / p99 mm)
10 | 26.59 / 91.16 | 0.57 / 1.67
20 | 13.28 / 46.67 | 0.19 / 0.50
50 | 5.23 / 17.73 | 0.13 / 0.44
Using the latest pose on arrival gives a mean error of 41.6 mm (p99 87.9 mm), because the base has moved and turned during the 79 ms. Using the tf sample before the stamp with no interpolation is better but still off by 26.6 mm at 10 Hz and 5.2 mm at 50 Hz, since the sample lags the capture by up to one tf period. Interpolating at the stamp gives a mean error of only 0.57 mm at 10 Hz and 0.13 mm at 50 Hz, below the 3 mm tolerance of battery swapping even at a low tf rate, because the motion within one tf period is close enough to a straight line. The conclusion is to stamp at exposure and look up at that time; a higher tf rate helps only a little. Looking back in time requires a buffer that is deep enough and a timeout long enough for the newest transform to arrive. If both the base and the parcel move, use the “time travel” lookup, which names a fixed frame, as the tf2 documentation describes.
QoS: compatibility and command timeout
UAT 308 taught that the policies of publisher and subscriber must be compatible. The ROS 2 documentation uses a “request versus offer” model. Two rules to remember are that a best-effort publisher cannot connect to a reliable subscriber, and a volatile publisher cannot connect to a transient-local subscriber (so to have a “latched” topic visible to late joiners, both sides must use transient local). The defaults are keep last 10, reliable, volatile, and the sensor-data profile uses best effort and a smaller queue.
Another group of policies concerns safety: the command timeout. A silent velocity command must not let the base run on forever. The diff_drive_controller of ros2_control has a parameter cmd_vel_timeout (default 0.5 s), after which a command received on cmd_vel is considered stale, and 0.0 disables it. Setting it is a trade between two things: too short and the base stops for nothing when the network hiccups, too long and the stopping distance after a real loss grows.
Example 3 Check compatible QoS and choose the command timeout
Check five publisher and subscriber pairs against the rules above, then simulate 20 Hz velocity commands for one hour with network jitter averaging 8 ms and hiccups of 0.12 to 0.40 s about 12 times an hour (assumed). The base moves at 0.5 m/s and brakes at 1.0 m/s². Count how often the timeout stops the base for nothing per hour, and compute the stopping distance after a real loss.
# QoS compatibility by the "request versus offer" tables of the ROS 2 (Jazzy) documentation
REL = {("best_effort", "best_effort"): True, ("best_effort", "reliable"): False, ("reliable", "best_effort"): True, ("reliable", "reliable"): True}
DUR = {("volatile", "volatile"): True, ("volatile", "transient_local"): False, ("transient_local", "volatile"): True, ("transient_local", "transient_local"): True}
def compatible(pub, sub): return REL[(pub["rel"], sub["rel"])] and DUR[(pub["dur"], sub["dur"])]
default = {"rel": "reliable", "dur": "volatile"} # default: keep last 10, reliable, volatile
sensor = {"rel": "best_effort", "dur": "volatile"}
latched = {"rel": "reliable", "dur": "transient_local"}
for pn, p, sn, s in (("camera (sensor data)", sensor, "detector (default)", default), ("camera (sensor data)", sensor, "detector (sensor data)", sensor),
("cell state (default)", default, "monitor (sensor data)", sensor), ("map server (latched)", latched, "late joiner (default)", default),
("map server (default)", default, "late joiner (latched)", latched)):
print("%-22s -> %-24s : %s" % (pn, sn, "connected" if compatible(p, s) else "NO CONNECTION"))
# a command timeout (like cmd_vel_timeout of diff_drive_controller): too short stops for nothing, too long lengthens the stop
rng = np.random.default_rng(8)
N, period = 72_000, 0.050 # commands at 20 Hz for one hour
gaps = period + rng.exponential(0.008, N) # network jitter averaging 8 ms (assumed)
hiccup = rng.random(N) < 1 / 6000 # hiccups of 0.12-0.40 s, about 12 per hour (assumed)
gaps = gaps + hiccup * rng.uniform(0.12, 0.40, N)
v, a = 0.5, 1.0 # base speed m/s and braking deceleration m/s^2
print("timeout ms | stops per hour from jitter alone | stopping distance after a real loss (m)")
for T_o in (0.060, 0.100, 0.200, 0.500):
print("%10.0f | %33d | %39.3f" % (T_o * 1000, int((gaps > T_o).sum()), v * T_o + v * v / (2 * a)))
print("hiccups in the data: %d, longest gap %.3f s" % (hiccup.sum(), gaps.max()))
camera (sensor data) -> detector (default) : NO CONNECTION
camera (sensor data) -> detector (sensor data) : connected
cell state (default) -> monitor (sensor data) : connected
map server (latched) -> late joiner (default) : connected
map server (default) -> late joiner (latched) : NO CONNECTION
timeout ms | stops per hour from jitter alone | stopping distance after a real loss (m)
60 | 20749 | 0.155
100 | 132 | 0.175
200 | 9 | 0.225
500 | 0 | 0.375
hiccups in the data: 10, longest gap 0.442 s
A camera with the sensor-data profile (best effort) cannot connect to a detector that uses the defaults (reliable), because the detector requests more than the publisher offers, and nothing obvious appears on the topic. You must look at the incompatible-QoS events or run ros2 topic info --verbose. The timeout table shows the trade clearly. At 60 ms, too close to the 50 ms period, the base would stop for nothing 20,749 times an hour from ordinary jitter alone. At 100 ms that falls to 132, at 200 ms to 9 (the real hiccups that are long enough), and at 500 ms to none, but the stopping distance grows from 0.155 m to 0.375 m. The team picks 200 ms because it gives fewer than ten needless stops an hour and a 0.225 m stopping distance that still fits the protective field calculated in module 5. These numbers must be recalculated with real network data from the cell.
Node life cycle and ros2_control
A node that must open hardware, such as a motor driver, should not start sending commands as soon as it is created. ROS 2 has managed nodes with four primary states, Unconfigured, Inactive, Active and Finalized, and transition states between them (Configuring, CleaningUp, ShuttingDown, Activating, Deactivating, ErrorProcessing). Leaving a primary state needs a supervisor to ask for it, except when an error occurs in Active. In Inactive the node gets no execution time to read topics or answer services, and commands that arrive are not processed. If the onActivate callback returns an error the node enters ErrorProcessing, and if onError succeeds it returns to Unconfigured (the ROS 2 design of managed nodes). This lets the start-up order “driver, controller, planner” be checked and stopped halfway.
ros2_control separates control software into three parts: controllers, which take references and measurements and compute the system input; hardware components, which talk to drivers and encoders through read() and write() methods that the resource manager calls in every control cycle; and the controller manager, which connects the two sides (ros2_control documentation). The PI speed and position loops of module 3 are controllers in this structure, while reading the encoder and writing the voltage belong to the hardware component.
Example 4 Start-up order with the life cycle, when the driver cannot find the CAN adapter
Three nodes, driver, controller and planner, are commanded in order: configure, then activate, one node at a time. In the second case the driver fails to activate because it does not find the CAN adapter, and the supervisor must stop and not start the next nodes.
# the managed-node life cycle: four primary states plus ErrorProcessing
TRANSITIONS = {("Unconfigured", "configure"): "Inactive", ("Inactive", "activate"): "Active", ("Active", "deactivate"): "Inactive",
("Inactive", "cleanup"): "Unconfigured", ("Unconfigured", "shutdown"): "Finalized", ("Inactive", "shutdown"): "Finalized", ("Active", "shutdown"): "Finalized"}
class ManagedNode:
def __init__(self, name, fail=None):
self.name, self.state, self.fail = name, "Unconfigured", fail # fail = the transition that will fail
def trigger(self, tr):
if (self.state, tr) not in TRANSITIONS: return "rejected: %s is not valid in %s" % (tr, self.state)
if tr == self.fail: # the callback returns ERROR -> ErrorProcessing -> onError succeeds -> Unconfigured
self.state = "Unconfigured"; return "%s failed, ErrorProcessing, back to Unconfigured" % tr
self.state = TRANSITIONS[(self.state, tr)]; return "ok -> " + self.state
def command(self, v): # commands arriving while not Active are not processed
return "executed %.2f m/s" % v if self.state == "Active" else "ignored (state %s)" % self.state
def bring_up(nodes, order):
for name, tr in order:
node = nodes[name]
res = node.trigger(tr); print(" %-10s %-10s %s" % (name, tr, res))
if res.startswith("rejected") or "failed" in res:
print(" supervisor stops: later nodes are not activated"); return False
return True
order = [("driver", "configure"), ("driver", "activate"), ("controller", "configure"), ("controller", "activate"), ("planner", "configure"), ("planner", "activate")]
for title, fail in (("normal start-up", None), ("CAN adapter missing when the driver activates", "activate")):
print(title)
nodes = {"driver": ManagedNode("driver", fail), "controller": ManagedNode("controller"), "planner": ManagedNode("planner")}
ok = bring_up(nodes, order)
print(" states:", {n: x.state for n, x in nodes.items()}, "| command to controller:", nodes["controller"].command(0.2))
print("illegal request:", ManagedNode("x").trigger("activate"))
normal start-up
driver configure ok -> Inactive
driver activate ok -> Active
controller configure ok -> Inactive
controller activate ok -> Active
planner configure ok -> Inactive
planner activate ok -> Active
states: {'driver': 'Active', 'controller': 'Active', 'planner': 'Active'} | command to controller: executed 0.20 m/s
CAN adapter missing when the driver activates
driver configure ok -> Inactive
driver activate activate failed, ErrorProcessing, back to Unconfigured
supervisor stops: later nodes are not activated
states: {'driver': 'Unconfigured', 'controller': 'Unconfigured', 'planner': 'Unconfigured'} | command to controller: ignored (state Unconfigured)
illegal request: rejected: activate is not valid in Unconfigured
In the normal case all three nodes reach Active in order and a velocity command reaching the controller is executed. In the failing case the driver passes through ErrorProcessing back to Unconfigured, the supervisor stops at once and does not start the controller or the planner, so no command is processed without hardware behind it (the last line of that case reads “ignored”). An out-of-order request is rejected, such as activate while Unconfigured. This code is a state-table model of the design document, not the real ROS 2 API.
From the motor shaft to numbers: encoder, gyro and driver
A quadrature encoder gives signals A and B that change one bit at a time in Gray order; the sequence 00, 01, 11, 10 means forward and the reverse sequence means backward. An x4 decoder counts every state change, giving four times the number of lines (1,024 lines give 4,096 counts per turn, as used in module 3). A change of two bits at once is an illegal state, which tells you the sampling is too slow or there is noise. The hardware counter of a microcontroller is often 16 bits wide and wraps at 65,536, so differences must be taken circularly to avoid false speeds.
Example 5 Decode quadrature and handle counter wrap
Decode one forward and one backward turn, try sampling every second state, then simulate a turn at 100 rad/s for 5 s with the 16-bit counter read every 1 ms, comparing a plain difference with a circular one.
# an x4 quadrature decoder: the (A, B) state changes one bit at a time in Gray order 00 -> 01 -> 11 -> 10
STEP = {(0b00, 0b01): +1, (0b01, 0b11): +1, (0b11, 0b10): +1, (0b10, 0b00): +1,
(0b01, 0b00): -1, (0b11, 0b01): -1, (0b10, 0b11): -1, (0b00, 0b10): -1}
LINES = 1024 # encoder lines per turn, x4 = 4096 counts per turn (as in module 3)
GRAY = [0b00, 0b01, 0b11, 0b10]
def decode(states, glitch_at=()):
count, errors, prev = 0, 0, states[0]
for k, s in enumerate(states[1:], 1):
if k in glitch_at: s ^= 0b11 # noise flips both bits at once
if s == prev: continue
if (prev, s) in STEP: count += STEP[(prev, s)]
else: errors += 1 # a skipped state: direction unknown, so not counted but reported
prev = s
return count, errors
turn = [GRAY[k % 4] for k in range(4 * LINES + 1)] # exactly one forward turn
back = [GRAY[(4 * LINES - k) % 4] for k in range(4 * LINES + 1)]
print("one forward turn: count %d (expect %d); one backward turn: count %d" % (decode(turn)[0], 4 * LINES, decode(back)[0]))
slow = turn[::2] # sampled too slowly: every second state is missed
print("sampled every 2nd state: count %d, illegal transitions %d" % decode(slow))
print("counts per second at 100 rad/s: %.0f; the sampling rate must be well above this, so use the hardware encoder interface" % (100 / (2 * np.pi / (4 * LINES))))
# the 16-bit hardware counter wraps at 65536: the difference must be taken modulo 65536
def delta16(new, old): return ((new - old + 32768) % 65536) - 32768
Ts, Qr = 1e-3, 2 * np.pi / (4 * LINES)
true_counts = np.floor(np.arange(0, 5.0, Ts) * 100.0 / Qr).astype(int) # a steady 100 rad/s for 5 s, read every 1 ms
reads = true_counts % 65536
naive = np.diff(reads) * Qr / Ts
safe = np.array([delta16(b, a) for a, b in zip(reads[:-1], reads[1:])]) * Qr / Ts
print("wraps in 5 s: %d; naive speed range %.0f to %.0f rad/s; wrap-safe speed range %.1f to %.1f rad/s" % ((np.diff(reads) < 0).sum(), naive.min(), naive.max(), safe.min(), safe.max()))
print("wrap-safe reading is valid up to %.0f turns per read = %.0f rev/s at Ts = 1 ms; 100 rad/s is %.1f rev/s" % (32768 / 4096, 32768 / 4096 / Ts, 100 / (2 * np.pi)))
one forward turn: count 4096 (expect 4096); one backward turn: count -4096
sampled every 2nd state: count 0, illegal transitions 2048
counts per second at 100 rad/s: 65190; the sampling rate must be well above this, so use the hardware encoder interface
wraps in 5 s: 4; naive speed range -100431 to 101 rad/s; wrap-safe speed range 99.7 to 101.2 rad/s
wrap-safe reading is valid up to 8 turns per read = 8000 rev/s at Ts = 1 ms; 100 rad/s is 15.9 rev/s
One forward turn counts exactly +4,096 and one backward turn −4,096. If every second state is skipped, each change is two bits, so the decoder counts zero and reports 2,048 illegal transitions. At 100 rad/s the count changes 65,190 times a second, which software polling cannot follow, so use the hardware encoder interface of the MCU. The 16-bit counter wraps 4 times in 5 s, and with a plain difference the speed would jump once to −100,431 rad/s, which fed to the PI would command full voltage at once. The circular difference gives 99.7 to 101.2 rad/s (the coarseness of 1.53 rad/s that module 3 calculated). It works as long as the change per read does not exceed half the counter range, 32,768 counts or 8 turns per read.
An inertial measurement unit (IMU) on the base reports turn rate, but a gyro has a constant bias. If the bias is , then after integration the angle error grows linearly with time, , while white noise produces a random walk whose standard deviation grows as (Woodman, 2007). A constant bias can be estimated as the mean output while stationary and then subtracted. UAT 205 Module 2 taught the error model and Allan deviation; here the simplest result is applied to robot start-up.
A PWM motor driver creates an average voltage by switching, which makes the current in a winding with inductance ripple as a triangle. With bus voltage , duty and frequency , the peak-to-peak ripple is (from the slopes while on and while off). A higher frequency reduces ripple but increases switching losses.
Example 6 Gyro bias at start-up and the PWM ripple current
A gyro reads at 200 Hz with a bias of 0.20 degrees per second and noise of 0.05 degrees per second per sample (assumed). Estimate the bias from the first 5 s while the robot is still, then measure the heading error after 60 s (2,000 simulated runs). Then simulate the current of the module 3 motor winding at duty 0.5 on a 12 V bus and compare with the formula.
# IMU: the gyro has a constant bias and white noise
rng = np.random.default_rng(9)
fs, bias, sigma = 200.0, 0.20, 0.05 # read rate Hz, bias deg/s, noise per sample deg/s (assumed)
still = bias + rng.normal(0, sigma, int(5 * fs)) # the first 5 s after power-up with the robot standing still
b_hat = still.mean()
print("bias estimate %.4f deg/s (error %.4f, expected scatter %.4f)" % (b_hat, b_hat - bias, sigma / np.sqrt(len(still))))
drift = lambda b_est, n=2000: [np.cumsum(bias + rng.normal(0, sigma, 60 * int(fs)) - b_est)[-1] / fs for _ in range(n)]
for name, b in (("integrate raw gyro", 0.0), ("subtract the 5 s bias estimate", b_hat)):
d = np.array(drift(b))
print("heading error after 60 s, %-31s: mean %6.3f deg, spread %.3f deg" % (name, d.mean(), d.std()))
print("theory: bias x time = %.1f deg; random walk sigma*sqrt(dt*t) = %.3f deg" % (bias * 60, sigma * np.sqrt(60 / fs)))
# a PWM motor driver: the current ripple of an R-L load on a 12 V bus
R, L = 1.2, 0.8e-3 # the motor winding of module 3
def ripple(f_pwm, duty, V=12.0, back_emf=5.0, steps=400):
T = 1 / f_pwm; dt = T / steps; i, log = 0.0, []
for k in range(8 * steps):
v = V if (k % steps) < duty * steps else 0.0 # the bridge drives positive or freewheels
i = max(0.0, i + dt * (v - back_emf - R * i) / L)
log.append(i)
last = np.array(log[-steps:]); return last.max() - last.min()
print("PWM kHz | simulated ripple A | formula V D (1-D)/(L f) A")
for f in (4e3, 8e3, 20e3):
print("%7.0f | %18.3f | %24.3f" % (f / 1e3, ripple(f, 0.5), 12.0 * 0.5 * 0.5 / (L * f)))
bias estimate 0.2003 deg/s (error 0.0003, expected scatter 0.0016)
heading error after 60 s, integrate raw gyro : mean 12.000 deg, spread 0.027 deg
heading error after 60 s, subtract the 5 s bias estimate : mean -0.016 deg, spread 0.027 deg
theory: bias x time = 12.0 deg; random walk sigma*sqrt(dt*t) = 0.027 deg
PWM kHz | simulated ripple A | formula V D (1-D)/(L f) A
4 | 0.935 | 0.938
8 | 0.480 | 0.469
20 | 0.203 | 0.188
The estimated bias is 0.2003 degrees per second, off by only 0.0003, consistent with the expected 0.0016. Integrating the raw gyro leaves a heading error of 12.0 degrees after 60 s, matching , while subtracting the estimated bias leaves a mean error of −0.016 degrees with a spread of 0.027 degrees, which matches the random walk degrees. Subtracting the bias therefore cut the error about 750 times. The ripple current is 0.935 A at 4 kHz (formula 0.938), 0.480 A at 8 kHz (0.469) and 0.203 A at 20 kHz (0.188), so model and formula agree within 8%. Raising the frequency five times cut the ripple 4.6 times.
Buses: CAN, Modbus RTU and EtherCAT
Six joints that must be commanded and read back every 1 ms need a bus that can carry the load, so we calculate before choosing. Classic CAN (ISO 11898-1) sends frames of at most 8 bytes. The worst-case transmission time of a frame with data bytes and an 11-bit identifier, including bit stuffing, is , so an 8-byte frame takes 135 bits. Davis et al. (2007) corrected an earlier worst-case response-time analysis of CAN. The simple sufficient test used in the code is and , where is the longest frame that may already be on the bus and is the set of higher-priority messages.
Modbus RTU is a question-and-answer protocol on a serial line. Each byte takes 11 bits and frames must be separated by a silence of at least 3.5 character times (t3.5), which above 19,200 bit/s the specification recommends fixing at 1.75 ms (the Modbus over serial line specification). A read-registers request (function 0x03) has an 8-byte request and a byte response for registers (the Modbus application protocol specification). EtherCAT sends one frame through every device in the ring, and each device reads and writes its own data “on the fly” as the frame passes, so the frame is delayed only by hardware propagation. The ETG states short cycle times (100 µs or less), bandwidth utilisation above 90%, and distributed-clock synchronisation with jitter below 1 µs.
Example 7 Bus load of six joints
There are 6 command and 6 feedback messages and 1 emergency-stop message (1 byte every 10 ms at top priority). Compare four CAN setups, then compute the time per Modbus RTU transaction at 115,200 bit/s and the minimum EtherCAT cycle at 100 Mbit/s. A frame overhead of 60 bytes and 1 µs of delay per device are assumed.
import math
# classic CAN (11-bit id): worst-case frame time with bit stuffing C = (55 + 10 s) bits for s data bytes (Davis et al., 2007)
def can_C(s, bit): return (55 + 10 * s) * bit
def can_wcrt(msgs, bit):
# the simple sufficient test: w = B + sum ceil((w + J + bit) / T_k) C_k, B = the longest frame
B = max(can_C(m[2], bit) for m in msgs)
out = []
for i, (name, T, s) in enumerate(msgs): # ordered from high to low priority
C, w = can_C(s, bit), B
for _ in range(200):
w2 = B + sum(math.ceil((w + bit) / T_k) * can_C(s_k, bit) for _, T_k, s_k in msgs[:i])
if abs(w2 - w) < 1e-12: break
w = w2
if w > 1.0: w = float("inf"); break # no convergence: there is no response-time bound
out.append(w + C)
return out
def cell(period, payload):
m = [("stop", 0.010, 1)] # an emergency-stop message every 10 ms at the highest priority
m += [("cmd%d" % j, period, payload) for j in range(1, 7)] + [("fb%d" % j, period, payload) for j in range(1, 7)]
return m
can_rows = []
print("bus setup | load % | worst response of the last frame ms | deadline ms | met")
for label, bit, period, payload in (("1 Mbit/s, 1 ms, 8 bytes", 1e-6, 0.001, 8), ("1 Mbit/s, 2 ms, 8 bytes", 1e-6, 0.002, 8),
("1 Mbit/s, 2 ms, 4 bytes", 1e-6, 0.002, 4), ("500 kbit/s, 5 ms, 8 bytes", 2e-6, 0.005, 8)):
msgs = cell(period, payload); R = can_wcrt(msgs, bit)
load = sum(can_C(s, bit) / T for _, T, s in msgs)
can_rows.append((label, 100 * load, R[-1], period))
shown = "%.3f" % (1000 * R[-1]) if R[-1] < float("inf") else "no bound"
print("%-34s | %6.1f | %35s | %11.1f | %s" % (label, 100 * load, shown, 1000 * period, "yes" if R[-1] <= period else "NO"))
# Modbus RTU at 115200 bit/s: 11 bits per byte and t3.5 = 1.75 ms above 19200 bit/s
def modbus_transaction(registers, baud=115200):
request, response = 1 + 1 + 2 + 2 + 2, 1 + 1 + 1 + 2 * registers + 2 # address, function, ... CRC (function 0x03)
return (request + response) * 11 / baud + 2 * 1.75e-3
for n in (6, 20, 100):
t = modbus_transaction(n)
print("Modbus RTU read of %3d registers: %6.2f ms per transaction, at most %5.0f per second" % (n, 1000 * t, 1 / t))
# EtherCAT: one frame passes every subdevice; at 100 Mbit/s a byte takes 80 ns (overhead and per-device delay are assumed)
def ethercat_cycle(devices, bytes_each, overhead=60, delay_each=1.0e-6):
return (overhead + devices * bytes_each) * 80e-9 + devices * delay_each
ecat_rows = []
for dev, b in ((6, 16), (6, 64), (30, 16)):
t = ethercat_cycle(dev, b); ecat_rows.append((dev, b, t))
print("EtherCAT %2d devices x %2d bytes: minimum cycle %5.1f us = %4.1f%% of a 1 ms cycle" % (dev, b, 1e6 * t, 100 * t / 1e-3))
bus setup | load % | worst response of the last frame ms | deadline ms | met
1 Mbit/s, 1 ms, 8 bytes | 162.7 | no bound | 1.0 | NO
1 Mbit/s, 2 ms, 8 bytes | 81.7 | 1.820 | 2.0 | yes
1 Mbit/s, 2 ms, 4 bytes | 57.6 | 1.300 | 2.0 | yes
500 kbit/s, 5 ms, 8 bytes | 66.1 | 3.640 | 5.0 | yes
Modbus RTU read of 6 registers: 5.89 ms per transaction, at most 170 per second
Modbus RTU read of 20 registers: 8.56 ms per transaction, at most 117 per second
Modbus RTU read of 100 registers: 23.84 ms per transaction, at most 42 per second
EtherCAT 6 devices x 16 bytes: minimum cycle 18.5 us = 1.8% of a 1 ms cycle
EtherCAT 6 devices x 64 bytes: minimum cycle 41.5 us = 4.2% of a 1 ms cycle
EtherCAT 30 devices x 16 bytes: minimum cycle 73.2 us = 7.3% of a 1 ms cycle
CAN at 1 Mbit/s with a 1 ms period cannot cope: the load is 162.7% and there is no response-time bound. With a 2 ms period the load is 81.7% and the last message responds in at most 1.820 ms, still within the 2.0 ms deadline but with very little margin. Cutting the data to 4 bytes gives a load of 57.6% (1.300 ms), and 500 kbit/s with a 5 ms period gives 66.1% (3.640 ms against a 5.0 ms deadline), but both make the control loop slower. Modbus RTU takes 5.89 ms per transaction to read 6 registers, at most 170 per second, which suits talking to a PLC at tens of hertz but not joint control. EtherCAT for 6 joints of 16 bytes each needs a minimum cycle of only 18.5 µs (1.8% of 1 ms), and 30 devices still need just 73.2 µs. The comparison is clear: calculate the load and worst-case response time of the bus before buying devices. The EtherCAT figures are a lower bound under the stated assumptions; a real system also has the operating-system time of the master and synchronisation, which the vendor tells you to check.
Embedded controllers in the robot: dividing real-time work between the MCU and the computer
An embedded system is a computer built into a device to do one dedicated job under timing limits. A robot such as MM-1 has at least two groups of computers with different jobs. The first is the microcontroller (MCU) next to the motor and driver, which runs the fast control loops. The second is the onboard computer running Linux and ROS 2, which handles perception and planning. Lynch and Park (2017) note that a robot’s torque command is typically updated about 1 kHz, while the amplifier’s voltage-control loop runs ten times faster or more. The table summarizes how the work of MM-1 is divided (the rates are this module’s example values).
| Level | Rate | Runs on | Reason |
|---|---|---|---|
| Current loop in the driver | 10 kHz and up | MCU or driver circuit | Must answer every hundred microseconds, too fast to go over a bus |
| Joint speed and position loop | 1 kHz | MCU or a real-time thread of ros2_control | Module 3 shows the sampling period sets the delay of the loop |
| Perception, planning, high-level commands | 10 to 100 Hz | Onboard computer (Linux and ROS 2) | Heavy computation and many libraries; tolerates variable latency |
Why not let one computer do everything? Ordinary Linux does not guarantee timing: threads compete and drivers disable interrupts, so a task sometimes starts late (jitter). A PREEMPT_RT kernel reduces the latency between a high-priority task becoming runnable and actually running, by forcing interrupts into threads, using sleeping locks and applying priority inheritance (Linux kernel documentation). That helps a great deal, but the worst-case latency must still be measured on the real hardware. An MCU running an RTOS such as FreeRTOS, Zephyr or NuttX handles interrupts at the microsecond scale. micro-ROS puts ROS 2 nodes on the MCU using the rclc library and the Micro XRCE-DDS middleware, with an agent on the computer joining them to the normal ROS 2 graph (micro-ROS documentation).
Each task on the MCU is periodic, with period and worst-case execution time (WCET) , and its deadline is the start of the next period. A common way to assign priorities is rate-monotonic: the task with the shorter period gets the higher priority. Liu and Layland (1973) proved in Theorem 5 that for tasks the least upper bound of processor utilization is , which falls toward for large . If does not exceed this value, every task meets its deadline under that paper’s assumptions: the tasks are periodic, independent of one another, and have constant run time. The condition is sufficient but not necessary, so above the bound you cannot conclude that a deadline will be missed; compute the response time of each task instead.
Here are the higher-priority tasks; task is released times during and interrupts task for each time, and is the time blocked by sections that cannot be interrupted, such as a long interrupt handler. Iterate until the value stops changing. If for every task, the set passes. Davis et al. (2007) use the same technique for the worst-case response time of CAN messages in Example 7.
Example 8 Does the joint MCU meet its deadlines
The joint MCU has four tasks (assumed). The 10 kHz current loop takes 18 µs in the worst case, the 1 kHz speed and position loop 150 µs, the encoder and IMU fusion every 2 ms takes 300 µs, and CAN with micro-ROS communication every 10 ms takes 1.5 ms. The team checks them against the Liu and Layland bound, then adds a UART logging task of 4 ms every 20 ms, and finally lets an interrupt handler block the system for various values of .
# Real-time tasks on the joint MCU: check deadlines with the Liu-Layland bound and with response times (assumed values)
import math
rt_tasks = [("current loop", 100, 18), ("velocity+position loop", 1000, 150),
("encoder+IMU fusion", 2000, 300), ("CAN + micro-ROS comms", 10000, 1500)] # (name, period us, worst-case execution time us)
def rt_check(tasks, blocking=0):
# rate-monotonic priorities: shorter period = higher priority; deadline = period; R = C + B + interference from higher-priority tasks
util = sum(c / t for _, t, c in tasks)
bound = len(tasks) * (2 ** (1 / len(tasks)) - 1)
rows = []
for i, (name, t, c) in enumerate(tasks):
r = c + blocking
while True:
nxt = c + blocking + sum(math.ceil(r / tj) * cj for _, tj, cj in tasks[:i])
if nxt == r or nxt > t:
break
r = nxt
rows.append((name, t, nxt if nxt > t else r))
return util, bound, rows
for label, ts_ in (("4 tasks", rt_tasks), ("+ logging task", rt_tasks + [("UART logging", 20000, 4000)])):
util, bound, rows = rt_check(ts_)
verdict = "below the bound: schedulable" if util <= bound else "above the bound: inconclusive, check response times"
print("%s: U = %.3f, Liu-Layland bound = %.3f -> %s" % (label, util, bound, verdict))
for name, t, r in (rows if label == "4 tasks" else rows[-1:]):
print(" %-24s period %6d us, response %6d us, %s" % (name, t, r, "meets deadline" if r <= t else "MISSES"))
print("blocking B by a long interrupt handler -> first task to miss its deadline")
for b in (0, 60, 82, 90):
_, _, rows = rt_check(rt_tasks, blocking=b)
miss = [name for name, t, r in rows if r > t]
print(" B = %2d us: %s" % (b, miss[0] if miss else "none"))
4 tasks: U = 0.630, Liu-Layland bound = 0.757 -> below the bound: schedulable
current loop period 100 us, response 18 us, meets deadline
velocity+position loop period 1000 us, response 186 us, meets deadline
encoder+IMU fusion period 2000 us, response 558 us, meets deadline
CAN + micro-ROS comms period 10000 us, response 3294 us, meets deadline
+ logging task: U = 0.830, Liu-Layland bound = 0.743 -> above the bound: inconclusive, check response times
UART logging period 20000 us, response 13666 us, meets deadline
blocking B by a long interrupt handler -> first task to miss its deadline
B = 0 us: none
B = 60 us: none
B = 82 us: none
B = 90 us: current loop
The four tasks use 63% of the processor, below the 75.7% bound, so they pass at once. Adding the logging task raises the load to 83%, above the 74.3% bound, so the bound cannot decide; but the logging task’s response time is 13,666 µs, less than its 20,000 µs deadline, so it truly passes. Being above the bound does not mean failing: compute the response times. Blocking is a different matter. The current loop needs only 18 µs of its 100 µs deadline, so it tolerates blocking of up to 82 µs, but if an interrupt handler runs for 90 µs the current loop misses its deadline immediately, although the total processor load has hardly changed. The real-time problem lives in the worst case, not the average. In practice: measure the WCET on the real hardware, keep interrupt handlers short and push heavy work into ordinary tasks, leave a margin, and remember that this calculation relies on the original paper’s assumptions (periodic, independent tasks, constant run time); tasks that share a resource such as a single SPI bus must add the time spent waiting for one another.
Bridging MAVLink and ROS 2: what flows between the drone and MM-1
MM-1 speaks ROS 2, but the flight controller of a drone speaks MAVLink, a compact message protocol for drones. Landing on the moving base (Module 3, Example 8) and the approach interlock of Module 5 both need a bridge that turns MAVLink messages into ROS 2 topics and back. Two common bridges exist. MAVROS is a MAVLink-to-ROS 2 gateway that supports Humble and newer ROS 2 releases. It turns a MAVLink autopilot such as PX4 or ArduPilot into ROS 2 topics, services and parameters, and it can also proxy a ground station over the same link (MAVROS, n.d.). uXRCE-DDS is PX4’s own bridge: a client on the flight controller and an agent on the companion computer pass PX4’s internal uORB topics straight into the ROS 2 data space, using the px4_msgs definitions (PX4 Autopilot, n.d.-a).
The first thing a bridge must settle is the coordinate frame. ROS uses x forward, y left and z up for the body, and ENU (x east, y north, z up) for world frames, and names any NED frame with a _ned suffix (Foote & Purvis, 2010). Flight controllers use NED (x north, y east, z down) and FRD for the body. MAVROS converts for you: for local frames it applies 180° about the x axis and 90° about the z axis (MAVROS, n.d.). With uXRCE-DDS, PX4 topics stay in NED and FRD, so your ROS 2 node must convert them itself (PX4 Autopilot, n.d.-a). For a vector the rule is short: .
The data that flows in this cell is small but each item matters (MAVLink Development Team, n.d.):
- Drone to robot:
HEARTBEAT(is the drone still on the link, and is the armed flag set inbase_mode),EXTENDED_SYS_STATE(landed_state), and the drone’s local position and velocity - Robot to drone:
LANDING_TARGETwith the pad position (PX4 accepts onlyMAV_FRAME_LOCAL_NEDand reads only x, y, z; ArduPilot accepts body FRD), and, if a ROS 2 node flies the drone in offboard mode, speed setpoints inSET_POSITION_TARGET_LOCAL_NED(fieldsvx,vy,vzin NED). PX4 needs that setpoint stream at 2 Hz or more as proof of life, and leaves offboard mode if it stops for longer thanCOM_OF_LOSS_T(PX4 Autopilot, n.d.-b) - Time:
LANDING_TARGETcarriestime_usecand the setpoint carriestime_boot_ms, so the receiver can compute the age of every value, exactly as tf2 looks up the transform at the capture time
Example 9 Frames and link load for landing on the moving base
Frames. The base drives in the map frame (ENU) at m/s, and the pad sits at m. Assume that map and the drone’s local frame share their origin and are aligned (otherwise one more tf2 transform comes first). In NED the speed becomes m/s and the pad m; the height turns negative because z points down. A heading of 30° in ENU (measured from east, counterclockwise) is in NED (from north, clockwise). If a node forgets the swap and sends as north and east, the speed error is m/s. With the per second of Module 3, Example 8, the drone then trails the pad by m, most of the 0.20 m acceptance radius, before any other error is counted.
Link load. The bridge sends LANDING_TARGET and a speed setpoint at 20 Hz each and receives a HEARTBEAT at 1 Hz (rates assumed). From the field lists in common.xml, the full payload of LANDING_TARGET is bytes, of SET_POSITION_TARGET_LOCAL_NED bytes, and of HEARTBEAT 9 bytes. A MAVLink 2 packet adds a 10-byte header and a 2-byte checksum, 12 bytes in all, plus 13 bytes if the packet is signed (MAVLink Development Team, n.d.). The load is therefore
A 57,600 bit/s serial link with 10 bits per byte (8 data bits, start and stop) carries 5,760 bytes/s, so the bridge uses 47.9% of it, and 57.2% (3,294 bytes/s) when every packet is signed. MAVLink 2 also trims trailing zero bytes from the payload, so real packets can be shorter, but a design should count the worst case. The load fits, yet it leaves little room for logs and images, so these go over a separate link. Age matters as much as load: at a relative speed of 0.5 m/s, a pad position 0.1 s old is 0.05 m off and one 0.3 s old is 0.15 m off. The receiver must therefore read the timestamp, extrapolate or discard old values, and fail closed when the link goes quiet.
Module lab
Lab: assemble the software chain and interfaces of MM-1
- Write the node graph of the cell as in Figure 1, set the QoS of each topic, check compatibility with
ros2 topic info --verbose, and record the result of one deliberately mismatched pair - Measure the timing of a 100 Hz timer when it shares a thread and group with the image-detection callback, then separate them into different groups and threads, and compare with example 1
- Stamp images at exposure, look up the transform at that time with tf2, compare with using the latest pose, and report the parcel position error measured with a ruler
- Set
cmd_vel_timeoutto at least three values, count needless stops over a one-hour run, and measure the stopping distance when a real network cable is pulled - Open the life cycle of the driver node, command configure and activate from the tool, then unplug the CAN adapter and activate, and look at the state it returns to
- Connect the encoder of a test joint, decode it in hardware, check the count for one turn, turn slowly and fast, and check the counter-wrap handling. Measure the gyro bias for 5 s and report the heading error after 60 s with and without subtracting it
- Calculate the CAN load of all joints of the test arm with the code of example 7 and compare it with the bus load measured with an analyser
Common mistakes
Watch out
- Putting every callback in the default group and assuming a multi-threaded executor makes them parallel by itself
- Using the latest pose instead of the pose at the stamp, and thinking a higher tf rate alone will fix it
- Setting incompatible QoS on publisher and subscriber, so no data flows and no obvious message says why
- Disabling the command timeout, or setting it shorter than the network jitter so the robot stops too often
- Letting a hardware node start sending commands as soon as it is created, with no life cycle, so the system starts in the wrong order
- Reading a 16-bit counter and subtracting directly, which gives a speed jump at every wrap
- Not subtracting the gyro bias at start-up, although a bias of 0.2 degrees per second makes the heading 12 degrees off in a minute
- Choosing a bus from the datasheet speed without calculating the load and the worst-case response of the lowest-priority message
Summary
- ROS 2 splits work into nodes, topics, services and actions, with tf2 handling frames over time and DDS with QoS handling data delivery
- Executors and callback groups decide whether the control loop is blocked; heavy work must be separated from it by group and thread
- Look up the transform at the stamp of the measurement; tf2 interpolates, and the error in the example is below 1 mm while the latest pose is 41.6 mm off
- QoS must be compatible, and the command timeout trades needless stops against stopping distance
- The node life cycle lets the start-up sequence be checked and stopped halfway, and ros2_control separates controllers from hardware
- Decode the encoder in hardware, take counter differences circularly, subtract the gyro bias at start, and choose the PWM frequency from the ripple current
- Choose a bus by calculating load and worst-case response time: CAN cannot cope at 1 kHz with 12 messages, while EtherCAT uses under 2%
- The MCU runs the fast loops (current and speed) while the onboard computer runs perception and planning. Check deadlines with the bound , which is sufficient but not necessary, and with response times that include blocking. The real-time problem lives in the worst case, not the average.
Check your understanding
- A 20 ms timer is due first at 20 ms, but a single-threaded executor is running a heavy callback from 0 to 90 ms. When does the timer first run, when is its next call scheduled, and how many periods are skipped (by the rcl rule)?
- The base moves at 0.25 m/s and a detection is 80 ms old. If the latest pose is used instead of the pose at the stamp (translation only, ignoring rotation), by how many mm is a parcel that you believe to be still in the odom frame displaced?
- Can a best-effort publisher connect to a reliable subscriber? And a reliable publisher to a best-effort subscriber?
- With
cmd_vel_timeout0.3 s, a base moving at 0.4 m/s and braking at 0.8 m/s², what is the stopping distance after the commands are really lost? - A 16-bit counter reads 65,500 and the next read is 120. What is the true difference?
- What is the worst-case transmission time in µs of a 6-byte CAN message at 500 kbit/s?
- How long do the data bits of a Modbus RTU read of 10 registers occupy the line at 19,200 bit/s (not counting the silent gaps)?
Answers
- The timer runs at 90 ms (70 ms late). At the call, the schedule moves to , which is still below 90, so it moves a further periods, giving the next call at 100 ms. The periods due at 40, 60 and 80 ms are skipped: 3 periods
- m = 20 mm
- A best-effort publisher cannot connect to a reliable subscriber. A reliable publisher can connect to a best-effort subscriber
- m
- counts (the counter wrapped past 65,535 to 0)
- The request is 8 bytes and the response is bytes, so 33 bytes × 11 bits = 363 bits, and at 19,200 bit/s that is ms
Key formulas
| Circular difference of a 16-bit counter | |
| Gyro bias accumulating into angle | |
| PWM current ripple | |
| Worst-case CAN frame time | |
| Worst-case CAN response time | |
| Rate-monotonic bound and response time |
Key references
- Macenski, S., Foote, T., Gerkey, B., Lalancette, C., & Woodall, W. (2022). Robot Operating System 2: Design, architecture, and uses in the wild. Science Robotics, 7(66), eabm6074. link
- Open Robotics. Actions. ROS 2 documentation (Jazzy). link
- Open Robotics. Executors. ROS 2 documentation (Jazzy). link
- Open Robotics. Using callback groups. ROS 2 documentation (Jazzy). link
- Open Robotics. rcl_timer_call (rcl/src/rcl/timer.c), ros2/rcl repository, jazzy branch. link
- Open Robotics. Learning about tf2 and time. ROS 2 documentation (Jazzy). link
- Open Robotics. TimeCache::interpolate and extrapolation checks (tf2/src/cache.cpp), ros2/geometry2 repository, jazzy branch. link
- Open Robotics. Quality of Service settings. ROS 2 documentation (Jazzy). link
- ros2_control Maintainers. Diff drive controller. ros2_controllers documentation (Jazzy). link
- Open Robotics. Managed nodes. ROS 2 design documents. link
- ros2_control Maintainers. Getting started. ros2_control documentation (Jazzy). link
- Woodman, O. J. (2007). An introduction to inertial navigation (Technical Report UCAM-CL-TR-696). University of Cambridge, Computer Laboratory. link
- Davis, R. I., Burns, A., Bril, R. J., & Lukkien, J. J. (2007). Controller Area Network (CAN) schedulability analysis: Refuted, revisited and revised. Real-Time Systems, 35(3), 239–272. link
- International Organization for Standardization. (2024). Road vehicles — Controller area network (CAN) — Part 1: Data link layer and physical coding sublayer (ISO 11898-1:2024). link
- Modbus Organization. (2012). MODBUS application protocol specification V1.1b3. link
- Modbus Organization. (2006). MODBUS over serial line specification and implementation guide V1.02. link
- EtherCAT Technology Group. EtherCAT technology: Principles of operation (processing on the fly, cycle time, distributed clocks). link
- Lynch, K. M., & Park, F. C. (2017). Modern robotics: Mechanics, planning, and control. Cambridge University Press. link
- Liu, C. L., & Layland, J. W. (1973). Scheduling algorithms for multiprogramming in a hard-real-time environment. Journal of the ACM, 20(1), 46–61. link
- micro-ROS project. Features and architecture. micro-ROS documentation. link
- The Linux Kernel documentation. Theory of operation. In Real-time (PREEMPT_RT) documentation. link
- MAVLink Development Team. MAVROS: MAVLink to ROS gateway (ROS 2). link
- MAVLink Development Team. (n.d.). Coordinate frames. MAVROS documentation (ros2 branch). GitHub. link
- PX4 Autopilot. ROS 2 user guide (uXRCE-DDS bridge and frame conventions). PX4 user guide (main). link
- Foote, T., & Purvis, M. (2010). REP 103: Standard units of measure and coordinate conventions. ROS Enhancement Proposals. link
- MAVLink Development Team. MAVLink common message set (common.xml). link
- MAVLink Development Team. (n.d.). Packet serialization. MAVLink developer guide. link
- PX4 Autopilot. Offboard mode (multicopter). PX4 user guide (main). link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
ROS 2 และการเชื่อมต่อกับ flight stack
อินเทอร์เฟซอนุกรม UART I2C SPI CAN และ DroneCAN
Deep dive: from embedded systems to AI robots and ROS
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results