A CAN Joint Controller

Cut the cable to a robot joint and a naive joint keeps turning at 0.8 rad/s into its hard stop. A guarded joint notices in 30 ms and brakes itself. Build that guard, one check at a time.

Learn how the firmware of a robot joint listens to a main controller over a CAN bus, decides which commands to believe, and stops safely when it can no longer believe any.

Pick Naive joint, press Cut the cable and watch the arm. Press Reset, pick Guarded joint, and cut it again. Then we build each guard from zero: the bus, the clock, the counters, the limits and the stop.

You need a feel for what a motor and a speed command are and a little C for the code. We build the rest from zero: the bus, the checks and the stop.

Built from primary sources, listed in the Field Guide: the CAN frame and error rules, the STM32 bxCAN reference manual and HAL, CANopen error control from CAN in Automation, and AUTOSAR E2E Profile 1. The arm, the speeds and the timings are a model, not a real robot.

Cut the cable

A model, not a robot: every 10 ms the main controller sends a speed command for each joint (0.8 and 0.6 rad/s, reversing at turn points). Hard stops are at 1.2 and 1.1 rad. The guarded joint is the one this lesson builds, with a 30 ms deadman. All speeds, lags and stop rates are illustrative.

Chapter 0

Why a Joint Must Not Trust Its Last Command

See what happens to a moving arm when its commands stop making sense, and meet the five guards this lesson builds

Picture the elbow of a robot arm. A small circuit board sits right next to its motor. A cable runs from that board up the arm to a computer in the robot’s torso. Every 10 ms the computer sends the elbow one number: how fast to turn.

Now the cable works loose. Or the torso computer crashes and reboots. Or it freezes in the middle of a loop. The elbow has just been told “turn at 0.8 radians per second”. Nobody tells it to stop. What does it do?

If the firmware on that small board does the simple thing, it keeps doing what it was last told. The elbow keeps turning. It turns until something hard stops it, and that something might be a table, a wall or a person. The hero at the top of this page showed this: the naive joint drove into its hard stop at the full 0.8 rad/s.

The idea in plain words

A command is a promise about the next few milliseconds. “Turn at 0.8” is true for about 10 ms. After that, only a newer command can say what is true now. The joint must act only on promises that are still fresh, and it must have a plan for the moment when none arrive.

That plan lives in firmware: the program that runs on the small chip inside the joint, with no operating system between it and the hardware. This lesson builds that program’s guard, one check at a time. It is the capstone of the motor track, so it uses ideas from three lessons: CAN and EtherCAT for the wire, motor control firmware for the fast loop inside the joint, and fail-safe design and functional safety for what a safe state is. We re-teach what we need, so you can read this one first.

Two computers, two speeds

Why two computers at all? Because the two jobs run at different speeds. The main controller plans the motion of the whole arm. It runs a loop of maybe 100 times a second and it may run a big operating system. The joint controller closes the fast loop around one motor, maybe 1,000 times a second or more, and it must never wait for anyone. The sensor and actuator integration lesson draws these nested loops. Here the slow loop talks to the fast loop through a bus.

A bus is a shared wire that many chips use to send each other messages, like a group chat on two copper wires. The bus used in cars and robots is the CAN bus (Controller Area Network). Every message on it is a frame. A frame carries an identifier that names what the message is about, and up to 8 bytes of data. Nobody addresses a frame to a chip. Chips listen for the identifiers they care about. Chapter 1 opens one frame bit by bit.

Feel the cost of a stale command

Here is the size of the danger, as a number. If the joint keeps obeying a command that is age milliseconds old, the arm keeps moving for that long. The tip of the arm moves speed × reach × age. Drag the age and the speed.

Count the blind distance

The line shows how far the arm tip travels while the joint obeys a command of the given age. The two dashed marks are one command period (10 ms) and the deadman window this lesson uses (30 ms). Drag both sliders.

100 ms
0.8 rad/s

Illustrative: the tip is 0.5 m from the joint axis, so the tip speed is the joint speed times 0.5 m. One joint, constant speed, no braking. Real arms vary; the arithmetic does not.

On real hardware. Put a CAN transceiver chip on an STM32 Nucleo-F446RE (its bxCAN needs one) and send a speed frame every 10 ms to a second board. Pull the cable. Toggle a GPIO pin the moment the second board decides the link is dead, and measure the time from the last frame on a logic analyzer. That time is your blind time.

At 0.8 rad/s and a 100 ms old command, the tip moves 40 mm. That is the width of a thumb, in a direction nobody chose. At 500 ms it moves 200 mm. The distance grows in a straight line with the age, so the cheapest safety feature is a firmware check that keeps the age small.

The five guards

The joint can protect itself in five ways. Each one answers a different question, and each one fails to catch something the others catch. The capstone chapter lets you switch them on and off one by one against five injected faults.

  1. The bus: what a CAN frame is, and how two chips share one wire.
  2. Time on the bus: how long a frame takes and how busy the wire gets.
  3. Mailboxes: how the CAN peripheral holds frames, and why an old command can wait inside it.
  4. Trust: a counter, a timestamp and a checksum, so the joint can tell fresh from stale from damaged.
  5. The deadman: a timer that fires when good commands stop.
  6. Limits: caps on speed, force and position that hold even for a wrong command.
  7. Safe stop: what the joint does when the deadman fires.
  8. Faults on the bus: error counters, error passive and bus-off.
  9. The capstone: a two-joint arm over a virtual bus with five faults to inject.
  10. Field guide: numbers, a checklist, the core code and where to go next.
The torso computer freezes. The joint receives nothing more. A naive joint keeps its last speed command. Why is that dangerous?

Chapter 1

One Wire, Many Voices: Frames and Arbitration

Open a CAN frame bit by bit and watch three chips fight for the wire without losing a single message

Your arm has a torso computer and two joint boards. All three hang on the same two wires. At one instant the torso wants to send the elbow its speed, the shoulder wants to report its angle, and a safety button wants to shout “stop”. Three voices, one wire, no referee. Who speaks first?

A first idea is a turn-taking schedule. That works, but one failed chip can stall everyone. CAN uses a smarter trick. Every chip may start talking whenever the wire is idle. If two start together, the wire itself settles it, in the middle of the message, and nobody loses a bit of the winning message.

A wire that can only say 0 loudly

The trick rests on how the wire is driven. A chip can pull the two wires apart, which is a dominant bit and counts as logical 0. Or it can let them rest, which is a recessive bit and counts as logical 1. If one chip pulls and another rests, the wire shows the pull. So the wire always shows the AND of everything sent: a 0 from anyone beats a 1 from everyone else.

Every chip also listens to the wire while it sends. Suppose a chip sends a recessive 1 and hears a dominant 0. It knows another chip is talking at the same time, with a smaller number at this position. It stops at once, falls silent and waits for the wire to go idle.

The frame, field by field

The number that decides the fight is the identifier, 11 bits in the standard frame, sent first (right after a start bit). Smaller identifier means more important message. The bits that follow describe and protect the data. Here is the whole classical CAN frame with 8 data bytes. The sizes are the standard layout; the sum is worked out below.

FieldBitsJob
Start of frame1One dominant bit that wakes every listener.
Identifier11Names the message and sets its priority.
RTR, IDE, r03Flags: remote request, extended format, reserved.
Data length code4How many data bytes follow (0 to 8).
Data0 to 64The payload: up to 8 bytes.
CRC15A checksum over the fields so far.
CRC delimiter, ACK slot, ACK delimiter3Receivers pull the ACK slot dominant to say “I got it”.
End of frame7Seven recessive bits close the frame.
Interframe space3At least three recessive bits before the next start.

With 8 data bytes the fields add up to 1 + 11 + 3 + 4 + 64 + 15 + 3 + 7 + 3 = 111 bit times. Classical CAN carries at most 8 data bytes per frame. Chapter 2 turns the 111 into microseconds.

Choosing identifiers for the arm

Because the smaller number wins, the identifier plan is the priority plan. A good rule: the more dangerous it is to miss a message, the smaller its identifier. This plan is our design for the lesson (it is not a standard):

Let us run the fight by hand. In 11 bits, 0x010 is 00000010000, 0x101 is 00100000001, 0x102 is 00100000010 and 0x201 is 01000000001. At bit 2 the status frame sends a 1 where the stop frame (and the commands) send a 0, so the status frame backs off first. At bit 3 the stop frame sends 0 and the commands send 1, so the commands back off. Between the two commands, the first difference is bit 10: 0x101 sends 0 and 0x102 sends 1, so joint 2’s command waits.

Fight for the wire

Choose who starts sending at the same instant, then press Step to send one identifier bit at a time. A chip that sends 1 while the bus shows 0 loses and falls silent (red).

Only the 11 identifier bits are drawn; the rest of the winning frame follows unchanged. Losers retry when the wire is idle again. Frame size and timing at 1 Mbit/s: 111 bit times, 111 µs, for 8 data bytes before stuffing (Chapter 2).

On real hardware. Use two Nucleo-F446RE boards with transceivers, and a 120 ohm resistor at each end of the bus. Trigger both boards from one shared GPIO so they start together, one sending 0x101 and one sending 0x102. Decode the bus with a logic analyzer or oscilloscope: 0x102 should go quiet at identifier bit 10, and the full 0x101 frame should follow.

Bit stuffing: why 111 is not the end of the story

A receiver finds the edges of bits by watching the wire change. A long run of identical bits has no edges, and the receiver’s clock could drift. So after five equal bits in a row the sender inserts one bit of the opposite value. This is bit stuffing. The receiver removes it again. Stuffing covers most of the frame, but not the CRC delimiter, the ACK field or the end of frame. Six equal bits in a row inside the stuffed part is an error. Stuffing makes the real frame longer than 111 bits, by up to one extra bit per four, and Chapter 2 counts the worst case.

Two chips start sending together, with identifiers 0x120 and 0x0F0. Which frame goes first, and why?

Chapter 2

How Long a Frame Takes, and How Full the Wire Gets

Turn bit counts into microseconds, add up the load, and find the point where commands start to arrive late

The arm works well with two joints. Then you add four more joints and a gripper. The motion starts to stutter, but no frame is lost and no check fails. Every message arrives. It just arrives a little later than it should. The bus is not broken. It is too busy.

To see why, we need one number: how long one frame occupies the wire. That is simple arithmetic, and it is the basis of every bus budget.

From bits to microseconds

The bit rate is how many bits the bus sends per second. Classical CAN runs up to 1 Mbit/s on a short bus, and slower rates allow longer wires. At 1 Mbit/s, one bit lasts 1 µs. At 500 kbit/s it lasts 2 µs. The time of a frame is then just its bit count divided by the bit rate.

Chapter 1 counted 111 bit times for an 8-byte frame, including the three bits of interframe space. Stuffing can add more. In the stuffed part, which has 34 + 8n bits for n data bytes, the sender adds at most one bit per four bits after the first. For n = 8 that part has 98 bits, so the most you can add is ⌊97 / 4⌋ = 24 bits. The worst-case frame is therefore:

111 + 24 = 135 bit times  →  135 µs at 1 Mbit/s,  270 µs at 500 kbit/s,  1,080 µs at 125 kbit/s

Public references agree with this arithmetic. The Linux kernel’s CAN length header counts 108 bits for a classical frame with an 11-bit identifier and 8 data bytes, and 111 with the 3-bit intermission, both without stuffing. A Vector training page gives 24 as the largest number of stuff bits, and 132 bits as the longest frame without the interframe space. Adding 24 stuff bits to 111 gives our 135. We plan with the worst case, because a safety budget must hold on the unlucky day.

Bus load

Bus load is the fraction of time the wire is busy. It is the bits sent per second divided by the bits the bus can carry per second. Work it for our two-joint arm. Every 10 ms (100 Hz) the main controller sends one frame per joint, each joint sends one status frame, and the main controller sends one stop-or-heartbeat frame. That is 2 × 2 + 1 = 5 frames per cycle.

5 frames × 135 bits × 100 cycles/s = 67,500 bit/s  →  6.75% of 1 Mbit/s,  13.5% of 500 kbit/s

That is a comfortable bus. Now count a bigger arm: 6 joints is 13 frames per cycle, which is 175,500 bit/s. At 125 kbit/s the demand is 140% of what the wire can carry. It cannot fit, so frames queue, and queued commands grow old. The slider below lets you find your own limit.

Latency: the frame that has to wait

Load tells you the average. The joint cares about the worst moment. CAN arbitration does not interrupt a frame once it has started its data. A very urgent stop frame that becomes ready a moment too late must wait for the frame already on the wire. That is up to 135 bit times, or 270 µs at 500 kbit/s. This delay is called blocking.

The next worry is a burst. Suppose the main controller queues all frames of a cycle at the same instant. They leave one after another in identifier order: stop first, then the commands, then the statuses. The last frame ends after all the frames together. For 13 frames at 500 kbit/s that is 13 × 270 µs = 3.5 ms of a 10 ms cycle. That is fine. At 125 kbit/s it is 14 ms, longer than the cycle, and the queue never empties.

Fill the wire

The bar is one control cycle. Each block is one frame in priority order: the stop frame, then every command, then every status. Change the joints, the rate and the bit rate until a block runs past the cycle.

2
100 Hz

Simplified: every frame carries 8 data bytes, all frames are ready at the start of the cycle, nothing is retransmitted, and the bus has no other traffic. Frame length: 135 bit times worst case, 111 without stuffing, as worked above. Real systems add other traffic and jitter.

On real hardware. Send an 8-byte frame at 500 kbit/s with the payload all zeros, then with 0x55 in every byte. Measure start of frame to the end of the interframe space on the analyzer. The 0x55 pattern gives about 222 µs (111 bits at 2 µs). The zeros add stuff bits and take longer; the worst case is 270 µs.

Try 6 joints at 125 kbit/s and 100 Hz. The blocks run far past the end of the cycle and the load reads above 100%. Switch to 500 kbit/s and everything fits. The remedy is almost always a faster bit rate or fewer, smaller frames. Choosing it is a design step, so write the budget down before you write the driver.

Why the joint cares: age on arrival

Every millisecond a command waits in a queue is a millisecond of age when it reaches the joint. In Chapter 4 the joint measures that age and refuses commands that are too old. A bus that is nearly full will trigger those refusals again and again, so the bus budget and the age limit are two halves of one design.

At 500 kbit/s, how long does a worst-case classical CAN frame with 8 data bytes (135 bit times) occupy the wire?

Chapter 3

From the Wire to Your Code: Mailboxes, Filters and the Stale Frame

See how a CAN peripheral queues frames, why it can send an old command after a new one is ready, and how to stop it

Your joint firmware never wiggles the wire itself. A hardware block called the CAN peripheral does the bit timing, the arbitration, the stuffing and the checksum. Your code only hands it whole frames and receives whole frames. The place where a frame waits on the way out is a transmit mailbox: a small hardware slot that holds one frame until it has been sent.

We use the STM32 bxCAN peripheral as our example, as found on STM32F4 parts and many others. It has three transmit mailboxes and two receive FIFOs (first-in-first-out queues for incoming frames). On a part with a single CAN instance it has 14 filter banks, and 28 are shared between two instances. These counts come from the STMicroelectronics HAL driver header and the reference manual. Always check the manual for the exact part on your desk.

Which mailbox goes first

Suppose two mailboxes both hold a frame and the bus becomes free. Which one does the hardware send? By default it picks the frame with the lowest identifier, the same rule the wire uses, and if two have the same identifier, the lower mailbox number goes first. A control bit named TXFP in the CAN_MCR register changes this to send-in-the-order-requested, like a queue. The default is usually what you want for a joint: the stop frame always leaves first.

Now the trap. Once a frame is in a mailbox, it stays there until the bus lets it go. By default the hardware also retries a frame that lost arbitration or was hit by an error. That is a good property for a log message and a terrible one for a speed command. If the bus is busy for 30 ms, the mailbox faithfully sends a command that is 30 ms old after a fresher one is already waiting behind it.

The reference manual gives you two tools. First, setting a bit named NART in CAN_MCR (the HAL calls it AutoRetransmission) makes each frame start only once: if it loses arbitration or fails, the hardware does not try again. Second, the abort request bit ABRQ in CAN_TSR (HAL: HAL_CAN_AbortTxRequest) takes a pending frame back out of its mailbox. A pending or scheduled frame is aborted at once. A frame already on the wire either finishes, or fails and is aborted.

Watch a stale frame leave

Each cycle (10 ms) the application writes one new command for each joint. Block the bus for a few cycles, then free it. Compare what leaves the mailboxes under each policy.

A model of the policy, not of the register timing. The bus frees up at the start of a cycle and sends every queued frame, lowest identifier first, before the application writes. “Send once” drops a frame that could not leave in its own cycle. Mailbox rules: STM32F4 and L4 reference manuals (RM0090, RM0351, RM0402).

On real hardware. On the Nucleo, set one GPIO when you call HAL_CAN_AddTxMessage and another in the transmit-complete callback. Hold the bus busy with a second board sending a higher-priority frame in a loop. Measure the write-to-complete delay with and without HAL_CAN_AbortTxRequest.

Run it. With Just write and the bus blocked for three cycles, the mailboxes fill up with commands from cycles 1 and 2, and the newest commands are refused because there is no free mailbox. When the bus frees up, the joint receives the old commands first. With Abort old first, each new command replaces the old command with the same identifier. Only the freshest value waits, and the joint gets that. This rule is called latest wins.

The receive side: filters and the interrupt

Incoming frames pass through acceptance filters before they reach a receive FIFO. The joint board only needs the stop frame 0x010 and its own command 0x101. A filter in mask mode accepts a frame when (id & mask) == (filter & mask). A filter in list mode simply lists exact identifiers. Rejecting everything else in hardware means your interrupt handler never wakes up for status frames of other joints.

When a frame is accepted, the peripheral raises an interrupt. The handler should do almost nothing: copy the frame out of the FIFO, stamp it with the local time, and put it into a small buffer. The decisions of Chapters 4 to 7 run later, in the main loop. This keeps the interrupt short, as the real-time systems lesson recommends.

c/* STM32 HAL, bxCAN. Joint 1 accepts the stop frame and its own command. */
CAN_FilterTypeDef f = {0};
f.FilterBank           = 0;
f.FilterMode           = CAN_FILTERMODE_IDLIST;     /* exact identifiers  */
f.FilterScale          = CAN_FILTERSCALE_32BIT;
f.FilterIdHigh         = 0x010u << 5;               /* standard id sits in the top 11 bits */
f.FilterMaskIdHigh     = 0x101u << 5;               /* in list mode: the second id */
f.FilterFIFOAssignment = CAN_RX_FIFO0;
f.FilterActivation     = ENABLE;
HAL_CAN_ConfigFilter(&hcan1, &f);

void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *h) {
    CAN_RxHeaderTypeDef hdr; uint8_t d[8];
    if (HAL_CAN_GetRxMessage(h, CAN_RX_FIFO0, &hdr, d) == HAL_OK)
        rx_ring_put(hdr.StdId, d, hdr.DLC, now_ticks());   /* copy and stamp; decide later */
}

The failure, as symptom, measurement, fix

Symptom: the arm twitches for one cycle now and then, after a busy moment on the bus. Measurement: log, for every command the joint receives, the difference between its arrival time and the time the main controller wrote it. A healthy system shows about 1 ms. The twitch shows a handful of frames at 20 to 40 ms. Fix: abort the old command before writing the new one, or send commands once. Then protect the joint anyway with the age check in Chapter 4, because a bus can still be late for reasons you cannot control.

The bus was blocked for 30 ms. By default the mailbox sends an old speed command right after the bus frees up. Which fix keeps the stale command from leaving?

Chapter 4

Trusting a Command: Sequence, Checksum and Timestamp

Give every command three small proofs, so the joint can tell a fresh, intact command from a replay, a frozen sender or a late arrival

A frame arrives at the elbow. Its CAN checksum is perfect, and the bus has already confirmed it. Should the elbow obey? Not yet. Perfect bits can still carry a bad command, and three examples show how.

First, the torso program hangs, but the CAN peripheral keeps re-sending the last buffer by itself. Every frame is intact, and every frame says the same old thing. Second, a command sits in a queue for 80 ms and then arrives. It is intact, but it is history. Third, a bug in the torso software copies the wrong variable into the buffer before the CAN hardware computes its checksum. The checksum then proves the wrong value arrived safely.

The CAN checksum protects the wire. It does not protect the meaning. So the application adds its own proofs. Each one answers one question about the command.

Three questions, three small fields

This is a standard idea in cars. The AUTOSAR end-to-end protection specification defines profiles that combine a counter, a data identifier, a CRC and timeout monitoring. Its Profile 1 uses a 4-bit counter that counts 0 to 14 and an 8-bit CRC with polynomial 0x1D (the SAE J1850 CRC) that also covers a data identifier. The same document marks Profile 1 as a legacy profile and tells new projects to use Profile 11. We borrow the idea, not the exact profile: Profile 1 uses different start and final XOR values from our start value of 0.

One command, byte by byte

The frame has 8 data bytes. We lay them out like this. This layout is our design for the lesson.

ByteFieldMeaning
0seqSequence counter, 0 to 255, wraps around.
1 to 2w1Joint 1 speed, 16-bit signed, units of 0.001 rad/s, low byte first.
3 to 4w2Joint 2 speed, same format.
5crcCRC-8 over bytes 0 to 4, followed by a data identifier byte (0x01 for this message).
6 to 7tsTimestamp in milliseconds, 16 bits, wraps every 65.536 s.

Work one by hand. Joint 1 at +0.800 rad/s is 800 = 0x0320, sent low byte first as 20 03. Joint 2 at −0.600 rad/s is −600, which in 16-bit two’s complement is 65,536 − 600 = 64,936 = 0xFDA8, sent as A8 FD. With seq = 0x2A, the first five bytes are 2A 20 03 A8 FD. Run the CRC-8 recipe over those bytes and then the data identifier 01 and you get 0xED. The device below does this arithmetic live.

Why the timestamp lives last

The timestamp sits in bytes 6 and 7 for a hardware reason. The STM32 bxCAN peripheral has a time-triggered communication mode. When you enable it and ask for the global time to be sent, the hardware writes a 16-bit time into data bytes 6 and 7 of the frame, replacing whatever your software put there. The HAL header says exactly this: the timestamp “is sent in DATA6 and DATA7 replacing pData[6] and pData[7]”, and that time-triggered mode must be on. Two cautions. That hardware timer counts in units set by the CAN bit timing, not in milliseconds, so scale it or write your own millisecond stamp in software before you use it as the age. And ST errata for some parts say time-triggered mode is not supported, so check the errata of your exact part. Because the hardware writes it after your code, the CRC cannot cover those bytes. That is why the CRC covers bytes 0 to 4 only.

This has a deep consequence. A hardware timestamp proves when the frame was sent. It does not prove that the command was fresh. A frozen program with a live CAN peripheral keeps sending old data with new timestamps. The age check sees a young frame and accepts it. Only the sequence counter notices that the command never advanced. You need both.

Break a command

The top row is the frame the joint receives, byte by byte. Pick a kind of damage. The checks below recompute from the received bytes only, as the joint would.

The joint’s clock reads 1,000 ms and the last command it accepted had sequence 41. CRC: 8 bits, polynomial 0x1D, start value 0, run over bytes 0 to 4 and then the data identifier 0x01 (our layout; the polynomial is the SAE J1850 one used by AUTOSAR E2E Profile 1). Age limit 30 ms, speed limit 2 rad/s (Chapter 6). Clocks are assumed to agree.

On real hardware. Compute the CRC in software, then flip one bit of the transmit buffer afterwards (on purpose) and send. Count the frames the receiver rejects. Then stop updating the counter and keep sending to reproduce the frozen sender. Check that each case is caught by the check this chapter says.

Try each button. Flip one bit is caught by the CRC alone. Replay old frame and Frozen sender look healthy to the CRC; the frozen one even passes the age check, because its timestamp is fresh. Only the sequence counter catches it. 80 ms late is intact and new, so only the age check catches it. Three frames lost is not a rejection: the counter jumped by 4, and the joint learns it missed 3 commands. The last button is the sobering one: a wrong but well-formed command passes all three checks. Chapter 6 deals with that.

The check, as code

ctypedef enum { CMD_OK, CMD_BAD_CRC, CMD_STALE_SEQ, CMD_TOO_OLD } cmd_status_t;

static uint8_t crc8_1d(const uint8_t *p, int n, uint8_t crc) {
    for (int i = 0; i < n; i++) {
        crc ^= p[i];
        for (int b = 0; b < 8; b++)
            crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x1D) : (uint8_t)(crc << 1);
    }
    return crc;
}

cmd_status_t cmd_check(const uint8_t rx[8], uint16_t now_ms, uint8_t *last_seq) {
    uint8_t c = crc8_1d(rx, 5, 0x00);
    c = crc8_1d(&(uint8_t){0x01}, 1, c);               /* data id, not sent on the wire */
    if (c != rx[5]) return CMD_BAD_CRC;                 /* intact?  */

    uint8_t delta = (uint8_t)(rx[0] - *last_seq);       /* modulo 256 */
    if (delta == 0 || delta > 127) return CMD_STALE_SEQ; /* new?     */

    uint16_t ts  = (uint16_t)(rx[6] | (rx[7] << 8));
    uint16_t age = (uint16_t)(now_ms - ts);             /* modulo 65536: survives the wrap */
    if (age > 30) return CMD_TOO_OLD;                   /* recent?  */

    *last_seq = rx[0];
    return CMD_OK;
}

Two details deserve attention. The sequence test uses subtraction modulo 256, so the counter can wrap from 255 to 0 without a false alarm, and a value that went backwards shows up as a large delta. The age test uses subtraction modulo 65,536 for the same reason. The age check also assumes the two clocks agree. If the torso clock and the joint clock drift apart, the age drifts with them. The multi-sensor time-sync lessons in this series (starting with what time is it on a chip) show how to keep clocks aligned.

The torso program hangs, but the CAN peripheral keeps sending the last buffer, with a fresh hardware timestamp on every frame. Which check catches it?

Chapter 5

The Deadman Timer: Noticing Silence

Choose how long the joint waits for a good command before it gives up, and see what a too-short and a too-long window each cost

The train driver holds a handle. If the driver lets go, because of a faint or a heart attack, the train brakes by itself. The handle does not ask the driver whether things are fine. It treats silence as the signal. This is a deadman switch, and it is the oldest safety idea in this lesson.

A joint needs the same thing. It cannot ask the torso computer “are you still there?” and wait, because the torso might be the thing that died. Instead the joint keeps a stopwatch. Every good command restarts it. If the stopwatch reaches the limit, the joint decides that nobody is steering and stops.

The rule, and the one thing that may feed it

In firmware the stopwatch is one number: the time of the last valid command. A fast periodic task, running every millisecond, compares the clock against it. The word “valid” matters most. If any arriving frame fed the stopwatch, a frozen sender would keep it fed for ever, and a bus jam that delays old frames would too. Only a command that passes the Chapter 4 checks may restart it.

c/* Runs every 1 ms from a timer interrupt (or the 1 kHz control tick). */
void joint_tick_1khz(void) {
    if (state == JOINT_RUN && (uint32_t)(now_ms - last_valid_ms) > DEADMAN_MS)
        enter_safe_stop(CAUSE_DEADMAN);               /* Chapter 7 */
}

/* Called from the main loop for every frame taken out of the receive ring. */
void on_command(const uint8_t rx[8]) {
    if (cmd_check(rx, now_ms, &last_seq) == CMD_OK) { /* Chapter 4: intact, new, recent */
        last_valid_ms = now_ms;                       /* feed the deadman ONLY here */
        apply_target(rx);
    }
}

Two more rules. First, the stop is latched: once the joint has stopped, good commands coming back do not restart it by themselves. An arm that springs back to life the moment a cable is re-seated would surprise the person who just plugged it in. A person or a supervisor must clear the stop on purpose. Second, the deadman is armed only after the first valid command, and the joint powers up stopped.

A cousin: the hardware watchdog

Do not confuse this with the hardware watchdog built into most microcontrollers. A watchdog timer resets the whole chip if the program forgets to feed it, so it catches a frozen joint program. The deadman catches a silent torso. You want both. Feed the watchdog from the main loop only when every task has made progress, and feed the deadman only from valid commands. They guard different failures. The fail-safe lesson covers watchdogs in depth.

The industrial world has a standard version of the same idea. In CANopen, a device can send a heartbeat: a small frame with the identifier 0x700 plus its node number, sent at a configured period (object 1017h) and carrying its current state. A consumer raises an error when the heartbeat stops. CAN in Automation no longer recommends the older node guarding, which polled each node with remote frames, and prefers the heartbeat. In our joint, the command stream itself plays the heartbeat role, and the status frame plays the joint’s heartbeat back to the torso.

How long should the window be?

Two forces pull in opposite directions. A short window stops the arm sooner after a real fault. A long window rides out ordinary trouble: one frame lost to noise, or a late frame because the torso’s operating system was busy for a few milliseconds. Too short, and the arm halts for no reason. Too long, and the arm turns blind for longer.

The window is counted in command periods. With a 10 ms period, a window of 30 ms means the joint tolerates two missing commands and stops on the third. In symbols: window = (missed commands you tolerate + 1) × period, plus a margin for jitter. And the cost of waiting is the Chapter 0 arithmetic: at 0.8 rad/s with a 0.5 m reach, a 30 ms window lets the tip move 0.8 × 0.5 × 0.03 = 12 mm before the stop even begins.

Set the window

The stream is 2,000 commands (20 s) with random jitter and random loss. The red line counts false trips: gaps between good commands longer than the window. The yellow line is how far the tip travels blind after a real cut. Drag the window and the two noise sliders.

30 ms
2.0 ms
5%

Illustrative stream: commands are due every 10 ms, each arrives with a bell-shaped random delay of the chosen spread (never early, never reordered) and is lost with the chosen probability. The seed is fixed, so the same settings give the same count. Blind travel uses a 0.8 rad/s joint and a 0.5 m reach.

On real hardware. Log the gap between valid commands for an hour, using the Cortex-M cycle counter or a 1 kHz timer, while the main controller (a Linux computer, say) does its normal work. Keep the largest gap and a histogram. Choose the window above the largest gap you trust, with margin.

Set the loss to 5% and the jitter to 2 ms. A 10 ms window trips constantly, because every single lost frame is a gap of 20 ms. A 30 ms window trips only when three frames in a row are late or lost. A 60 ms window almost never trips, but the arm now moves 24 mm blind. There is no free choice. You pick the point where the false trips are rare enough to live with and the blind travel is small enough to be safe.

The failure, as symptom, measurement, fix

Symptom: the arm stops by itself a few times an hour, and the log says CAUSE_DEADMAN. Measurement: record the largest gap between valid commands over a long run, and keep a histogram of gaps. If the biggest gap is 34 ms with a 30 ms window, you have found the cause. Fix: first ask why a gap happens. A torso process that is not scheduled in real time can pause for tens of milliseconds, which the real-time Linux and robot real-time performance lessons explain. Fix the source if you can. Widen the window only as far as the safety margin of Chapter 7 allows.

Why should only commands that pass the intact, new and recent checks restart the deadman stopwatch?

Chapter 6

Limits: Speed, Torque and the Braking Envelope

Cap what the joint will do even for a command that is intact, new, recent and wrong

A programmer on the torso team makes a unit mistake. The planner thinks in degrees per second, and one line sends 5 where it meant 0.087. The frame goes out with a perfect CRC, the right counter and a fresh timestamp. The deadman is happy, because commands keep arriving. Every check from Chapters 4 and 5 says “obey”.

The only thing left between that bug and a wall is the joint’s own firmware. This is the oldest rule of safe machines: the last line of defence must be local and simple. It lives next to the motor. It does not depend on the planner, the network or anyone else being right.

Three limits and what each one is for

The third one needs care, because it asks “how fast may I go here?” The answer comes from school physics. If the joint can brake at a rate a, then from speed v it needs a distance v² / (2a) to stop. Turn this around: with a distance d left before the soft limit, the highest speed from which it can still stop is:

vmax
The highest speed the joint may use right now, in rad/s, toward the limit.
a
The braking rate the joint can always deliver, in rad/s². Use a value you can guarantee, not the best case.
d
The distance left to the soft limit, in rad.

soft limit 1.05 rad, a = 6 rad/s²: at 0.90 rad, d = 0.15 and vmax = √1.8 = 1.34 rad/s  ·  at 1.00 rad, d = 0.05 and vmax = 0.77 rad/s  ·  at 1.04 rad, d = 0.01 and vmax = 0.35 rad/s

So the envelope costs nothing in the middle of the range, where vmax is large, and it gently squeezes the speed as the joint nears the end. The joint arrives at the soft limit at rest, with the gap to the hard stop as a safety margin.

Clamp or reject?

Two ways to treat a command that is over the limit. To clamp is to replace it by the limit: 1.3 rad/s becomes 1.0 rad/s. To reject is to throw it away and count it as invalid. Use both. A value slightly over the limit is a normal planner overshoot, so clamp it and carry on. A value far over the limit, say twice the limit, cannot be a real plan. Reject it, and do not let it feed the deadman. Then a stream of absurd commands ends in a safe stop (Chapter 7) after one deadman window, instead of pinning the joint at its limit for ever.

Hold the line

Pick a bad command. The top plot is joint angle against the soft limit (dashed) and the hard stop (red). The bottom plot is the command (teal, faint) and the speed the joint actually reaches (warm). Switch each limit on and off.

1.0 rad/s
10 rad/s²

Illustrative joint: a first-order speed lag of 0.04 s, inertia J = 0.05 kg·m² (so 10 rad/s² is 0.5 N·m), soft limit 1.05 rad, hard stop 1.2 rad, braking rate in the envelope 6 rad/s². With a limit off, the joint falls back to the hardware's own cap of 6 rad/s and 40 rad/s².

On real hardware. Run a small gimbal or hobby motor with an encoder from a Nucleo and its driver board. Send 5 rad/s and read back the speed from the encoder: it should flatten at your limit. Then command a full-speed run at the soft limit and measure the true braking distance. Compare it to v² / (2a).

Start with everything off and the Wild value command. The joint reaches several rad/s and hits the stop at full speed. Turn on the speed limit: it hits at 1.0 rad/s instead. Turn on the envelope too: the joint glides to a stop at the soft limit and never touches the stop. Now try Held command, the cable-cut case from the hero. The envelope alone saves the hardware, but the joint still drives on to the soft limit and then sits pushed against it for as long as the command stays. Limits protect the iron. The stop of Chapter 7 protects the situation.

The failure, as symptom, measurement, fix

Symptom: the joint slams into the soft limit and the whole arm shudders, or it still reaches the hard stop sometimes. Measurement: log the braking you actually get. Command a full-speed stop and record the distance. If it is longer than v² / (2a) for your chosen a, the envelope is too optimistic. Fix: lower the a in the formula until it is a rate the motor can always deliver (even with a full load and a low supply voltage), and keep a gap between the soft limit and the hard stop that is larger than the speed lag times the top speed (here 0.04 s × 1 rad/s = 0.04 rad).

Keep the limits in flash, set at build time or by a protected service step. A command on the same bus must not be able to change them. Otherwise the same bug that sent 5 rad/s could also raise the speed limit to 6.

A command of 5 rad/s arrives with a valid CRC, a new counter and a fresh timestamp. Which guard still protects the arm?

Chapter 7

Safe Stop: What the Joint Does When It Gives Up

Compare three ways to stop a joint that carries a weight, and choose the one that leaves the arm somewhere safe

The deadman has fired. The joint has decided that no one is steering. Now it must do something. The obvious answer is “turn the motor off”. For a robot arm that lies flat on a table, that is fine. For an arm that holds a weight in the air, it is the worst answer. Without torque, the arm falls.

The right stop depends on the machine. Safety engineers call the place a machine can rest without causing harm its safe state. Deciding what that state is for your joint is a design question, answered before the code is written.

Three stops

The sequence that most joints follow is: stop accepting motion commands, ramp the speed to zero at a fixed rate, hold or brake, report the cause on the bus, and latch until a person clears the stop. Whether the final step needs STO, a brake or both is set by your risk assessment and by the safety standards for your machine (the IEC 61800-5-2 standard defines drive safety functions such as STO; read the standard and the drive’s safety manual for the real requirements, we did not open them for this lesson).

The distance budget

Two things add up before the arm is still. First, the blind time of the deadman window W, during which the joint keeps its old speed v. Second, the braking distance at the guaranteed rate a:

s
The angle the joint turns between the last good command and standstill, in rad.
v
The joint speed when the commands stopped, in rad/s.
W
The deadman window, in seconds. It is the longest the joint can run blind.
v² / (2a)
The braking distance at rate a, in rad.

v = 0.8 rad/s, W = 0.03 s, a = 6 rad/s²: s = 0.024 + 0.8² / 12 = 0.024 + 0.053 = 0.077 rad

The hero showed a total slightly higher, because it adds the second joint and the small extra distance from the speed lag. The planning lesson is the formula: halve the window and you save 0.012 rad. Double the braking rate and you save 0.027 rad. Both choices have a price (more false trips, more stress on the gearbox).

Gravity changes the answer

Try the arm that carries its own weight. The device below models one vertical joint. The link has a mass, and gravity pulls it down with a torque that is largest when the link is horizontal. The joint is rising when the stop begins.

Stop a joint that holds weight

The joint is rising at 0.8 rad/s when the deadman fires at 0.2 s. Choose the stop and watch the angle. The red line is the lowest the arm may go before it hits something.

6 rad/s²

Illustrative link: mass 1.2 kg, centre of mass 0.2 m from the joint, inertia 0.08 kg·m² about the joint, light viscous friction, so gravity torque peaks at 2.35 N·m. The brake takes 30 ms to close once the speed is under 0.05 rad/s. Hard stop 1.2 rad below horizontal. Angles are measured up from horizontal.

On real hardware. Use a joint with a spring-applied holding brake. Measure the brake closing time with a current probe on the coil and the encoder. After the stop, record the angle for ten seconds in the worst pose. A sag means the stop type or the brake time is wrong.

With Coast, gravity wins at once: the link slows, stops, swings back down and hits the lower stop at several rad/s. With Ramp, then hold the link stops a little above where it was and stays, as long as the motor stays powered and the firmware keeps running. With Ramp, then brake it also stays, and it does so without any power at all. Raise the braking rate to see the distance shrink, and notice that the sudden stop also asks the motor for more torque.

The failure, as symptom, measurement, fix

Symptom: after a deadman stop, the arm sags a few millimetres per second, or drops when someone presses the stop button on the pendant. Measurement: run the stop with the arm at its worst pose (horizontal, full load) and plot the angle for ten seconds; check the brake closing time with a current probe on the brake coil. Fix: pick the stop type from the worst pose, not the average one, and test every stop path, including a power cut during the ramp.

A shoulder joint carries a heavy arm against gravity. The deadman fires. Which stop keeps the arm where it is?

Chapter 8

When the Bus Itself Fails: Error Counters and Bus-Off

Watch a damaged connector push a node from healthy to silent, and learn what your firmware should do at each step

A connector at the elbow has a bent pin. Now and then a frame from the elbow board gets garbled on the wire. The bus does not shrug this off, and it does not let one bad node shout for ever. Each CAN node keeps a score of its own mistakes. When the score gets too high, the node is progressively silenced.

This rule is part of CAN itself, and the CAN controller applies it for you. Your firmware does not run it. But your firmware must read the result, because it tells you the link is dying before the deadman does.

Two counters and three states

Every node has a transmit error counter (TEC) and a receive error counter (REC). The rules are simple:

Many controllers also set a warning flag when a counter passes 96, while the node is still error active, the healthy starting state. A passive transmitter does not add to its TEC for an acknowledge error, so a lone node that nobody hears goes error passive but does not reach bus-off.

Recovery from bus-off differs between controllers. A common rule is that the controller must see 128 occurrences of 11 consecutive recessive bits on the wire. Some parts need a restart by software, and the STM32 HAL exposes an AutoBusOff setting for automatic management. Read the manual for your part.

Worked example: how fast does a bad node go quiet?

Take a node whose every transmission fails. Each failure adds 8. After 16 failures the TEC is 128, which is above 127, so the node is error passive. After 32 failures the TEC is 256, above 255, and the node is bus-off. Whether that takes a fraction of a second or a few milliseconds depends on a choice from Chapter 3. If the controller retries a failed frame at once, the 32 failures come one after another within a few milliseconds. If you send once per cycle (no automatic retransmission), the 32 failures take 32 cycles, which is 320 ms at 100 Hz.

What about a node that only fails sometimes? A failure adds 8 and a success removes 1. If a fraction p of transmissions fail, the counter moves on average by 8p − (1 − p) = 9p − 1 per attempt. That is positive when p is above 1/9, about 11%. A connector that corrupts more than one frame in nine will, sooner or later, push the node all the way to bus-off. Below that rate, the counter wanders but stays low.

Walk the error counter

Each cycle the node sends one command. A random share of attempts fail (+8); the rest succeed (−1). The bands show error active, error passive and bus-off. Move the failure rate across 11%.

8%

Illustrative stream: one command attempt per 10 ms cycle, each failing with the chosen chance (seeded noise). With “retry at once” a failed frame is resent immediately, each failed try costing 0.35 ms (a worst-case frame plus an error frame at 500 kbit/s, rounded), until it succeeds or the node is bus-off. Counter rules as listed above (Kvaser CAN protocol tutorial).

On real hardware. Read CAN_ESR over a debug probe or the console once a second. Disconnect one terminating resistor, or touch CANH to CANL briefly, and watch the counters climb. Count the failed frames before the node goes error passive: the model says 16 in a row.

At 8% the counter drifts down and stays near zero. Push to 15% and it climbs: it passes 127 (error passive), then 255 (bus-off), usually within a few hundred milliseconds. Turn on Retry at once at the same rate and look at the time axis: the damage happens faster, because every retry is another chance to add 8.

What the joint firmware should do

Read the counters, and act on the state. In bxCAN the error status register CAN_ESR carries the flags and the counts (error warning, error passive, bus-off, last error code, TEC and REC); check the exact bit layout in your reference manual.

c/* In the 1 kHz tick, after the deadman test. Layout of CAN_ESR: see your RM. */
uint32_t esr = hcan1.Instance->ESR;
uint8_t  tec = (uint8_t)(esr >> 16);
uint8_t  rec = (uint8_t)(esr >> 24);

if (esr & CAN_ESR_BOFF)       enter_safe_stop(CAUSE_BUS_OFF);   /* cannot talk or hear: stop */
else if (esr & CAN_ESR_EPVF)  status.flags |= FLAG_LINK_DEGRADED; /* tell the torso, log it */
else if (tec > 96 || rec > 96) status.flags |= FLAG_LINK_WARNING;

A bus-off joint is, from the arm’s point of view, a joint that has lost its link. The deadman will fire anyway, because no commands reach it. Reading the state still helps: the cause code shows why it stopped, and the warning and passive flags let the torso see the trouble coming, long before the arm stops moving.

Symptom: the arm stops without any deadman message in the log. Measurement: log TEC and REC every second during a run, and note the last values before each stop. A slow climb tells you about a wiring or termination problem; a sudden jump points to a node that was reset or wired wrong. Fix: check the two 120-ohm terminating resistors at the ends of the bus, the connector pins and the cable shield, before you change any firmware.

A node fails every transmission and each failure adds 8 to its transmit error counter. How many failures take it to error passive, and how many to bus-off?

Chapter 9

The Capstone: A Two-Joint Arm With Faults You Choose

Assemble the guards into one pipeline, then break the bus five different ways and see which guard saves the arm

You now have five guards. Each one is small. The skill is in how they fit together, and in knowing which guard answers which fault. This chapter puts the guards into one pipeline and gives you a workbench.

The pipeline inside the joint

Every frame that comes off the bus goes through the same gates, in the same order. The order matters, because each gate protects the next one.

  1. Filter (Chapter 3). Hardware keeps only the stop frame and this joint’s command.
  2. Intact? (Chapter 4). Recompute the CRC. A mismatch means drop the frame and count it.
  3. New? (Chapter 4). The sequence counter must step forward. A repeat is dropped.
  4. Recent? (Chapter 4). The age, from the timestamp, must be under the limit.
  5. Sensible? (Chapter 6). A speed far over the limit is rejected, not clamped.
  6. Feed the deadman (Chapter 5). Only now does the stopwatch restart.
  7. Apply with limits (Chapter 6). Clamp the speed, cap the torque, brake before the soft limit.
  8. Tick (Chapters 5, 7, 8). Every millisecond: has the stopwatch run out, or is the bus-off? If so, enter the latched safe stop.

The state machine on top is small. The joint powers up in INIT, stopped. The first valid command and an explicit enable move it to RUN. Any stop cause (deadman, bus-off, a received stop frame) moves it to SAFE_STOP, which is latched. A person or a supervisor clears it, and it returns to INIT. The cause is reported in the status frame so the torso knows what happened.

Five faults, five answers

The workbench below uses the same arm as the hero. This time you choose which guards are on, and which fault strikes. The five faults are:

Break the bus, save the arm

Choose the guards, then press a fault. The table at the bottom tests all five faults at once with your guard settings, so you can see the whole map. Press Reset to start over.

0 ms
FaultOutcomeTip blind

A model, not a robot (same as the hero). Each fault begins at 1.2 s and the table shows the next 4 s. “Tip blind” is the total joint travel after the fault, in rad, for both joints. Limits include the range check: a speed over 2 rad/s is rejected and does not feed the deadman. Deadman window 30 ms; age limit 30 ms.

On real hardware. Let a second Nucleo play the main controller and add a button for each fault: pause sending, delay frames, repeat the last buffer, corrupt a byte, send 5 rad/s. Log the joint's cause code and the time to standstill for each. Fill in the same table the device builds.

What the map says

Work through the table in order, and keep the arm in mind.

  1. All guards off. Every fault hits the hard stop. This is the naive joint.
  2. Deadman only. The cable cut becomes a safe stop in tens of milliseconds. The other four faults still crash. A frozen sender, a jammed bus and a wild sender all keep the stopwatch fed.
  3. Deadman and age check. The bus jam is now caught: once frames are over 30 ms old they are refused, the stopwatch runs out, and the arm stops. The stuck sender is still obeyed, because its timestamps are fresh.
  4. Deadman and sequence. Now the stuck sender is caught. The jam is not.
  5. CRC. Bit flips are refused. With the deadman on as well, three bad frames in a row also trip the stop, which is the price of a 30 ms window.
  6. Limits. The wild command is contained. It cannot reach the hard stop. With the deadman on as well, the range check also feeds the stop: a rejected value does not restart the stopwatch, so the arm ends in a safe stop.

No single guard covers all five faults. Together they do. That is what defence in depth means: each guard has a blind spot, and the blind spots do not overlap.

The integration failure nobody expects

Slide Torso clock behind by up to 40 ms with every guard on and press Reset. The arm stops in the first 30 ms and never moves. Every command looks old, because the two clocks disagree by more than the age limit. Nothing is broken on the wire. Symptom: the joint refuses all commands right after boot, and the age-reject counter climbs. Measurement: log the age of each accepted-looking frame; a constant offset (here 40 ms) is the signature of unsynchronised clocks. Fix: synchronise the two clocks, as in the many MCUs, one timeline lesson, or measure age relative to the sender’s own previous frame. The age check is only as good as the clock behind it.

With only the deadman and the age check on, which of the five faults still gets through to the hard stop?

Chapter 10

Field Guide: The Joint Guard on One Page

Keep the numbers, the checklist, the core code and the sources, then go on to the lessons that go deeper

A robot joint obeys commands that cross a bus, and a bus can fail in many ways while every frame still looks perfect. The joint therefore guards itself in layers: filters and mailboxes that avoid stale frames, three proofs on every command (intact, new, recent), a deadman that notices silence, limits that hold even for wrong commands, a safe stop that reaches a safe place, and a read of the bus error state. Each layer answers faults the others cannot see.

The numbers and terms

ItemValueWhere it comes from
Classical CAN data per frame0 to 8 bytesCAN frame format (Chapter 1)
Frame length, 8 bytes, no stuffing111 bit times incl. 3-bit interframe spaceSum of the fields; Linux CAN length header (108 + 3)
Frame length, worst-case stuffing135 bit times (24 stuff bits)Vector training page (24 stuff bits); 111 + 24 = 135
Time of a 135-bit frame135 µs at 1 Mbit/s, 270 µs at 500 kbit/sBits divided by bit rate
Bus loadframes/s × bits ÷ bit rateChapter 2
Transmit mailboxes, receive FIFOs (bxCAN)3 and 2ST HAL header (stm32f4xx_hal_can.h)
Filter banks (bxCAN)14 for one instance, 28 shared for twoST HAL header
Mailbox send orderlowest identifier first, or request order with TXFPRM0090 and RM0351
Abort and no-retransmitABRQ in CAN_TSR; NART in CAN_MCRRM0402 and RM0351
Hardware timestamp in a framebytes 6 and 7, needs time-triggered modeST HAL header
AUTOSAR E2E Profile 14-bit counter 0 to 14; CRC-8, polynomial 0x1DAUTOSAR E2E protocol specification R22-11
Error countersTEC +8, REC +1, success −1; warning above 96; passive above 127; bus-off when TEC above 255Kvaser tutorial; Microchip CAN notes
Failures to passive, to bus-off16 and 32 in a row16 × 8 = 128; 32 × 8 = 256
CANopen heartbeatidentifier 0x700 plus node number; period in object 1017hCAN in Automation
Deadman window(missed commands tolerated + 1) × period, plus jitterChapter 5
Braking envelopevmax = √(2 a d)Chapter 6
Stop distances = v W + v² / (2a)Chapter 7

The checklist

  1. Write the identifier plan: the more dangerous a message is to miss, the smaller its identifier.
  2. Compute the bus budget with 135-bit frames, and check the finish time of a full burst against the cycle.
  3. Make every command carry a sequence counter, a CRC over the data and a timestamp. Keep hardware-written bytes out of the CRC.
  4. Never let a stale command wait in a mailbox: abort the old one first, or send once.
  5. Filter in hardware; copy and stamp in the interrupt; decide in the main loop.
  6. Feed the deadman only from commands that passed every check.
  7. Pick the window as (missed commands tolerated + 1) periods plus jitter, and log the longest gap you see.
  8. Clamp small overshoots, reject absurd values, and keep the limits in flash where the bus cannot change them.
  9. Build the braking envelope from a rate the motor can always deliver.
  10. Choose the stop from the worst pose: coast, ramp and hold, or ramp and brake. Latch it. Report the cause.
  11. Read the CAN error state every tick. Treat bus-off as a lost link.
  12. Test each guard against the fault it answers, then all together. Check that the clocks agree.

The core as code

c/* ---- the guard of one joint: Chapters 3 to 8 in one place (STM32-class, C) ---- */
#define DEADMAN_MS   30u
#define AGE_MAX_MS   30u
#define W_LIMIT      1.0f      /* rad/s: speed limit                             (Ch 6) */
#define W_REJECT     2.0f      /* rad/s: over this is rejected, not clamped      (Ch 6) */
#define ACC_LIMIT   10.0f      /* rad/s^2: torque limit divided by inertia       (Ch 6) */
#define SOFT_LIMIT   1.05f     /* rad                                            (Ch 6) */
#define BRAKE_ACC    6.0f      /* rad/s^2 the motor can always deliver           (Ch 6, 7) */

typedef enum { J_INIT, J_RUN, J_SAFE_STOP } jstate_t;
static jstate_t state = J_INIT;
static uint32_t last_valid_ms;  static uint8_t last_seq;  static float w_target;

void joint_on_frame(const uint8_t rx[8], uint32_t now_ms) {      /* main loop, one frame */
    if (state == J_SAFE_STOP) return;                            /* latched (Ch 5, 7) */
    if (cmd_check(rx, (uint16_t)now_ms, &last_seq) != CMD_OK) return;   /* Ch 4 */
    float w = (int16_t)(rx[1] | (rx[2] << 8)) * 0.001f;
    if (fabsf(w) > W_REJECT) return;                             /* sensible?  (Ch 6) */
    last_valid_ms = now_ms;                                      /* feed the deadman ONLY here (Ch 5) */
    w_target = w;
    if (state == J_INIT) state = J_RUN;
}

static float limit_speed(float w_cmd, float theta, float w_now, float dt) {
    float w = fminf(fmaxf(w_cmd, -W_LIMIT), W_LIMIT);                       /* speed limit */
    float room_p = fmaxf(0.f, SOFT_LIMIT - theta), room_n = fmaxf(0.f, theta + SOFT_LIMIT);
    w = fminf(w,  sqrtf(2.f * BRAKE_ACC * room_p));                         /* braking envelope */
    w = fmaxf(w, -sqrtf(2.f * BRAKE_ACC * room_n));
    float dw = ACC_LIMIT * dt;                                              /* torque limit */
    return fminf(fmaxf(w, w_now - dw), w_now + dw);
}

void joint_tick_1khz(uint32_t now_ms, float theta, float w_now) {      /* every 1 ms */
    uint32_t esr = hcan1.Instance->ESR;
    if (state == J_RUN && (now_ms - last_valid_ms) > DEADMAN_MS) enter_safe_stop(CAUSE_DEADMAN);
    if (esr & CAN_ESR_BOFF)                                    enter_safe_stop(CAUSE_BUS_OFF);
    float w_set = (state == J_RUN) ? limit_speed(w_target, theta, w_now, 0.001f)
                : (state == J_SAFE_STOP) ? ramp_to_zero(w_now, BRAKE_ACC, 0.001f) : 0.f;
    speed_loop_set(w_set);                                     /* the fast loop of fw-mot-02 */
}

Read it top to bottom and name the chapter behind each line. The frame function is the pipeline of Chapter 9. The limit function is the equation of Chapter 6 plus the speed and torque caps. The tick holds the deadman and the bus state. The function enter_safe_stop picks the stop of Chapter 7, sets the latch and writes the cause for the status frame.

Where this sits, and what we left out

This lesson closes the motor track. Motors, drivers and six-step built the muscle. Encoders and the position loop built the fast loop that speed_loop_set feeds. The guard here wraps both. We left out CAN FD, which carries up to 64 data bytes per frame and can switch to a faster bit rate after arbitration; CANopen drive profiles; EtherCAT; redundant channels with two CPUs; and the formal safety analysis (the IEC 61508 safety integrity levels and ISO 13849 performance levels) that a certified machine needs. Those need standards you must read in full.

Keep going

Sources

Not opened for this lesson, so treat as pointers: the IEC 61800-5-2 text on safe torque off, the exact bit layout of the bxCAN CAN_ESR register, the 120 ohm bus termination value, and the bus-off recovery rule of your own controller. Check them in the standard or the manual for your part. The arm, the speeds, the stop rates and the link timings in the devices are a model.

The takeaway. A joint must never act on a promise nobody renewed. Give each command three proofs, give the joint a deadman, give it limits that hold when everything upstream is wrong, and give it a stop that ends somewhere safe. Then test each guard with the fault it was built for.
Which design is closest to the lesson's joint guard?

Now press Present or Teach and explain one fault from memory: what broke on the bus, which guard saw it, and what the arm did. Then go back to the cable and cut it again.

A CAN Joint Controller, Firmware from Zero to Expertise
CAN and EtherCAT · Fail-safe design · Previous: encoders and the position loop · Back to Gleams