Worked System: A Motor Controller

A motor controller meets a hard deadline 20,000 times a second. It must also stop a fault faster than any program can react.

You Will Be Able To

  • Walk one PWM period and show that the control loop meets its deadline.
  • Decide which jobs must be hardware, from their rates and their deadlines.
  • Replace power modes by safe states, under reset, under a fault and under a debug halt.
Lesson
S11.11
Time
30 min
Runs on
Your browser
Check
5 questions

The engineer halts the controller with the debugger, to read one variable. The motor jerks, and a switch on the board burns out.

The software was right. Which column of the review was left empty?

Before You Start

You need Design Reviews: "Design This SoC" and the board of Worked System: A Sensor Hub.

You need Timers: Prescaler, Compare, Capture and PWM: a counter, a compare value and a duty cycle.

You need the safe state of Analog Blocks in Test Mode, and Interrupts at the Core.

Five questions this page answers
Question
1What deadline must the control loop meet in every period?
2Why must dead time, edge counting and the fault path be hardware?
3What replaces power modes on a motor controller?
4What must the outputs do when a debugger halts the core?
5The loop needs 3000 cycles. What does the lab print last?

The Idea: A Deadline in Every Period

An electric motor turns when its coils are switched on and off in the right order. A motor controller chip does the switching, thousands of times a second.

The first idea is a deadline in every period. The chip measures the currents, works out new duty cycles and writes them before the next period starts. Late is wrong.

The second idea is that some jobs are too fast for any program. They must be hardware: the gap between two switches, the counting of pulses from the shaft, and the reaction to a fault.

The third idea is that power modes become safe states. The question is not how to save power. It is what the outputs do when software is not in control.

New Words

New words on this page
WordMeaning
Half-bridgeTwo switches in series between the supply and ground, with a motor coil at their middle. Three phases need three.
Shoot-throughBoth switches of a half-bridge on at once. The supply is shorted, and a switch can burn out.
Dead timeA short gap in which both switches of a half-bridge are off, between one turning off and the other turning on.
Centre-aligned PWMA PWM whose counter counts up to a top value and back down in every period.
Valley of the counterThe point where a centre-aligned counter is at zero. New duty values are loaded there.
ADCAnalog-to-digital converter: a block that turns a voltage, here a motor current, into a number.
Motor control loopThe program that reads the motor currents and writes new duty cycles, once every period.
EncoderA sensor on the shaft that gives two pulse trains. Counting their edges gives the angle and the speed.
Break inputAn input of the PWM block that forces every output off at once, with no program involved.
Masked sectionA stretch of code that runs with interrupts disabled. A request that arrives meanwhile waits.

One Picture: The Board, Filled for a Motor

The Board of the Motor ControllerStep through the board. Here the hard columns are timing and safety, not memory or sleep.
  • File
  • Processor
  • Memory
  • Clock / reset
  • Control / FSM
  • Power
  • Debug
  • Report
The Board of the Motor ControllerStep through the board. Here the hard columns are timing and safety, not memory or sleep. component Requirements PWM at 20 kHz onthree phases; 1024steps or more; 500 nsdead time; off within1 µs of a fault component Block diagram core; PWM timer withdead time and a breakinput; ADC; encodercounter; comparator;UART; SRAM component Memory map ap_soc map; PWM at1000_8000, ADC at1000_9000, encoderat 1000_A000;SRAM of 8 KiB component Clocks and resets PLL 100 MHz forthe core and thePWM counter;outputs low fromreset until armed component Interrupts 21,000 requests asecond: the controlloop first, then thespeed loop component Power modes run; standby with theoutputs off; fault,latched off untilcleared component Debug on a debug halt theoutputs go off; afault-cause register;a telemetry stream component Risks control takes 44 of50 percent; dead timeagainst the real gatedriver; noise at thesample point what to buildwhat to placewhat to timewhat to countwhen to wakewhat to seewhat is thinchange and run again
  1. component RequirementsPWM at 20 kHz on three phases; 1024 steps or more; 500 ns dead time; off within 1 µs of a fault
    • what to build → Block diagram
  2. component Block diagramcore; PWM timer with dead time and a break input; ADC; encoder counter; comparator; UART; SRAM
    • what to place → Memory map
  3. component Memory mapap_soc map; PWM at 1000_8000, ADC at 1000_9000, encoder at 1000_A000; SRAM of 8 KiB
    • what to time → Clocks and resets
  4. component Clocks and resetsPLL 100 MHz for the core and the PWM counter; outputs low from reset until armed
    • what to count → Interrupts
  5. component Interrupts21,000 requests a second: the control loop first, then the speed loop
    • when to wake → Power modes
  6. component Power modesrun; standby with the outputs off; fault, latched off until cleared
    • what to see → Debug
  7. component Debugon a debug halt the outputs go off; a fault-cause register; a telemetry stream
    • what is thin → Risks
  8. component Riskscontrol takes 44 of 50 percent; dead time against the real gate driver; noise at the sample point
    • change and run again → Requirements
  1. 1. Requirements

    The numbers are rates and deadlines. Nothing here is large; everything here is late if it is slow.

  2. 2. Block diagram

    Three blocks exist because software would be too slow: dead time, edge counting and the fault path.

  3. 3. Memory map

    A small map. The control loop needs a sine table and a stack, and telemetry needs a buffer.

  4. 4. Clocks and resets

    One clock for the counter and the core keeps the arithmetic simple. Reset must never switch a phase on.

  5. 5. Interrupts

    The control request comes when the conversions end. A masked section delays it, and the delay counts.

  6. 6. Power modes

    A motor chip does not sleep to save power. Its modes are safe states.

  7. 7. Debug

    A halted loop must never leave a phase switched on. Telemetry shows the loop without stopping it.

  8. 8. Risks

    Each is listed with a test: measure the handler, measure the driver, move the sample point.

Read the diagram as text
  • Requirements: PWM at 20 kHz on three phases; 1024 steps or more; 500 ns dead time; off within 1 µs of a fault
  • Block diagram: core; PWM timer with dead time and a break input; ADC; encoder counter; comparator; UART; SRAM
  • Memory map: ap_soc map; PWM at 1000_8000, ADC at 1000_9000, encoder at 1000_A000; SRAM of 8 KiB
  • Clocks and resets: PLL 100 MHz for the core and the PWM counter; outputs low from reset until armed
  • Interrupts: 21,000 requests a second: the control loop first, then the speed loop
  • Power modes: run; standby with the outputs off; fault, latched off until cleared
  • Debug: on a debug halt the outputs go off; a fault-cause register; a telemetry stream
  • Risks: control takes 44 of 50 percent; dead time against the real gate driver; noise at the sample point
  • Requirements → Block diagram: what to build
  • Block diagram → Memory map: what to place
  • Memory map → Clocks and resets: what to time
  • Clocks and resets → Interrupts: what to count
  • Interrupts → Power modes: when to wake
  • Power modes → Debug: what to see
  • Debug → Risks: what is thin
  • Risks → Requirements: change and run again

The eight columns of S11.4, filled for a motor controller. Compare column 6 with the sensor hub.

The Smallest Example, Worked by Hand

No simulator yet. Start with the PWM. The counter runs at 100 MHz and counts up and down once in each 50 µs period.

The PWM, by hand
EntrySumResult
Top value100,000,000 ÷ (2 × 20,000)2500 counts
Duty stepsone step a count2500: more than the 1024 asked for
Dead time500 ns × 100 MHz50 ticks
Encoder edges1024 lines × 4 edges × 6000 ÷ 60 turns a second409,600 a second

Now walk one period. The core also runs at 100 MHz, so a cycle is 10 ns.

One PWM period of 50 µs, by hand
TimeWhat happensSum
0 µsThe counter reaches its valley and starts the two conversionsstart
2.0 µsBoth conversions are done; the control request is raised2 × 1 µs
4.3 µsThe handler starts, after the worst masked section and its own entry2.0 + (200 + 30) cycles × 10 ns
24.3 µsThe loop has written the new duties4.3 + 2000 cycles × 10 ns
50 µsThe next valley: the counter loads the new duties25.7 µs to spare

Last, the fault. A handler waits behind the same masked section: (200 + 30 + 50) cycles is 2.8 µs. The limit is 1 µs. Software cannot meet it, even when it is ready.

The Rules

  1. Rule 1: Walk the worst period.

    Add the conversions, the longest masked section, the entry and the loop. The sum must end before the next valley.

  2. Rule 2: A job faster than a request is hardware.

    If events come many times in one period, count them in hardware and read the count.

  3. Rule 3: A deadline shorter than the worst latency is hardware.

    The fault limit of 1 µs is shorter than the 2.8 µs of the best handler. The break input acts alone.

  4. Rule 4: Outputs are off unless software has armed them.

    From reset, after a fault and under a debug halt, every switch is off.

  5. Rule 5: Leave half the period free.

    Other work, and later growth of the loop, need room. This design keeps the loop under 50 percent.

  6. Rule 6: Size telemetry for the longest stall.

    Bytes pile up while the link waits. The buffer holds the rate times the stall.

Sources for These Rules

A counter, a compare value and a duty cycle: Timers: Prescaler, Compare, Capture and PWM. A request waits while interrupts are disabled: Interrupts at the Core.

Half-bridges, dead time, centre-aligned PWM and sampling at the valley are common practice in motor control. So are encoders with four edges a line, break inputs and outputs off under a halt. No book in our library covers them.

Every rate, time and cycle count here is an exercise value. The PLL of 100 MHz is that of ap_soc (docs/soc/ap_soc-facts.md, section 10).

Now Run It: The Sizing Sheet

The lab at the end of this page is the sizing sheet of the controller. Its last two rows come from one PWM period, walked in steps of 10 ns.

Printed by the lab on Icarus: the sizing sheet of the motor controller.
pwm       top=2500  steps=2500 (11 bits)  dead_time=50 ticks  ok
encoder   edges=409600/s  per_period=20.4  -> count in hardware
irq       control=20000/s  speed=1000/s  total=21000/s
telemetry rate=32000 B/s  uart=92160 B/s  stall=5 ms  buffer=160 B -> 256 B
memory    sine=2048  telemetry=256  stack=2048  total=4352 -> sram=8192 B
fault     hardware=30 ns  software=2800 ns  limit=1000 ns  -> break input in hardware
period    adc_done=2000 ns  isr_start=4300 ns  isr_end=24300 ns  next_valley=50000 ns  slack=25700 ns
cpu       control_share=44%  budget=50%  ok

The pwm row: a top of 2500 gives 2500 steps, which is 11 whole bits. Dead time is 50 ticks.

Rule 2, in the encoder row: 409,600 edges a second, 20.4 in each period. A counter in hardware counts them; the loop reads it once a period.

Rule 3, in the fault row. The break input turns the outputs off in 30 ns: three ticks of the counter clock. A handler would need 2800 ns.

Rule 1, in the period row. The handler starts at 4300 ns and the new duties are written at 24,300 ns. The next valley is at 50,000 ns, so 25,700 ns are left.

Rule 5, in the last row. From the end of the conversions to the new duties is 44 percent of the period, under the budget of 50.

Rule 6, in the telemetry row. 32,000 bytes a second, and the link may stall for 5 ms: 160 bytes pile up, so the buffer is 256.

This lab leaves things out. There is no motor, no current and no control law: the loop is a count of cycles. All timing is in whole steps of 10 ns.

The Rest of the Board

Columns 3 to 5: map, clocks, resets and interrupts
EntryChoiceReason
PWM timer1000_8000, 4 KiBSix outputs with dead time and a break input. The Timer and PWM of ap_soc has none of these.
ADC1000_9000, 4 KiBTwo conversions, started by the valley of the counter, not by software.
Encoder counter1000_A000, 4 KiBCounts every edge; the loop reads the count once a period.
SRAM8000_0000, 8 KiB4352 bytes: a sine table, the telemetry buffer and the stack.
ClocksPLL at 100 MHz for core and counterOne clock: the duty and dead-time sums use one tick.
Resetoutputs low and the gate drivers disabled until armedA reset in the middle of a period must not leave a switch on.
Source 7conversions done: the control loop, highest priority20,000 a second.
Source 8fault, after the break input has actedOnly to record the cause; the hardware has already stopped the motor.
Columns 6 to 8: safe states, debug and risks
EntryChoiceReason
Runoutputs follow the dutiesThe only state with switches on.
Standbyoutputs off, gate drivers disabledThe state after reset and before arming.
Faultoutputs off, latched until software clears itA fault must not clear itself and restart the motor.
Debug haltoutputs off while the core is haltedThe hook of this page: a frozen loop left a phase on.
Risk: loop time44 of 50 percentMeasure the real loop on the real core.
Risk: dead time500 ns against the real switchesMeasure the turn-off time of the gate driver and switch.
Risk: sample pointswitching noise near the valleyCheck on a board; move the start of the conversions if needed.

Why It Is Built This Way

ChoiceThe alternativeWhat it buys, and what it costs
A break input in hardwareA fault interrupt with the top priority30 ns in place of 2800 ns. The cost is a wire from a comparator and a latch.
Conversions started by the counterStarted by softwareThe sample point is the same in every period. Software start would wander with the latency.
Duties loaded at the valleyLoaded at once when writtenNo period ever mixes old and new duties. The cost is a full period of delay.
Outputs off under a debug haltOutputs frozen as they wereA halt is safe. The cost: the motor cannot run while you step through code.

The Trap: Halting a Running Motor

This is the hook. The debugger halted the core. The PWM block kept its last duty, and one switch stayed on. The current rose until the switch burnt out.

Rule 4 forbids it. Column 7 should have asked what the outputs do under a halt. The answer is off.

The second trap is the fault interrupt. It was given the top priority and thought fast enough. Behind a masked section of 200 cycles it took 2.8 µs.

The third trap is the average. On most periods the handler starts at once. On the period with the longest masked section, the loop takes 44 percent.

At Scale

This page1 motor, 3 phases
A robot armsix motors, one chip

This section looks ahead, to controllers for cars and robots.

  1. Many motors

    Six motors need six PWM blocks whose valleys are spread out, so that six loops do not all start at once.

  2. Safety as a requirement

    In cars, column 1 holds safety goals with their own standards and tests. Column 8 becomes a formal analysis of faults.

  3. Two cores

    Some chips run the loop on one core and everything else on another, so a masked section elsewhere cannot delay it.

Try It

Run the lab. Find the deadline of the loop in the period row, and the fault times in the fault row.

Set FOC_CYCLES to 2400. Does the loop still meet the next valley? Does it meet the 50 percent budget?

Set CNT_HZ to 40000000. Which requirement fails first, steps or dead time?

Names Printed by the Lab
NameMeaning
top, steps, bitsThe count at which the counter turns round; the duty steps in a period; the whole bits they give.
dead_timeThe dead time in ticks of the counter clock, rounded up.
edges, per_periodEncoder edges each second at top speed, and in one PWM period.
control, speed, totalInterrupt requests each second, by source.
rate, uart, stall, bufferTelemetry bytes each second; what the UART can send; the longest stall of the link; the bytes that pile up meanwhile.
sine, telemetry, stackThe SRAM for a sine table, the telemetry buffer and the stack, in bytes.
hardware, softwareThe time from a fault to the outputs off, by a break input or by a handler behind the worst masked section.
adc_done, isr_start, isr_endIn one period: the conversions end, the handler starts, the new duties are written.
next_valley, slackThe time at which the counter loads the duties, and the time left before it.
control_shareThe time from the end of the conversions to the new duties, as a share of the period.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: pwm top=2500 steps=2500 (11 bits) dead_time=50 ticks ok encoder edges=409600/s per_period=20.4 -> count in hardware irq control=20000/s speed=1000/s total=21000/s telemetry rate=32000 B/s uart=92160 B/s stall=5 ms buffer=160 B -> 256 B memory sine=2048 telemetry=256 stack=2048 total=4352 -> sram=8192 B fault hardware=30 ns software=2800 ns limit=1000 ns -> break input in hardware period adc_done=2000 ns isr_start=4300 ns isr_end=24300 ns next_valley=50000 ns slack=25700 ns cpu control_share=44% budget=50% ok

Check Yourself

Predict the outputIn this run the control loop needs 3000 cycles in place of 2000. What is the last line? Its form is: cpu control_share=..% budget=50% ..
// The sizing sheet of a motor controller. Test code: arithmetic, and one PWM period walked in steps of 10 ns.
// Every number is an exercise value. Change a requirement and run the sheet again.
module tb;
  // ---- Requirements -------------------------------------------------------------------------------------
  parameter int PWM_HZ = 20000, DEAD_NS = 500, MIN_STEPS = 1024;   // switching rate, dead time, duty steps in a period
  parameter int LINES = 1024, MAX_RPM = 6000;                 // the encoder and the top speed
  parameter int FAULT_LIMIT_NS = 1000;                   // over-current: outputs off within this time
  parameter int SPEED_HZ = 1000, TELEM_B = 16, TELEM_EVERY = 10, BAUD = 921600, STALL_MS = 5;   // speed loop, telemetry
  // ---- Choices of this design ---------------------------------------------------------------------------
  parameter int CNT_HZ = 100000000, CORE_HZ = 100000000, BUDGET_PCT = 50;   // PWM counter clock, core clock, share for the control loop
  parameter int ADC_NS = 1000, ADC_COUNT = 2;              // conversions, one after the other
  parameter int IRQ_ENTRY = 30, MASKED = 200, FOC_CYCLES = 3000;   // core cycles: entry, longest masked section, the loop
  parameter int BREAK_CYCLES = 3, FAULT_ISR = 50;       // fault path: hardware break, or a software handler
  localparam int SINE_B = 2048, STACK = 2048;     // bytes

  function automatic int ceil_div(input longint a, input longint b); return (a + b - 1) / b; endfunction
  function automatic int pow2_at_least(input int n); int s = 1; while (s < n) s = s * 2; return s; endfunction

  initial begin
    int top, dead, bits, counts, per_loop10, irq, telem, uart, buf_b, mem, hw_ns, sw_ns;
    // 1. PWM: a centre-aligned counter counts up to TOP and back down once in each period.
    top = CNT_HZ / (2 * PWM_HZ);
    dead = ceil_div(longint'(DEAD_NS) * CNT_HZ, 1000000000);
    bits = $clog2(top + 1) - 1;
    if (top >= MIN_STEPS) $display("pwm       top=%0d  steps=%0d (%0d bits)  dead_time=%0d ticks  ok", top, top, bits, dead);
    else $display("pwm       top=%0d  steps=%0d (%0d bits)  dead_time=%0d ticks  SHORT", top, top, bits, dead);
    // 2. The encoder: four edges for each line.
    counts = longint'(LINES) * 4 * MAX_RPM / 60;
    per_loop10 = longint'(counts) * 10 / PWM_HZ;
    $display("encoder   edges=%0d/s  per_period=%0d.%0d  -> count in hardware", counts, per_loop10 / 10, per_loop10 % 10);
    // 3. Interrupts, the telemetry buffer and the memory.
    irq = PWM_HZ + SPEED_HZ;
    telem = TELEM_B * (PWM_HZ / TELEM_EVERY);
    uart = BAUD / 10;
    buf_b = longint'(telem) * STALL_MS / 1000;
    $display("irq       control=%0d/s  speed=%0d/s  total=%0d/s", PWM_HZ, SPEED_HZ, irq);
    $display("telemetry rate=%0d B/s  uart=%0d B/s  stall=%0d ms  buffer=%0d B -> %0d B", telem, uart, STALL_MS, buf_b, pow2_at_least(buf_b));
    mem = SINE_B + pow2_at_least(buf_b) + STACK;
    $display("memory    sine=%0d  telemetry=%0d  stack=%0d  total=%0d -> sram=%0d B", SINE_B, pow2_at_least(buf_b), STACK, mem, pow2_at_least(mem));
    // 4. The fault path: a hardware break input against a software handler behind the same masked section.
    hw_ns = ceil_div(longint'(BREAK_CYCLES) * 1000000000, CNT_HZ);
    sw_ns = ceil_div(longint'(MASKED + IRQ_ENTRY + FAULT_ISR) * 1000000000, CORE_HZ);
    $display("fault     hardware=%0d ns  software=%0d ns  limit=%0d ns  -> %s", hw_ns, sw_ns, FAULT_LIMIT_NS,
      hw_ns <= FAULT_LIMIT_NS && sw_ns > FAULT_LIMIT_NS ? "break input in hardware" : "either path");
  end

  // ---- One PWM period, walked in steps of 10 ns ------------------------------------------------------------
  // At 0 ns the counter is at its valley and starts the conversions. When they are done, the control interrupt
  // is raised. In the worst case a masked section has just begun, so entry waits for it. The loop then runs, and
  // writes the new duties before the next valley, where the counter loads them.
  initial begin
    int t, adc_done, isr_start, isr_end, period_ns, slack, load;
    #1;
    period_ns = 1000000000 / PWM_HZ;
    adc_done = -1; isr_start = -1; isr_end = -1;
    for (t = 0; t < period_ns; t += 10) begin
      if (adc_done < 0 && t >= ADC_NS * ADC_COUNT) adc_done = t;
      if (adc_done >= 0 && isr_start < 0 && t >= adc_done + ceil_div(longint'(MASKED + IRQ_ENTRY) * 1000000000, CORE_HZ)) isr_start = t;
      if (isr_start >= 0 && isr_end < 0 && t >= isr_start + ceil_div(longint'(FOC_CYCLES) * 1000000000, CORE_HZ)) isr_end = t;
    end
    slack = isr_end >= 0 ? period_ns - isr_end : -1;
    load = isr_end >= 0 ? (isr_end - adc_done) * 100 / period_ns : 100;
    $display("period    adc_done=%0d ns  isr_start=%0d ns  isr_end=%0d ns  next_valley=%0d ns  slack=%0d ns", adc_done, isr_start, isr_end, period_ns, slack);
    if (isr_end >= 0 && load <= BUDGET_PCT) $display("cpu       control_share=%0d%%  budget=%0d%%  ok", load, BUDGET_PCT);
    else $display("cpu       control_share=%0d%%  budget=%0d%%  OVER", load, BUDGET_PCT);
  end
endmodule
ConceptWhat deadline must the control loop meet?
ConceptWhy must the fault path be hardware?
ConceptWhat takes the place of power modes on this chip?
ConceptWhat must the outputs do when a debugger halts the core?

Common Mistakes

Wrong Time the control loop without the masked sections.

The worst period has the longest masked section in front of the loop.

Fix Add the longest masked section to the latency.

Wrong Handle an over-current with a top-priority interrupt.

Behind a masked section, the handler takes 2.8 µs against a limit of 1 µs.

Fix Use a break input that turns the outputs off in hardware.

Wrong Let the PWM keep its outputs when the core halts.

A frozen loop can leave a switch on.

Fix Turn every output off while the core is halted.

Remember

  • Walk the worst period: conversions, the longest masked section, entry and loop must end before the next valley.
  • Jobs faster than a request, and deadlines shorter than the worst latency, are hardware.
  • Safe states replace power modes: outputs are off unless software has armed them.
  • Under a debug halt, the outputs turn off.

Practice

Report a problem with this page