Motors and motor control
DC motors and H-bridges, steppers, BLDC commutation and FOC.
Making things move
Motors turn electrical energy into motion, and firmware decides how. The type of motor determines the driver hardware, the peripherals you need (PWM, encoders, ADCs for current) and how complex the control code is.
| Motor | How it is driven | Control complexity | Typical use |
|---|---|---|---|
| Brushed DC | Voltage via PWM through an H-bridge | Low | Toys, pumps, fans, small actuators |
| Hobby servo | 50 Hz PWM pulse width (1 to 2 ms) to an internal controller | Very low | RC models, simple positioning |
| Stepper | Phase currents switched in sequence | Medium (open loop) | 3D printers, CNC, camera sliders |
| Brushless DC (BLDC) / PMSM | Three-phase inverter, electronically commutated | High | Drones, e-bikes, appliances, robots, EVs |
Brushed DC motors and the H-bridge
Speed is roughly proportional to voltage, and torque to current. An H-bridge (four transistors) applies the supply in either polarity, so the motor can run both ways; PWM on the bridge sets the average voltage.
| High-side A | Low-side A | High-side B | Low-side B | Result |
|---|---|---|---|---|
| on | off | off | on | Forward |
| off | on | on | off | Reverse |
| off | on | off | on | Brake (both low sides: motor shorted) |
| off | off | off | off | Coast |
| on | on | – | – | Shoot-through: destroys the bridge |
Firmware rules: never turn on both transistors of one leg; use complementary PWM with dead time (see the timers lesson); prefer driver ICs (DRV8871, VNH5019 and similar) with built-in protection. PWM frequency is usually above 16 to 20 kHz so the motor does not whine.
Current sensing (a shunt plus amplifier into the ADC) lets you limit torque, detect a stall, and protect the motor.
Stepper motors
A stepper moves a fixed angle per step (commonly 1.8°, 200 steps per revolution) as its coils are energised in sequence. It holds position without feedback as long as it does not lose steps.
- Full step, half step and microstepping (sine/cosine-weighted currents in the two coils, for example 1/16 step) trade torque for smoothness and resolution.
- Driver ICs (A4988, DRV8825, Trinamic TMC2209) take STEP and DIR inputs and regulate coil current with their own chopper; firmware generates the step pulses.
- Acceleration ramps are essential: a stepper cannot jump instantly to high speed; trying makes it stall and lose steps. Ramp the step rate up and down (trapezoidal or S-curve profiles), generated by a timer, not by delay loops.
#include <stdio.h>
#include <math.h>
/* Trapezoidal ramp: step intervals for an accelerate-cruise-decelerate move.
For constant acceleration a (steps/s^2), step n of the ramp happens at t = sqrt(2n / a). */
int main(void) {
double accel = 4000.0, max_rate = 2000.0; /* steps/s^2, steps/s */
int total = 3000;
int ramp = (int)(max_rate * max_rate / (2 * accel)); /* steps needed to reach max_rate */
if (2 * ramp > total) ramp = total / 2; /* short move: triangle profile */
printf("accelerate for %d steps, cruise for %d, decelerate for %d\n", ramp, total - 2 * ramp, ramp);
double t_prev = 0;
for (int n = 1; n <= 5; n++) { /* first few step intervals */
double t = sqrt(2.0 * n / accel);
printf("step %d after %.2f ms\n", n, (t - t_prev) * 1000);
t_prev = t;
}
printf("cruise interval: %.2f ms per step\n", 1000.0 / max_rate);
return 0;
}
The intervals shrink as the motor speeds up; a timer's compare value is updated after each step (efficient real-time algorithms such as David Austin's avoid the square root).
Brushless motors
A BLDC motor has permanent magnets on the rotor and three phase windings on the stator. There are no brushes, so it is efficient and long-lived, but the controller must switch the phase currents in step with the rotor's position (commutation).
Six-step (trapezoidal) commutation: energise two of the three phases at a time, changing every 60 electrical degrees, using rotor position from three Hall sensors or, sensorless, from the back-EMF zero crossing on the undriven phase. Simple, but torque ripples.
Field-oriented control (FOC): measure two phase currents, transform them (Clarke and Park transforms) into a rotating frame aligned with the rotor (d and q axes), run PI controllers on the torque-producing current (Iq) and the flux current (Id, usually held at 0), transform back and generate three sinusoidal PWMs with space-vector modulation. Smooth, quiet, efficient; it needs fast ADC sampling synchronised to the PWM (centre-aligned PWM gives a clean sampling point), a current loop running at 10 to 30 kHz, and an encoder or a sensorless observer for rotor angle. Vendors provide FOC libraries (ST Motor Control SDK, TI InstaSPIN, Infineon), and advanced timers exist largely for this job.
Encoders and feedback
| Sensor | Gives | Notes |
|---|---|---|
| Incremental quadrature encoder | Relative position (A and B pulses 90° apart) and direction | Timer encoder mode counts in hardware; needs homing at start-up |
| Absolute encoder (SSI, BiSS, SPI) | Absolute angle | No homing; more expensive |
| Hall sensors | Coarse rotor position (60° sectors) | Enough for six-step commutation |
| Back-EMF, observers | Estimated position without sensors | Does not work at standstill or very low speed |
Protection
Motor drives handle large currents and inductive energy. Firmware must implement: overcurrent shutdown (with the timer's hardware break input for microsecond response), stall detection, over-temperature derating, undervoltage and overvoltage (regenerative braking pumps energy back into the supply), and a safe state on any fault.
Pitfall: Debugging a motor drive with a breakpoint halts the CPU, but the PWM hardware may keep driving whatever duty cycle it last had, or a phase may stay on. Configure the timer to freeze its outputs safely in debug halt (the debug-freeze and "main output enable" settings), and use a current-limited supply when developing.
Interview question: Compare six-step commutation and field-oriented control for a BLDC motor.
Answer: Six-step energises two phases at a time and switches every 60 electrical degrees based on Hall sensors or back-EMF zero crossings; it is simple and needs little computation, but produces torque ripple, noise and lower efficiency. FOC measures phase currents, transforms them into the rotor's reference frame, controls the torque and flux components with PI loops and drives sinusoidal currents with space-vector PWM; it gives smooth torque, quiet running and better efficiency across speeds, at the cost of fast synchronised ADC sampling, more maths per PWM cycle and accurate rotor angle.
Interview question: How would you read a quadrature encoder on a microcontroller?
Answer: Use a timer in encoder mode: its two inputs connect to the A and B channels, and the counter counts up or down in hardware on every edge (four counts per line in x4 mode), with input filters to reject noise. Read the counter periodically, compute the position change with unsigned or signed wrap-around arithmetic, extend it to a wider software count, and derive speed from the change per period (or from the time between edges at low speed). Home it with an index pulse or limit switch at start-up.
Build it: commutate the brushless motors
This is step 4 of the module project, the camera gimbal. Each axis is a brushless motor with three Hall sensors, which together report which of six sectors the rotor is in. The firmware energises the two phases that pull the rotor on to the next sector: one high, one low, one floating. Get a sector wrong and the motor stalls or jerks; trust a broken Hall wire and it can drive full current into a stalled motor.
Lab: Six-step commutation from the Hall sensors
The Hall sensors read as a 3-bit value. Turning forward, they step through HALL_SEQ: 5, 4, 6, 2, 3, 1, then 5 again. FWD[hall] gives the drive for each phase (U, V, W) when turning forward: +1 high, -1 low, 0 floating. 0 and 7 are not possible with working sensors.
bldc_hall(m, hall, now_us, out) runs on every Hall edge and fills out with the three phase drives:
- Direction:
m->diris +1 or -1. Turning backward uses the opposite drive: every phase ofFWD[hall]negated. - Invalid states (0 or 7) and jumps (a new state that is not one step on from the last, in either direction, as when an edge was missed) count as errors. On an error drive all phases 0. After
MAX_ERRORSerrors in a row, setm->fault; from then on always drive 0, until the motor is restarted. A valid step resets the error count. The very first edge after start (m->lastis 0) cannot be a jump. - Speed: on a valid step,
m->rpmis the mechanical speed from the time since the previous valid edge: there are 6 edges per electrical turn andPOLE_PAIRSelectrical turns per mechanical turn, sorpm = 60 000 000 / (dt_us × 6 × POLE_PAIRS). It is 0 after the first edge. - Remember the last valid state and its time.
Going deeper
Interview question: How would you control a 3D printer's axes for accuracy and speed?
Answer: Stepper motors through drivers with microstepping and current control, a motion planner that turns the path into steps with acceleration limits (trapezoidal or S-curve profiles) so steps are never lost, and step generation from a hardware timer. Home each axis against an end stop at start-up, and consider closed-loop steppers where losing steps would ruin a long print.
Interview question: Why does a motor drive's current measurement need to be synchronised with the PWM?
Answer: The phase current ripples with every PWM switching edge, and switching causes noise spikes. Sampling at a consistent point in each PWM period, typically the centre of the low-side on-time in centre-aligned PWM, measures the average current away from the switching edges. Advanced timers trigger the ADC at that point in hardware so the sample timing has no software jitter.
Interview question: What happens electrically when a spinning motor is braked or decelerated quickly, and why does firmware care?
Answer: The motor acts as a generator. During fast deceleration that energy flows back through the inverter into the DC bus, raising its voltage; if the supply cannot absorb it (a battery may, a power supply usually cannot), the bus voltage can exceed component ratings. Firmware monitors the bus voltage, limits the deceleration rate, or switches a braking resistor in (a brake chopper) to dissipate the energy.
Explain it: In your own words, explain how an H-bridge with PWM controls the speed and direction of a brushed DC motor.
Answer: An H-bridge has two legs, each with a transistor to the supply and one to ground, with the motor connected between the legs' midpoints. Turning on the top switch of one leg and the bottom switch of the other drives current through the motor one way; the opposite pair drives it the other way, which sets the direction. Switching that pair on and off rapidly with PWM makes the motor see an average voltage proportional to the duty cycle, which sets the speed. Dead time between switching transistors in the same leg prevents both being on at once and shorting the supply.