A brushless motor has no brushes to switch its coils. Your firmware does it, six times per turn of the magnetic field, using three Hall sensors. Get the wiring order wrong and the rotor stalls.
Learn what each kind of motor needs from a microcontroller: an H-bridge for a brushed motor, steps for a stepper, and a six-step table driven by Hall sensors for a brushless motor.
Press Two Hall wires swapped and watch the speed fall to zero while the current climbs. Press Wired right and watch it spin up. Then we build, piece by piece, everything underneath: the bridge, the dead time, the Hall code, the table and the timer that applies it.
You need the timers and PWM chapter (Timers, PWM and sampling) and a feel for voltage and current. We build the rest from zero.
Built from primary sources: Microchip application note AN885, Brushless DC Motor Fundamentals, and the open-source STM32G4 HAL driver and CMSIS device header from STMicroelectronics. The full list is in the Field Guide. Every idea is taught in our own words and devices; all motor numbers are from a model and say so.
A model, not a measurement. A 24 V bus, four pole pairs, phase resistance 1.2 Ω, torque and back-EMF constants 0.05 in SI units, a constant 0.03 N·m of friction. Time runs at one eighth of real speed so you can watch. Six-step commutation, Hall sensors 120° apart, no phase inductance and no current limit. A real drive would clamp the stall current.
Chapter 0
See why a brushless motor needs your firmware to flip its coils at exactly the right moments, and meet the five pieces that make it work
It is late on the bench. You have a small three-wire motor from a robot joint, a Nucleo board and a driver board. You flash your first program. The motor does not spin. It hums, it gets warm, and the supply meter shows far more current than it should.
Nothing is broken. The motor is working exactly as designed. It is waiting for something that your firmware has not yet learned to do. This lesson explains what that is, and it takes the problem apart until each piece fits in your head.
Think of a compass needle. It is a small magnet. Bring a second magnet close and the needle swings to line up with it, then stops. A motor is a machine that turns electric power into a turning push, called torque. Most motors work like that compass, with one trick added.
The part that turns is the rotor. In a brushless motor it carries permanent magnets. The part that stays still is the stator. It carries coils of wire. A coil with current in it is an electromagnet. Choose which coils carry current and you choose the direction of the stator's magnetic field.
Hold the field still and the rotor behaves like the compass needle. It swings round, overshoots a little, and settles in line with the field. When it is lined up, the push on it is zero. A motor that stops pushing is no use. To keep it turning, you must move the field on ahead of the rotor, again and again. That is the trick.
Try it. The purple arrow is the stator field. The warm bar is the rotor. First hold the field still. Then switch to chasing, where the field is always kept 90 degrees ahead of the rotor.
Left: the rotor and the stator field. Right: the push on the rotor over the last three seconds, as a percentage of the most the coils can give. Press a mode, then press Kick the rotor to start from rest.
A model in plain units: the push is the sine of the angle between field and rotor, with a little friction. Two-pole picture, so mechanical and electrical angles agree. Chapter 4 explains why they differ on a real motor.
With the field held, the push dies away as the rotor settles. With the field chasing, the push stays at its maximum and the rotor speeds up until friction balances it. The only difference is who moves the field, and when.
A brushed motor solves this with copper and carbon. Its coils sit on the rotor. Two carbon blocks, the brushes, slide over a ring of copper segments on the shaft, called the commutator. As the shaft turns, the sliding contact reverses the current in each coil at the right angle. No electronics are needed. Give it a voltage and it spins.
The price is wear. The brushes rub away, and they throw sparks. A brushless motor removes them. The magnets move to the rotor and the coils stay on the stator, with no sliding parts. Microchip's application note AN885 lists the gains: better speed against torque, fast response, high efficiency, long life, quiet running and higher speed ranges.
But someone must still flip the coils. In a brushless motor that someone is you. Your firmware reads where the rotor is, picks which coils get current, and switches six power transistors to make it happen. This is called commutation, and it is the subject of this lesson. Robot joints, drones, fans, pumps and power tools all use it.
The hero at the top of the page ran all five. Follow one rotor position through them.
Each piece has its own way to fail. A wrong Hall wire stalls the rotor. A missing pause between two transistors shorts the supply. A slow timer loses the speed reading. The chapters below take the pieces one by one, starting with the simplest motor and the driver it needs.
Chapter 1
Work out why a motor that is held still draws twenty amps, then control its direction with four switches
You clamp a small brushed motor in a vise and wire it to a 24 V bench supply. You turn the supply on and the motor spins up. The current meter jumps to 20 A, then falls to 3 A within a quarter of a second. Why does the same motor draw so much at the start and so little later?
The answer is the first thing to know about every motor in this lesson. A spinning motor is also a generator. The faster it spins, the more voltage it makes against you.
A brushed motor follows two simple laws. First, the torque is proportional to the current. Write it T = Kt · I, where Kt is the torque constant, in newton-metres per amp. Second, a coil moving through a magnetic field makes a voltage that opposes the supply. This is the back-EMF (EMF means electromotive force, a voltage). It is proportional to the speed: E = Ke · ω, where Ke is the back-EMF constant and ω is the speed in radians per second.
The supply must push current through the winding's resistance R and also overcome the back-EMF. Add the two drops and you get the sum that governs every brushed motor.
Now read the sum at two moments. At the start, ω = 0, so the back-EMF is zero and only R limits the current. This is the stall current: I = V / R. With 24 V and a winding of 1.2 Ω the model gives 20 A, and a torque of 0.05 × 20 = 1.0 N·m. At half of the no-load speed the back-EMF is 12 V, so the current halves to 10 A. At the no-load speed only friction remains and the current is small.
no-load speed = V / Ke = 24 / 0.05 = 480 rad/s = 4,584 rpm stall current = 24 / 1.2 = 20 A
The two constants have the same number in SI units. That is no accident: a motor turns electric power into mechanical power, and the books must balance. This is why the model gives both the value 0.05. These numbers are illustrative, not from a datasheet. A datasheet lists the real ones, and firmware must be sized for the stall current, because that is the largest current the motor can ever draw.
To drive the motor both ways you need to reverse the voltage across it. The standard circuit is the H-bridge: four switches arranged as the letter H, with the motor as the crossbar. The two switches on the left form the left leg. The two on the right form the right leg. Each leg connects its middle point either to the supply or to ground.
This page names the switches by position: high-left (HL), low-left (LL), high-right (HR), low-right (LR). In real bridges they are transistors, called MOSFETs. Switch on HL and LR and current flows left to right through the motor: forward. Switch on HR and LL and it flows right to left: reverse. Switch on both low switches and the two motor wires are tied together, so the back-EMF drives a current through the winding that opposes the motion: a brake. Switch off all four and the motor coasts.
One thing is forbidden. If both switches of one leg are on together, the supply is shorted through them. This is called shoot-through. The Wikipedia article on the H-bridge says it plainly: the two switches on the same side must never be closed together, because the short is dangerous to the supply and to the switches. Try the four switches below. The bridge model is in the left of the picture.
Press a switch to turn it on or off. Left: the bridge, the supply on top, ground below. Right: motor speed and current. Try forward, then both low switches, then HL with LL.
A model with a 24 V supply, winding resistance 1.2 Ω, Kt = Ke = 0.05 and 0.03 N·m of friction, shown at one quarter of real speed. The shoot-through figure assumes two switches of 0.01 Ω each, an illustrative value. Real transistors also have a body diode that carries current when all switches are off.
Notice what the brake does. Press both low switches while the rotor spins. The back-EMF drives a current of Ke · ω / R backward through the winding, and that current gives a torque against the motion. The faster the rotor, the harder the brake. As the rotor slows, the brake weakens. Compare that with coast, which has no current and no brake at all.
On the bench supply you changed the speed by turning the voltage knob. A microcontroller has no knob. It switches the bridge on and off thousands of times a second and varies the on-time. The ratio of on-time to the full period is the duty. The motor's inertia (its reluctance to change speed) and its inductance (the coil's reluctance to change current) smooth the pulses, so the motor sees the average: duty × supply. The timer chapter, Timers, PWM and sampling, builds the PWM signal itself. AN885 gives a rule of thumb: keep the PWM frequency at least ten times the highest motor frequency.
The firmware sets the direction with the four enable bits, then sets the duty. Here is the first half in C. The key line writes all four pins in a single store to the STM32 bit set and reset register, GPIOx_BSRR, so the pins never pass through an illegal middle state.
c · brushed H-bridge, direction part typedef enum { M_COAST, M_FWD, M_REV, M_BRAKE } motor_cmd_t; /* PA0 = HL, PA1 = LL, PA2 = HR, PA3 = LR (gate-driver inputs) */ #define HL (1u << 0) #define LL (1u << 1) #define HR (1u << 2) #define LR (1u << 3) #define ALL (HL | LL | HR | LR) static void bridge_set(motor_cmd_t cmd) { uint32_t on = 0; switch (cmd) { case M_FWD: on = HL | LR; break; case M_REV: on = HR | LL; break; case M_BRAKE: on = LL | LR; break; default: on = 0; break; /* coast */ } /* BSRR: low half sets pins, high half clears pins. One store. */ GPIOA->BSRR = on | ((ALL & ~on) << 16); }
A single store is not enough. A real MOSFET turns off more slowly than it turns on, and the next chapter measures exactly how that fails. For now, keep the lesson of the failure: the symptom is a bridge board that dies at power-up or a supply that droops for a microsecond; the measurement is a spike on the supply current; the fix is a pause between turning one switch off and the other on.
On real hardware. Take an STM32 Nucleo (for example NUCLEO-G431RB), a motor driver board and a small brushed motor. Set the bench supply current limit low, clamp the rotor for one second and read the stall current. Divide the supply voltage by that current. You have measured R, and it should match the motor datasheet.
Chapter 2
Measure the overlap when one transistor turns off late, and set the timer's dead-time register to close it
Your H-bridge ran well at low duty. You raise the PWM and the driver board warms up. At 60% duty a transistor fails with a small puff of smoke. You checked the code three times. Your four enable bits never put two switches of one leg on together.
The code is not the problem. The transistors are. A transistor does not switch instantly, and the two switches of one leg do not follow the code at the same speed.
A power MOSFET is switched by charging or discharging its gate, a tiny capacitor. After the gate signal falls, the transistor keeps conducting for a while, until the gate charge has drained. That wait is the turn-off delay. Turn-on has its own, usually shorter, delay. Datasheets list both in nanoseconds. This page uses illustrative values: 150 ns to turn off, 30 ns to turn on.
Now think about one leg of the bridge, with a high switch and a low switch. A timer produces two complementary signals for it: when one is high the other is low. On an STM32 advanced timer such as TIM1 they are the channel output OC1 and its complement OC1N. If the two signals flip at the same instant, the low switch begins conducting after 30 ns, while the high switch is still conducting for another 120 ns. For about 120 ns both are on. The supply is shorted through them, and the current is limited only by their tiny resistance.
The fix is old and simple. After one switch is told to turn off, wait before telling the other to turn on. This pause is the dead time. During it both switches are off and the motor current flows through the transistors' body diodes. A body diode is a one-way path that is built into every power MOSFET, a small side door that stays open for current while the main door is shut. A longer dead time is safer. A shorter one wastes less. The target is a dead time just longer than the worst-case difference between the turn-off delay of one switch and the turn-on delay of the other, plus a margin.
overlap = turn-off delay of the first switch − (dead time + turn-on delay of the second) if the result is zero or less, there is no overlap
You do not build this pause in software. The advanced timers have a dead-time generator in hardware. It delays the rising edge of each of the two complementary outputs. Software writes one 8-bit field, DTG, in the break and dead-time register, TIMx_BDTR. ST publishes two open-source C layers for the chip: the CMSIS device header, a file that gives every register and bit field a name, and the HAL (hardware abstraction layer), ready-made C functions that set those registers for you. In the STM32G4 CMSIS device header the field is TIM_BDTR_DTG, with a mask of 0xFF at bit 0. The STM32G4 low-level driver also has a helper macro that turns a time in nanoseconds into a DTG value. Reading that macro shows how the 8 bits are split into four ranges.
Let tDTS be the dead-time clock period. For a 80 MHz timer clock with no clock division it is 12.5 ns. The four ranges are these.
| DTG bits 7:5 | Dead time | Step at 80 MHz | Largest at 80 MHz |
|---|---|---|---|
| 0xx | DTG[7:0] × tDTS | 12.5 ns | 1,587.5 ns |
| 10x | (64 + DTG[5:0]) × 2 × tDTS | 25 ns | 3,175 ns |
| 110 | (32 + DTG[4:0]) × 8 × tDTS | 100 ns | 6,300 ns |
| 111 | (32 + DTG[4:0]) × 16 × tDTS | 200 ns | 12,600 ns |
The ranges grow coarser as the time grows. The first range reaches 1,587.5 ns with a 12.5 ns step. That covers the switches in this chapter, so it is the range you use. Work an example with the helper macro's own numbers. You want 120 ns. Divide by 12.5 ns: 9.6. The macro rounds down, so DTG = 9, and you get 112.5 ns, not 120. If your switch needs 120 ns, you are 7.5 ns short. Ask for 150 ns instead: 150 / 12.5 = 12 exactly, so DTG = 12.
Try the scope below. The top two rows are what the timer commands. The bottom two rows are what the transistors do. Move the dead time to close the red overlap. Then watch what the pause costs.
A virtual scope. The high switch is told to turn off at 100 ns. Raise the dead-time register until the red region disappears, then lower the switch's turn-off delay to see how much margin you gain.
A model. The timer clock is 80 MHz with no clock division, as in the STM32G4 low-level driver's own helper-macro example, so one DTG step is 12.5 ns. The switch delays are illustrative: 30 ns to turn on and the slider value to turn off. The 20 kHz PWM period of 50 µs sets the lost-duty figure.
Dead time has a cost. During the pause neither switch drives the leg, so the motor sees a slightly different voltage than you asked for. With a 20 kHz PWM the period is 50 µs and each period holds two dead intervals. At 150 ns that is 300 ns out of 50 µs, or 0.6% of the period. At low speed and light load this error matters. Field-oriented control, in the later motor lessons, often compensates for it.
Real drivers add a second guard. Many gate-driver chips include their own shoot-through protection. Read the datasheet of yours. The STM32 timer also has a break input, which can force the outputs to a safe state in hardware without waiting for software. The HAL driver describes the timer as having a break input "to put the timer output signals in reset state or in a known state." Use both layers. Software bugs happen, and a single bug must not cost a transistor.
c · STM32G4, TIM1 complementary PWM with dead time (HAL) TIM_BreakDeadTimeConfigTypeDef bdt = {0}; bdt.OffStateRunMode = TIM_OSSR_DISABLE; bdt.OffStateIDLEMode = TIM_OSSI_DISABLE; bdt.LockLevel = TIM_LOCKLEVEL_OFF; bdt.DeadTime = 12; /* DTG = 12: 12 x 12.5 ns = 150 ns at an 80 MHz timer clock */ bdt.BreakState = TIM_BREAK_ENABLE; bdt.BreakPolarity = TIM_BREAKPOLARITY_HIGH; bdt.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; /* outputs stay off after a break until software re-arms */ HAL_TIMEx_ConfigBreakDeadTime(&htim1, &bdt); HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1); /* OC1 : high-side gate command */ HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1); /* OC1N : low-side gate command, dead time inserted */
Now the three steps of a failure report, as they appear on a bench. The symptom is a bridge that heats up or fails when the duty rises. The measurement is a scope on the bridge's supply or on the low-side current sense: a short spike at every switching edge, as tall as the transistors allow. The fix is to raise DTG until the spike disappears, and then to add a margin of about 50% on top. Set DTG before you enable the PWM outputs.
On real hardware. Use an STM32 Nucleo (for example NUCLEO-G431RB) and a half-bridge driver board. Probe the two gate signals at the transistors with a two-channel scope, 20 ns per division. Measure the real gap between one gate falling and the other rising, and compare it with DTG times 12.5 ns. Do this at low supply voltage first.
Chapter 3
Command two hundred steps, see where the shaft really ends up, and learn the one load-and-speed rule that keeps a stepper honest
You build a small camera slider. The carriage must move exactly 50 mm and stop. You do not want to add a position sensor. A stepper motor promises a deal: you send it pulses, and each pulse turns the shaft by a fixed small angle. Count the pulses and you know where the shaft is.
It is a fine deal, with one hidden clause. The motor never tells you whether it kept its side. This chapter shows how the deal works and exactly when it breaks.
A stepper has two coils on the stator, called phase A and phase B, and a toothed rotor. Energize a coil and the rotor clicks to the nearest stable position for that field, as the compass needle did in Chapter 0. Switch to the other coil and the rotor clicks to the next position. Four patterns in order, A+, B+, A−, B−, turn the shaft through four steps. Reverse the order and it turns the other way.
A common size is 1.8 degrees per full step, which is 200 full steps per revolution. The Wikipedia article on stepper motors gives exactly that example. The motor has full torque at standstill if the windings are energized. That is its strength: it can hold a position with no feedback loop at all.
The pattern you choose changes the smoothness and the torque. In wave drive only one phase is on at a time. The step count is the same as full-step drive but the torque is below the rated value. In full-step drive two phases are always on, which gives the full rated torque. In half-step drive the pattern alternates between two phases on and one phase on. That doubles the resolution, to 400 positions on a 200-step motor, or 0.9 degrees. The single-phase positions give about 70% of the torque, according to the same article.
Then there is microstepping. Instead of switching a coil fully on or off, the driver sets the two coil currents to a sine and a cosine of the wanted angle. The rotor settles between the full-step positions, wherever the two fields balance. With 1/8 microstepping the step becomes 1.8 / 8 = 0.225 degrees, which is 1,600 positions per revolution. The motion is much smoother and the resonance is lower. The article also warns that the extra resolution is limited by friction, backlash and other mechanical errors. Many small commands may produce no motion and then a sudden jump.
A stepper is usually run open loop: the controller sends steps and trusts they happened. It works because of a simple torque curve. If the rotor lags the commanded position by an angle e, the motor pulls it forward with a torque of Tmax × sin(e). Here e is measured in electrical degrees, and one full step is 90 of them. A load torque pushes back. The rotor settles where the pull equals the load. That is the lag.
Take a load of half the available torque. The lag is asin(0.5) = 30 electrical degrees, a third of a step. The rotor trails the command by that much and keeps every step. Now raise the load to 100% and the lag reaches 90 degrees, the peak of the curve. Past the peak the pull gets weaker as the lag grows, so the rotor falls behind faster and faster. The field moves on without it and the rotor drops back a whole step to the next stable position. That is a lost step.
Speed matters too. The pull-out torque, the most the motor can give, falls as the step rate rises. The coil current needs time to build against the coil's inductance. At the start of the move you are asking the rotor to go from rest to full rate in one step, and the available torque is low. The standard cure is a ramp: raise the rate gradually. The device shows the effect with an illustrative pull-out curve that halves at 1,200 steps per second.
Left: the dial. The purple tick is where you commanded. The warm bar is the real shaft. Right: the torque curve at this speed. The yellow line is your load. If it sits above the curve's peak, steps are lost. Set a load and a rate, then press Send 200 steps.
An illustrative model. The pull-out torque is T0 / (1 + rate / 1,200) with T0 the standstill torque, and the load is a share of T0. Lost steps are counted as 200 × (1 − pull-out / load) when the load exceeds the pull-out torque. Real motors lose steps in messier ways, often at a resonance, and the dial runs at a fifth of real speed.
Watch the case that matters most. Set the load to 60% and the rate to 1,200 steps per second. The pull-out torque is 50% at that rate, so the load beats it. The dial shows 200 steps commanded and the shaft ends short. Nothing on the wires says so. The firmware thinks the carriage is at 50 mm. In the model it is at about 42 mm, because 33 of the 200 steps were lost.
Here is the failure written as a bench report. The symptom: the slider drifts a little further from home on every pass. The measurement: mark the shaft with tape, command 200 steps at rising rates, and see where the mark ends. The fix: ramp the rate up and down, lower the top rate, give more current, or add a sensor. A closed-loop stepper with an encoder is a different motor entirely, and the next lesson, Encoders and the position loop, shows how encoders close the loop.
c · step/dir pulses from a timer interrupt, with a rate ramp static volatile uint32_t rate_hz = 100, target_hz = 1200; /* steps per second */ static volatile int32_t steps_left; void stepper_move(int32_t n) { HAL_GPIO_WritePin(DIR_GPIO_Port, DIR_Pin, n > 0 ? GPIO_PIN_SET : GPIO_PIN_RESET); steps_left = n > 0 ? n : -n; rate_hz = 100; /* start slow: pull-out torque is highest here */ HAL_TIM_Base_Start_IT(&htim2); } /* called at every timer update event */ void TIM2_step_isr(void) { HAL_GPIO_TogglePin(STEP_GPIO_Port, STEP_Pin); /* one edge = half a pulse */ if (HAL_GPIO_ReadPin(STEP_GPIO_Port, STEP_Pin) == GPIO_PIN_RESET) { if (--steps_left == 0) { HAL_TIM_Base_Stop_IT(&htim2); return; } if (rate_hz < target_hz) rate_hz += 4; /* ramp up: 4 steps/s per step */ __HAL_TIM_SET_AUTORELOAD(&htim2, TIM_CLK_HZ / (2 * rate_hz) - 1); } }
The code ramps only upward and does not slow near the end. A complete version also brakes the last few hundred steps so the carriage can stop without overshoot. Keep the ISR short: it only toggles a pin and updates the reload value. The lesson on interrupts and DMA explains why.
On real hardware. Use a Nucleo with a step/dir driver board and any 200-step motor. Stick a strip of tape on the shaft. Command 200 steps at 200, 800 and 1,600 steps per second with a light load, and look at the tape. Find the rate where it starts to miss, then add a ramp and repeat.
Chapter 4
Learn why the rotor angle your code needs is not the angle you can see, and count how many switch changes a motor needs every second
Pick up a small gimbal motor, the kind that steadies a camera. Look at the ring of magnets on its rotor. Count them. A typical gimbal motor has fourteen, seven north and seven south. Turn the shaft one full turn by hand and the coils see that pattern go by seven times. That repeat count is the first thing a firmware engineer must learn to count in.
The firmware does not care how many degrees the shaft has turned. It cares where the magnets are relative to the coils. Because the pattern of magnets repeats around the shaft, the same relative position comes round many times per turn. This chapter builds the right angle to count in.
Microchip's AN885 describes the usual layout. The stator of a brushless motor holds three windings, called phases, joined in a star. In a star, one end of each winding meets at a common point, and the other three ends are the three wires you connect. We call the phases A, B and C. The rotor is a ring of permanent magnets with alternating north and south poles. AN885 says the rotor can have from two to eight pole pairs.
A pole pair is one north and one south magnet side by side. Let p be the number of pole pairs. A motor with p = 4 has eight magnets. The three coils repeat p times around the stator, so each coil appears four times, spaced evenly. As the rotor turns, each magnet pair passes each coil once. The picture the coils see is the same after the rotor moves 360 / p degrees.
To the coils, one pole pair passing is one full cycle. So we define the electrical angle, in which one pole pair is 360 degrees. It is the mechanical angle multiplied by the number of pole pairs.
Every motor lesson from now on uses θe. AN885 states the consequence plainly: for each rotor pole pair, one electrical cycle is completed, so the number of electrical cycles per mechanical turn equals the number of pole pairs. Six-step commutation changes the coils six times per electrical cycle. AN885 explains why. Every 60 electrical degrees one Hall sensor changes state, and it takes six steps to complete an electrical cycle.
Now count. For p = 4: a turn has 4 electrical cycles, so 6 × 4 = 24 commutation steps per mechanical turn. Each step covers 360 / 24 = 15 mechanical degrees. At 3,000 rpm the shaft turns 50 times a second, so the firmware must switch the coils 24 × 50 = 1,200 times a second, once every 833 µs. The electrical frequency is p times the turns per second: 4 × 50 = 200 Hz. AN885 gives a rule of thumb that the PWM frequency should be at least ten times the highest motor frequency. Here that means at least 2 kHz, and real drives use far more.
Left: the rotor magnets, with a purple mark for each place where phase A sits. Right: the electrical angle dial, cut into six commutation steps. Drag the rotor angle, change the pole pairs, then press Spin and set the speed.
A geometric model, not a datasheet. AN885 gives the 2-to-8 pole-pair range and the rule that the number of electrical cycles per mechanical turn equals the pole pairs. Spinning runs about forty times slower than the speed you set, so the picture is readable.
Two effects share one geometry. When you push current through a coil, it makes a magnetic field along its own axis. Send current into A and out of B and the two coils together make a field halfway between their axes. Because the three axes are 120 degrees apart, the six pairs of "one in, one out" give six field directions, 60 degrees apart. This is the whole reason the method is called six-step.
The magnets make an effect too. As they sweep past a coil they induce a voltage in it. This is the back-EMF of Chapter 1, now in each phase. AN885 gives the proportion: back-EMF is proportional to the winding turns, the rotor length and radius, the magnet field strength and the angular velocity. The shape depends on how the coils are wound. AN885 calls the two kinds trapezoidal and sinusoidal motors. The sinusoidal motor gives a smoother torque than the trapezoidal one, but costs more because the windings are more complex. Chapter 8 compares them.
The torque rule is the one from Chapter 0. AN885 says the peak torque occurs when the stator field and the rotor field are at 90 degrees to each other, and it falls off as they move together. With six field directions, 60 degrees apart, the stator field can only approximate that 90 degrees. Right after a switch the field leads the rotor by 120 degrees. Just before the next switch it leads by 60. Both give a torque of sin(120°) = sin(60°) = 0.866 of the best. Halfway between, at 90 degrees, the torque is 1. That swing of 0.866 to 1 is the torque ripple Chapter 8 measures.
Here is the failure for this chapter, written as symptom, measurement, fix. The symptom: the motor starts and runs, but at a speed far from what you set, or with a twitch every few degrees. The measurement: count the commutations per turn with a scope on one Hall line and compare with 6 × p. The fix: put the right p in your speed calculation, and read the datasheet to confirm whether it lists pole pairs or poles (a motor listed with 14 poles has 7 pole pairs).
On real hardware. Take a small BLDC motor and a Nucleo. Turn the shaft by one full mechanical turn by hand while you watch one Hall line on a scope or logic analyzer. The number of cycles on that line is p. Check it against the datasheet.
Chapter 5
Read the three Hall wires as one code, see why two of the eight codes should never appear, and catch a broken wire from the edge count
Put a logic analyzer on the three thin signal wires of a brushless motor. Turn the shaft slowly by hand. Three square waves appear. They have the same shape, the same period and a fixed shift in time. At every instant, the three levels together form a pattern, and the pattern changes six times in each electrical cycle.
That pattern is the only thing your firmware needs to start a brushless motor. This chapter shows where it comes from, how to read it, and how to tell when it is lying.
A Hall sensor is a small chip that outputs a high or low level depending on the pole of the magnet near it. The effect is named after E. H. Hall, who found in 1879 that a current-carrying flat conductor in a magnetic field develops a small voltage across its sides. AN885 explains it in a note, and then states what matters: whenever the rotor poles pass near the Hall sensors, they give a high or low signal, showing that an N or an S pole is passing.
Most brushless motors have three sensors, embedded in the stator at the non-driving end. AN885 notes that they may be placed 60 or 120 electrical degrees apart, and that the manufacturer defines the commutation sequence for each layout. This lesson uses the 120 degree layout. Call the sensors A, B and C. Sensor A goes high while the rotor's north pole is within 90 electrical degrees of phase A's axis. B and C do the same, 120 and 240 degrees later.
The sensors need power. AN885 says the supply may range from 4 V to 24 V, with a current of 5 to 15 mA, and the outputs are normally open-collector. An open-collector output can pull a line low, but it cannot push it high. The controller side must add a pull-up resistor, a resistor to the supply that lifts the line high when the sensor lets go. This detail matters in a moment, because it decides what a cut wire reads.
Read the three levels together as a number: A in the top bit, then B, then C. Three bits give eight codes. With sensors 120 degrees apart, only six of them occur as the rotor turns. Here they are, in the order the rotor passes through them, with the electrical angle of the middle of each sector.
| Sector | Rotor angle (centre) | Hall A B C | Code |
|---|---|---|---|
| 0 | 0° | 1 0 0 | 4 |
| 1 | 60° | 1 1 0 | 6 |
| 2 | 120° | 0 1 0 | 2 |
| 3 | 180° | 0 1 1 | 3 |
| 4 | 240° | 0 0 1 | 1 |
| 5 | 300° | 1 0 1 | 5 |
This table is the convention of this page, worked out from the geometry above. Your motor may start the sequence elsewhere or run it the other way, and the datasheet is the authority. The shape never changes: six codes, each one differing from its neighbours by exactly one bit.
The two missing codes are 0 0 0 and 1 1 1. They cannot happen with a 120 degree layout, because three levels shifted by a third of a cycle are never all equal. That makes them useful. If the firmware ever sees code 0 or 7, something is wrong: a wire is cut, a sensor is dead, or noise has hit the line. A 60 degree layout works differently. AN885's own example uses 60 degree sensors, and in its tables 000 and 111 are valid codes. Check which layout your motor has before you write the validity test.
One more fact about what the code means. It tells you which of six sectors the rotor is in, each 60 electrical degrees wide. It does not tell you where inside the sector the rotor is. With four pole pairs, 60 electrical degrees is 15 mechanical degrees. The Hall code gives a position only to within that. Chapter 9 uses the time between edges to estimate more, and the next lesson adds an encoder for fine position.
The three waveforms are the Hall lines over two electrical cycles. Drag the cursor to read the code. Then break Hall B with a wire fault and look at the bottom strip: what the rotor does against what the firmware reads.
A geometric model: sensor i is high while cos(θe − 120° × i) is above zero. A cut wire with a pull-up reads high. A line shorted to ground reads low. Real sensors have switching hysteresis and small placement errors.
Set the fault to "B cut, pulled high" and scan the cursor. Of the six sectors, three still read correctly. Two read as a neighbouring sector, so the firmware believes the rotor is 60 degrees away from where it is, and nothing flags it. One reads 1 1 1, an invalid code, which a validity test would catch. A validity test alone finds a third of the damage.
A second test finds more. Count the edges. On a healthy motor the firmware sees six Hall edges in every electrical cycle. With B stuck high, it sees only four. The scan shows it in the read-out. A watchdog that checks "six edges per electrical cycle while the motor is running" catches the fault even when the codes look plausible.
The failure, as a bench note. The symptom: the motor runs rough, with a stutter at the same angle each turn, or it refuses to start from some positions. The measurement: a logic analyzer on the three Hall wires, counting edges over one electrical cycle. The fix: repair the wire or the pull-up, and make the firmware treat code 0, code 7 or a miscount as a fault that stops the drive.
c · reading the three Hall lines in one load /* Hall A = PB8, B = PB7, C = PB6: three consecutive pins, so one read and one shift */ static inline uint8_t hall_code(void) { return (uint8_t)((GPIOB->IDR >> 6) & 7u); /* A<<2 | B<<1 | C */ } static const int8_t SECTOR_OF_CODE[8] = { /* 0 */ -1, /* invalid: all low */ /* 1 */ 4, /* 2 */ 2, /* 3 */ 3, /* 4 */ 0, /* 5 */ 5, /* 6 */ 1, /* 7 */ -1 /* invalid: all high */ }; int hall_sector(void) { int s = SECTOR_OF_CODE[hall_code()]; if (s < 0) fault_raise(FAULT_HALL_INVALID); /* stop the drive; do not guess */ return s; }
On real hardware. Use a Nucleo and a BLDC motor with Halls. Power the Hall supply, add pull-ups if the motor needs them, and watch the three lines on a logic analyzer while you turn the shaft by hand. Count the edges in one full turn. It should be 6 × p. Write down the order of the codes and compare it with the table above.
Chapter 6
Turn a Hall code into a choice of coils, then hand the switching to a timer so that it happens on the edge, not after an interrupt
You have the Hall code. Now you must decide which of the six power switches to close. A good answer fits in a table of six rows. Writing that table is the one place in this lesson where your firmware makes a decision about the motor.
The power stage for a three-phase motor has three half-bridges, one for each phase. A half-bridge is one leg of the H-bridge from Chapter 1: a high switch to the supply and a low switch to ground, with the phase wire taken from the middle. Six switches in all. Each phase wire can be joined to the supply (high), to ground (low), or to neither (floating, with both switches off).
In six-step commutation, exactly one phase is high, one is low, and one floats. AN885 puts it the same way: each step has one winding energized positive, a second negative, and the third not energized. Current flows in through the high phase, through two windings in series and out through the low phase. That makes the stator field point along one of six directions.
The rule of choice is the one you already know. Pick the pair whose field points about 90 degrees ahead of the rotor, so the push is close to its best. For each sector of 60 degrees, one pair does that job. Here is the table for the convention of this lesson, forward direction. The "field" column is the direction of the stator field, worked out from the three coil axes at 0, 120 and 240 degrees.
| Sector | Hall A B C | High (PWM) | Low | Floating | Field |
|---|---|---|---|---|---|
| 0 | 1 0 0 | B | C | A | 90° |
| 1 | 1 1 0 | B | A | C | 150° |
| 2 | 0 1 0 | C | A | B | 210° |
| 3 | 0 1 1 | C | B | A | 270° |
| 4 | 0 0 1 | A | B | C | 330° |
| 5 | 1 0 1 | A | C | B | 30° |
Look at the pattern. From one row to the next, exactly one phase changes its role: either the high one moves on, or the low one does. That is the signature of a correct table. A table where two phases change at once is a typo. Also notice the field column: it steps by 60 degrees each row, and the sector centres step by 60 degrees too, so the field always leads the rotor's sector centre by exactly 90.
To run the motor the other way, swap the high and low roles in every row. That turns the field by 180 degrees, so it now lies 90 degrees behind the rotor, and the push reverses. This is cheaper than it sounds: the same Hall decoding feeds a second table.
Speed comes from PWM. AN885 describes one common scheme: the high switch stays on for its whole step, and the low switch is chopped with the duty cycle. The motor sees the average voltage, duty times supply. It follows the same rule as the brushed motor of Chapter 1: more average voltage, more speed.
Work one example. The rotor is at 100 electrical degrees. Hall A is high while cos(100°) is above zero, so A reads 0. Hall B reads 1, because cos(100° − 120°) is positive. Hall C reads 0. The code is 0 1 0, sector 2. The table says C high, A low, B floating. The field points at 210°. The rotor is 110° behind it, and the torque factor is sin(110°) = 0.94.
Drag the rotor angle. The Hall code picks a row of the table, the table closes two switches, and the purple arrow shows the field they make. Switch the direction and watch the field flip to the other side of the rotor.
The model of this lesson: Hall sensors 120° apart, phase axes at 0, 120 and 240 degrees, and the Hall code order in the table above. The real order for your motor comes from its datasheet, and AN885 notes that the manufacturer defines the sequence. The turning runs slowly so you can read the table.
The simplest firmware reads the Hall pins in an interrupt on every edge and writes the six switches. It works at low speed. At high speed it fails in a quiet way, because the switch change comes late by the interrupt latency, and the latency varies. A late commutation means the field is not where the table assumed. The push falls and the current rises.
The STM32 advanced timers take the CPU out of this path. Read the open-source HAL driver and you can see how. One timer, say TIM3, runs in Hall sensor interface mode. The driver sets the TI1S bit of control register 2, which XORs the three Hall inputs into one signal. Any edge on any Hall line then flips that signal, so every one of the six edges triggers a capture. The driver also makes each edge reset the counter, and it uses channel 2 as a compare that sets a commutation delay. Its output goes to TRGO.
The power timer, TIM1, receives that trigger as a COM event, a "commutate now" pulse. The control bits that choose which outputs are on live in preload registers, because the driver sets the CCPC bit. You write the next step's bits in advance. They take effect together on the COM event, in hardware, on the edge. The HAL calls this ConfigCommutEvent, and its source can be the trigger input or a software write to the COMG bit. The HAL's own documentation notes that one timer interfaces with the Hall sensors and another timer uses the commutation event.
Dead time from Chapter 2 still applies, because TIM1's complementary outputs are what the COM event switches. Two details of timing remain for your own code. First, the CPU still has to write the next step's preload bits before the next edge, which gives you a deadline of one sector time. At 3,000 rpm and four pole pairs that is 833 µs, plenty. Second, filter the Hall inputs. The timer input filter field IC1Filter takes a value from 0 to 15 and rejects short glitches caused by the switching noise right beside the Hall wires.
c · six-step on STM32G4: Hall interface timer + COM event (HAL) /* Step table: for each sector, which phase is high, which is low (forward). */ static const uint8_t HIGH_PH[6] = { 1, 1, 2, 2, 0, 0 }; /* A=0 B=1 C=2 */ static const uint8_t LOW_PH [6] = { 2, 0, 0, 1, 1, 2 }; TIM_HallSensor_InitTypeDef hs = {0}; hs.IC1Polarity = TIM_ICPOLARITY_RISING; hs.IC1Prescaler = TIM_ICPSC_DIV1; hs.IC1Filter = 8; /* input filter, 0..15 (reject switching glitches) */ hs.Commutation_Delay = 10; /* timer counts between the Hall edge and the COM event */ HAL_TIMEx_HallSensor_Init(&htim3, &hs); /* sets TI1S: XOR of the three Hall inputs */ /* TIM1 listens for TIM3's TRGO as its commutation trigger (pick the ITRx in the reference manual) */ HAL_TIMEx_ConfigCommutEvent_IT(&htim1, TIM_TS_ITRx, TIM_COMMUTATION_TRGI); /* sets CCPC: preload */ HAL_TIMEx_HallSensor_Start_IT(&htim3); /* Runs just after each COM event: prepare the NEXT step's preloaded bits. */ void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) { int next = (hall_sector() + 1) % 6; bridge_preload(HIGH_PH[next], LOW_PH[next]); /* write CCER/CCMR bits; they take effect at the next COM */ }
The failure for this chapter: the symptom is a motor that runs but sounds rough, gets warm and loses speed as RPM rises. The measurement is the delay between a Hall edge and the matching gate edge on a scope. A fixed hardware path shows a tiny constant delay. An interrupt path shows a wobble. The fix is the timer path, plus the delay field to tune the commutation point.
On real hardware. Use a NUCLEO-G431RB with a three-phase driver board and a Hall BLDC. Probe one Hall line and one gate signal. Measure the delay from the Hall edge to the gate edge in the interrupt version and in the COM-event version.
Chapter 7
Work out the torque in every sector for a swapped wire, then find, by swapping two wires at a time, the wirings that spin cleanly
The prototype arrives with a cable. Three thick wires go to the motor windings. Three thin wires go to the Hall sensors. Both sets are coloured, and the colours in the drawing do not match the colours in the box. You connect them in the order that looks sensible, and the motor hums.
Count the ways to connect them. Three Hall wires can go to three Hall inputs in 6 orders. Three phase wires can go to three bridge legs in 6 orders. Together: 36 wirings. How many of them make the motor spin, and how can you find one quickly?
The hero showed a stall. Now find out exactly why it happens. In every sector the firmware picks a stator field direction φ. The rotor sits at an electrical angle θ. From the idea in Chapter 4, the push is proportional to sin(φ − θ). Call that the torque factor, g. It is 1 when the field is 90 degrees ahead, 0 when they line up, and negative when the field is behind.
Take the wiring where Hall sensors A and B are swapped. Stand the rotor at the middle of each sector in turn and ask what the firmware does. At θ = 0 the real Hall lines read 1 0 0, but the swapped pair reads 0 1 0. That is code 2, so the table closes the switches for sector 2, with a field at 210°. The factor is sin(210°) = −0.5. The push is negative, so the rotor is pushed backward.
At θ = 60° the real lines read 1 1 0, and swapping A with B changes nothing. The table is right, and g = 1. Now do all six centres. The results are in the table below, with the correct wiring and a third case, a Hall board mounted 60 degrees off, to compare.
| Wiring | g at 0° | 60° | 120° | 180° | 240° | 300° | Average |
|---|---|---|---|---|---|---|---|
| Wired right | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 | 0.955 |
| Hall A and B swapped | −0.50 | 1.00 | −0.50 | −0.50 | 1.00 | −0.50 | 0.000 |
| Hall board off by 60° | 0.50 | 0.50 | 0.50 | 0.50 | 0.50 | 0.50 | 0.477 |
Read the last column. The right wiring averages 0.955: the factor swings between 0.87 and 1 inside a sector, the ripple of Chapter 8. The swapped wiring averages zero. Two sectors of every six push forward at full strength and four push backward at half strength, and they cancel. A rotor in such a field cannot make net progress. It rolls to the nearest angle where the push crosses from forward to backward, and it sits there. That is the stall.
The off-by-60 board is the quiet failure. The push is half as strong in every sector, but it always points the right way. The rotor spins, and the model shows it spinning faster than the healthy motor: about 1,476 rpm against 1,223. A faster motor sounds like good news. It is a warning, because the back-EMF is smaller (g is smaller), so more current flows. The model draws 4.5 to 5.9 A, against 1.3 A when wired right.
A stall has a clear signature. The shaft does not turn, or it twitches a few degrees and stops. The supply current is V / R: 6.0 A in the model at 30% duty, from 7.2 V over 1.2 Ω. The winding heats at I2R, and the Chapter 1 note applies: a stalled motor is a heater. The measurement is the supply current, plus the Hall codes you read while turning the shaft by hand. The fix is a swap of two wires.
Why two wires? One swap turns an order into a neighbouring order, and a few swaps reach any order. Try it below. The grid has all 36 wirings. Each cell shows the speed that the model reaches. Green cells spin cleanly with a low current. Yellow cells spin hot. Red cells stall. Press a swap button to swap two Hall wires or two phase wires and watch where you land.
Rows: which Hall sensor each firmware input is wired to. Columns: which motor winding each bridge leg drives. The outlined cell is your wiring. Press Mystery bench for a random bad one, then swap two wires at a time until it turns green.
Every cell is a 1.5 s run of the same model as the hero: 30% duty, four pole pairs, no current limit. Green: it spins with under 3 A. Yellow: it spins but draws 3 A or more. Red: under 30 rpm. The model assumes the Hall board is aligned so that sensor a rises where winding U’s axis is. Real boards may differ, and your datasheet decides.
Count the grid. Six cells are green, three that turn the motor forward and three that turn it backward. Twelve are yellow and eighteen are red. From any cell, the fewest swaps to reach a green one is at most two: six cells need none, eighteen need one swap and twelve need two. If you land on a green cell that spins the wrong way, you do not touch the wires at all. You use the reverse table from Chapter 6.
A bench routine follows from this. Set a low duty and a low current limit. Turn the shaft by hand and record the Hall codes, as in Chapter 5. If they do not walk through the table in the expected order, swap two Hall wires. Then run at low duty. If the motor draws a high current and barely moves, or spins hot, swap two phase wires. Stop and think after two swaps. Before every attempt, check the current limit, because each wrong try is a short stall.
On real hardware. Use a Nucleo, a driver board and a Hall BLDC. Set the bench supply to 12 V with a 1 A limit. Run the six-step table at 10% duty. Measure the supply current and the speed in each of the wirings you try. A clean wiring draws the least current for the speed, as the model's 1.3 A against 4.5 to 6.0 A shows.
Chapter 8
Compute the torque of a six-step drive step by step, see where its wobble comes from, and decide when it is worth paying for a sine drive
Your robot joint works. It lifts, it holds, and it turns at speed. Then you ask it to creep at one turn per second and the camera on the end of the arm shows a buzz. Something is pushing unevenly, six times per electrical cycle. That something is the torque ripple of six-step commutation.
This chapter works out how big the ripple is, where it comes from, and what the alternative costs. It is mostly arithmetic, and every number is worked step by step.
Each phase has a back-EMF, e, that depends on the rotor angle, and a current, i. The power a phase turns into motion is e · i. Torque is power divided by speed. So, in units that remove the speed, the torque is the sum over the three phases of e · i. Use units where the back-EMF peak is 1 and the current is 1.
Take a motor with a sinusoidal back-EMF, so the phase voltages follow sine waves 120 degrees apart. Run six-step on it. In each sector two phases carry the current: +1 in the high phase, −1 in the low phase. In sector 0 that is B high and C low, so the torque is eB − eC. For sine voltages, the difference of two phases 120 degrees apart is √3 times a sine wave: 1.732 × cos θ, where θ is measured from the centre of the sector.
Now put in the sector limits. The sector runs from −30 to +30 degrees around its centre. At the centre, cos 0° = 1, so the torque is 1.732. At the edges, cos 30° = 0.866, so the torque is 1.732 × 0.866 = 1.5. So the torque swings between 1.5 and 1.732, six times per electrical cycle, with a mean of 1.654.
ripple = (maximum − minimum) / mean = (1.732 − 1.500) / 1.654 = 14.0%
The same maths explains the hero's torque factor: sin(90° ± 30°) is 0.866 to 1. It is the 0.866 again. The ripple is not a bug in your code. It is the price of pointing the field in only six directions.
A sine drive sets each phase current to a sine wave in step with that phase's back-EMF, so ik = −sin(θ − 120° · k). Each phase then gives sin2, and the three together always add to 1.5. The torque is flat. This is the idea behind field-oriented control (FOC), which the lesson on motor control firmware builds. It needs the rotor angle to a fine fraction of a degree, continuously, and not just a six-sector Hall code. That usually means an encoder (a sensor that reports shaft angle finely; some drives estimate it from the motor signals instead), and the next lesson, Encoders and the position loop, covers it.
Is the sine drive just smoother, or also better? Compare them at equal heat. The heat in the windings goes with the sum of squared currents. A six-step current has two phases at 1, so the sum is 2. A sine current has three phases at a mean square of one half, so the sum is 1.5. Scale the six-step current down by the square root of 1.5 / 2, which is 0.866, so both heat the motor equally. The six-step mean torque becomes 1.654 × 0.866 = 1.432. The sine drive gives 1.5. Six-step delivers 95.5% of the torque for the same heat, on a sine-EMF motor.
AN885 describes a second kind of brushless motor, the trapezoidal motor, whose back-EMF has flat tops. For a trapezoid with flat tops 120 degrees wide, the two energized phases both sit on their flat tops during a whole sector. Then eH − eL = 1 − (−1) = 2 at every angle. In the ideal case, six-step on a trapezoid motor has no ripple at all. That is the reason for pairing them.
The ideal breaks at the edge of each sector, because a coil current cannot change instantly. The coil has inductance, which acts like a heavy flywheel for current. When the firmware switches, the incoming phase current climbs and the outgoing one falls over a short stretch of angle. If the two ramps match, their torques add to a constant. If the climb is slower than the fall, the total dips. With a climb over 8 degrees and a fall over 4, the model gives a dip from 2.0 to 1.5, a 25% notch at every commutation. If the climb is faster, you get a bump instead. Use the sliders below to see both.
AN885 itself says that the sinusoidal motor gives a smoother torque than the trapezoidal one, at extra cost because of the more complex windings. The notch is a good part of the reason.
The warm curve is torque over one electrical cycle, in units of one phase's back-EMF peak times its current. The dotted lines mark the smallest and largest value. Choose a motor and a drive. For the six-step drives, set how fast the current climbs into the new phase and falls out of the old one.
An ideal-motor model: three phases with a sine or a trapezoid back-EMF (flat tops 120° wide), block currents of plus or minus one, linear current ramps starting at each commutation, and no friction or cogging. The slider values are illustrative, not from a datasheet. Four pole pairs set the ripple frequency.
Set the speed to 60 rpm with four pole pairs. The ripple frequency is 6 × 4 × (60 / 60) = 24 Hz. At 3,000 rpm it is 1,200 Hz. A rotor with some inertia smooths a 1,200 Hz push into almost nothing. At 24 Hz it shows. This is why six-step is fine for a fan and not for a camera gimbal.
The bench report: the symptom is a buzz or a shudder at low speed, at a frequency that rises with speed. The measurement is an accelerometer on the load, or the encoder velocity, with the frequency of the ripple compared with 6 × p × (turns per second). The fix is, in order of cost: tune the commutation timing and current ramps, raise the PWM frequency, add a sine drive with an encoder, or accept the ripple and smooth it with inertia.
On real hardware. Use a NUCLEO-G431RB, a three-phase driver and a BLDC with Halls. Hold the shaft lightly with a rubber band to a small mass on a table. Run six-step at 30 rpm and record the tabletop with a phone accelerometer app. Look for a peak at 6 × p × 0.5 Hz.
Chapter 9
Turn the time between two Hall edges into a speed, then find the two places where that number goes stale or wrong
Your motor now turns the right way. The next request is simple: hold 60 rpm, whatever the load. To hold a speed, a control loop needs to know the speed. You have no encoder, only three Hall wires. Can they tell you how fast the shaft turns?
They can, with a timer and one division. Along the way you meet two limits of this cheap sensor. Both are about time, and both can be measured.
Each Hall edge marks a change of 60 electrical degrees. The motor has p pole pairs, so one mechanical turn contains 6p edges, as Chapter 4 showed. If the shaft turns at n rpm, one turn takes 60 / n seconds. The time between two neighbouring edges is that, divided by the number of edges:
This is the method AN885 describes for low-cost speed feedback: use a timer to count between two Hall transitions, and calculate the speed from the count. On the STM32 the Hall interface mode of Chapter 6 does the counting for you. The HAL driver makes every edge reset the counter, so the captured value in the capture register is already the time since the previous edge, in timer ticks.
Work an example. Four pole pairs, 60 rpm, a timer counting at 1 MHz. The edges are 41.7 ms apart, so N = 41,667 ticks. Put that in: n = 10 × 1,000,000 / (4 × 41,667) = 60.0 rpm. Now a faster case. At 3,000 rpm the edges are 833 µs apart and N = 833. One tick of error is now 1 / 833 = 0.12% of the reading. At 60 rpm the same tick is 0.0024%. The count is finer at low speed and coarser at high speed.
A 16-bit timer counts to 65,535, then wraps to zero. At 1 MHz that is 65.5 ms. An edge interval longer than that wraps the count, and the formula returns a speed that is too high. For p = 4 the wrap happens below 10 / (4 × 0.0655) = 38 rpm. A 32-bit counter pushes the ceiling to over an hour. A slower tick, 100 kHz, pushes the 16-bit ceiling out to 655 ms, down to 3.8 rpm, and costs resolution at high speed: at 3,000 rpm N is only 83 and a tick is 1.2%.
There is a second low-speed trap. At standstill there are no edges at all, so no new speed arrives and the last value stays in your variable. The code must have a timeout: if no edge has arrived for, say, 100 ms, report speed 0.
A new speed arrives once per edge: 6p times per turn. At 60 rpm with p = 4 that is 24 times a second, every 41.7 ms. A speed loop running at 1 kHz sees the same number 41 times in a row. And the number describes the last 60 electrical degrees, so on average it is half an interval old, about 21 ms. A loop built on it reacts as if it had a 21 ms delay. The next lesson, Encoders and the position loop, studies how this delay limits what a speed loop can do.
The bump comes from the Hall sensors themselves. They are placed by hand or by a jig, and a placement error of 2 degrees means one sector is 62 degrees wide and its neighbour is 58. At steady speed the edge intervals alternate, and the computed speed alternates by about 2 / 60 = 3.3% either way. This is noise in the loop's input, and the loop will turn it into torque noise. The fix is to measure over all six edges of an electrical cycle. The sector errors cancel in the sum, because the six sector widths add to exactly 360 degrees.
The blue ticks are Hall edges. Each warm dot is the speed computed from one interval. The grey line is the true speed. The teal line averages six edges. Drag the speed down past the wrap point, and raise the placement error.
A model with four pole pairs. Each of the six sector widths is 60° plus an error that repeats every cycle and sums to zero, scaled by the slider. The count is rounded to whole ticks and wraps at the counter width. The pole pairs, the tick rates and the 100 ms timeout are illustrative choices, not a particular board’s.
c · Hall interval to speed, with a timeout /* TIM3 in Hall interface mode: the counter resets on every Hall edge, so the capture register holds the ticks since the previous edge. */ #define TICK_HZ 1000000.0f #define POLE_PAIRS 4.0f static volatile uint32_t edge_ticks, last_edge_ms; void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { if (htim->Instance == TIM3) { edge_ticks = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); last_edge_ms = HAL_GetTick(); } } /* called from the 1 kHz speed loop */ float hall_rpm(void) { if (HAL_GetTick() - last_edge_ms > 100 || edge_ticks == 0) return 0.0f; /* stopped, or slower than we can see */ return 10.0f * TICK_HZ / (POLE_PAIRS * (float)edge_ticks); }
Now the failure in report form. The symptom is a speed loop that is jumpy at low speed, hunts around its setpoint, or kicks hard as the motor starts. The measurement is the speed estimate logged against time: a staircase that changes only on Hall edges, with a six-step pattern from sensor error, and sudden jumps near the wrap speed. The fix is a longer counter or slower tick for the ceiling, a six-edge average or a calibrated sector table for the bump, a timeout for standstill, and an encoder when the loop needs better.
That brings the lesson full circle. Hall sensors give you three cheap things: a sector for commutation, an edge for a timer trigger and a coarse speed. They do not give you fine position, quick speed or good low-speed behaviour. When the application needs those, an encoder and a faster loop are the next step, and the robot-joint lessons that follow build them.
On real hardware. Use a NUCLEO-G431RB and a Hall BLDC. Run TIM3 in Hall interface mode and print edge_ticks over the debug port while you turn the shaft at a steady slow pace by hand. Watch the six-step pattern from sensor placement in the numbers. Then spin it with the drive and compare the estimate with a hand tachometer or a phone strobe app.
Chapter 10
Keep the numbers, terms, checklist and core code of motor firmware on one page, and find where each idea goes next
A brushed motor needs a voltage and an H-bridge. A stepper needs counted pulses and a rule for the load. A brushless motor needs your firmware to commutate: read a three-bit Hall code, pick one of six coil pairs, and apply the choice on the edge, behind a dead time that protects the bridge. Wire the Hall sensors in the wrong order and the rotor stalls. Drive it with six steps and the torque ripples by 14%. Both are the price of a cheap, sensor-light drive, and you now know how to measure each one.
| Quantity | Value | Source |
|---|---|---|
| Commutation steps per electrical cycle | 6, one every 60 electrical degrees | Microchip AN885 |
| Electrical cycles per mechanical turn | equal to the pole pairs p (rotors have 2 to 8) | AN885 |
| Commutation steps per turn | 6p; for p = 4 that is 24, each 15° of shaft | derived in Chapter 4 |
| Hall sensor spacing | 60° or 120° electrical; the maker defines the sequence | AN885 |
| Valid Hall codes, 120° layout | 6 of 8; codes 0 and 7 are faults | derived in Chapter 5 |
| Hall sensor supply and output | 4 to 24 V, 5 to 15 mA, open collector, pull-up needed | AN885 |
| PWM frequency rule of thumb | at least 10 times the maximum motor frequency | AN885 |
| Best torque | stator and rotor fields 90° apart | AN885 |
| Brushed motor | V = I R + Ke ω; stall current V / R | standard; Wikipedia, Brushed DC electric motor |
| Stepper | 1.8° per full step, 200 per turn; a half-step single-phase position gives about 70% torque | Wikipedia, Stepper motor |
| H-bridge rule | never close both switches of one leg | Wikipedia, H-bridge |
| Dead-time register | DTG[7:0] in TIMx_BDTR; four ranges with steps of 1, 2, 8 and 16 × tDTS | STM32G4 CMSIS header and LL driver |
| Hall interface and commutation bits | TI1S = CR2 bit 7; CCPC = CR2 bit 0; COMG = EGR bit 5 | STM32G431 CMSIS header; HAL driver |
| Six-step ripple, sine-EMF motor | 1.5 to 1.732, 14.0% of the mean; 95.5% of sine torque at equal heat | derived in Chapter 8 |
| Wirings of 3 Hall wires and 3 phase wires | 36: 6 clean, 12 hot, 18 stall (in the model) | model, Chapter 7 |
| Hall speed | n = 10 f / (p N); 16-bit at 1 MHz wraps below 38 rpm for p = 4 | derived in Chapter 9 |
| Term | In one line |
|---|---|
| Commutation | Switching which coils carry current, in step with the rotor. |
| Electrical angle | Pole pairs times the shaft angle: the angle the coils feel. |
| Back-EMF | The voltage a spinning motor makes against the supply; it grows with speed. |
| Stall current | Supply voltage over winding resistance: the largest current the motor draws. |
| Shoot-through | Two switches of one leg on together, which shorts the supply. |
| Dead time | A pause with both switches off between turning one off and the other on. |
| Hall code | Three sensor bits that name one of six 60° sectors of the rotor angle. |
| Six-step | One phase high, one low, one floating, chosen by a six-row table. |
| COM event | A timer trigger that applies all preloaded output settings at once. |
| Torque ripple | The swing of torque inside one cycle, as a share of the mean. |
| Lost step | A stepper step the rotor missed while the controller kept counting. |
The sketch below puts the Chapter 6 pieces together for TIM1 channels 1 to 3 as phases A, B and C. A high phase gets PWM on its high-side output. A low phase has its reference forced low, which makes the complementary output high and turns on the low switch. A floating phase has both outputs disabled. Check each bit against the reference manual for your part before you rely on it; the lesson’s own checks were the open-source HAL driver and the CMSIS header.
c · six-step core, STM32G4 (sketch) static const uint8_t HIGH_PH[6] = { 1, 1, 2, 2, 0, 0 }; /* A=0 B=1 C=2, forward */ static const uint8_t LOW_PH [6] = { 2, 0, 0, 1, 1, 2 }; static const int8_t SECTOR_OF_CODE[8] = { -1, 4, 2, 3, 0, 5, 1, -1 }; /* Write the NEXT step's output bits. CCPC = 1 holds them until the COM event. */ static void bridge_preload(int hi, int lo) { static const uint32_t OCM[3] = { TIM_CCMR1_OC1M, TIM_CCMR1_OC2M, TIM_CCMR2_OC3M }; static const uint32_t PWM[3] = { TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1, TIM_CCMR1_OC2M_2 | TIM_CCMR1_OC2M_1, TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1 }; static const uint32_t OFF[3] = { TIM_CCMR1_OC1M_2, TIM_CCMR1_OC2M_2, TIM_CCMR2_OC3M_2 }; /* forced inactive */ static const uint32_t EN [3] = { TIM_CCER_CC1E, TIM_CCER_CC2E, TIM_CCER_CC3E }; static const uint32_t ENN[3] = { TIM_CCER_CC1NE, TIM_CCER_CC2NE, TIM_CCER_CC3NE }; uint32_t m1 = TIM1->CCMR1 & ~(OCM[0] | OCM[1]), m2 = TIM1->CCMR2 & ~OCM[2]; uint32_t er = TIM1->CCER & ~(EN[0] | EN[1] | EN[2] | ENN[0] | ENN[1] | ENN[2]); for (int p = 0; p < 3; p++) { uint32_t mode = 0; if (p == hi) { mode = PWM[p]; er |= EN[p]; } /* high side chopped, low side off */ else if (p == lo) { mode = OFF[p]; er |= ENN[p]; } /* OCxREF low, so OCxN high: low side on */ if (p < 2) m1 |= mode; else m2 |= mode; /* floating: both outputs disabled */ } TIM1->CCMR1 = m1; TIM1->CCMR2 = m2; TIM1->CCER = er; } void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) { int s = SECTOR_OF_CODE[(GPIOB->IDR >> 6) & 7u]; if (s < 0) { drive_off(); fault_raise(FAULT_HALL_INVALID); return; } int next = (s + 1) % 6; /* forward; use the reverse table for the other way */ bridge_preload(HIGH_PH[next], LOW_PH[next]); }
Six-step with Halls is the entry level of motor control. It is cheap, it needs no fine position, and it is enough for fans, pumps, power tools and many drives. The next level is field-oriented control, which uses a fine rotor angle and a current loop to make the torque flat and efficient. Robot joints, gimbals and quiet servo drives use it. Both levels share what you learned here: a bridge with dead time, a timer that applies outputs on an edge, and a model of the rotor angle. Only the table is replaced by a calculation.
This lesson is built from primary sources, opened and read for it, and not from course slides. Each fact above comes from one of them, from the lesson’s own derivations (marked as derived), or from a model with illustrative numbers (marked as such).
Now press Present or Teach and explain one commutation step out loud, from memory: what the Hall code says, how the table picks two coils, why the dead time exists, and what happens when two Hall wires are swapped. Then go back to the motor at the top, swap the Hall wires, and say which sector torque factors you expect before you look.