There was one number in the OpenServoCore firmware I never liked. Below 13.3% duty, the servo didn’t trust its own motor terminal readings and just threw them away. A servo holding a light load or creeping toward a goal spends a lot of its life down there, and that’s exactly where it couldn’t read its own motor terminals, the readings the back-EMF speed estimate runs on.

I knew roughly that the floor came from where the samples sit in the ADC (analog-to-digital converter) scan, and I had filed it under “that’s just how the scan is”. It turned out one sample was the whole problem, and it could move. Moving it to before the PWM crest took the floor from 13.3% to 7.7%, in both drive directions, and no part on the board changed.

If you’re new here, OpenServoCore is my effort to turn cheap MG90S-class servos into networked smart actuators with sensor feedback, cascade control, and its own single-wire bus protocol. Everything below ran on the rev 2A dev board, which carries a CH32V006 (WCH’s sub-20-cent RISC-V microcontroller), mostly with a resistor grid standing in for the motor.

TL;DR

If you want to skip all the tick counting, here it is:

  • The ADC scan starts at the PWM crest and converts one channel every 52 timer ticks. The second motor terminal was sampled 135 ticks after the crest. Below about 12% duty the drive pulse was over by then, so it read the brake and the motor resistance came out 4 to 5% high.
  • I moved that terminal to the ADC’s injected group, triggered by a spare timer channel so its sample lands 37 ticks before the crest. The floor dropped from 160 ticks to 93, which is 7.7% duty.
  • Reverse drive still read 3 to 5% high, because there the early sample hit the high-side terminal right after its edge, before the supply sagged. Swapping the two terminal samples with the drive direction fixed it. Reverse now matches forward within 0.1 point.

Some Background

The motor driver is an H-bridge, four switches that connect each motor wire to the supply or to ground. The timer drives it with center-aligned PWM (pulse-width modulation) at 20 kHz. Center-aligned means the counter counts up from 0 to 1200 and then back down. I call the top of that count the crest. Every drive pulse is centered on the crest, so a window of h ticks switches on h ticks before the crest and off h ticks after. One tick is about 21 ns and the duty is h / 1200, so 93 ticks is 7.7% and 160 ticks is 13.3%.

Outside the drive window the bridge runs slow decay, which on this board means brake. Both motor wires sit at ground, so the winding is shorted to itself. Inside the window, one wire goes to the supply (the high side) and the other stays at ground (the low side).

Each motor wire has a resistor divider into the ADC, tap A and tap B. During the drive window, the difference between the taps is the voltage across the motor. Take away the current times the winding resistance and what’s left is the back-EMF, the voltage a spinning motor generates, which is proportional to its speed. With the shaft still there’s no back-EMF, so the difference over the current is the winding resistance. That’s how the servo measures R, and how it can guess its speed without an encoder.

All of that only works if each sample lands inside the drive window, so the firmware keeps a floor for each sense path and drops readings below it. The current’s floor was 64 ticks (5.3%). The terminals’ floor was 160 ticks, two and a half times higher.

Where the Samples Actually Land

The timer triggers one ADC scan at every crest, and the scan converts its channels one after another. Shunt, tap A, tap B, then the pot and some slow board readings. The ADC runs at 24 MHz against a 48 MHz timer, so one ADC clock is two ticks and each conversion takes 26 clocks, 52 ticks. I tried 48 MHz once and the ADC lost about a third of its codes, so 52 ticks a slot is what I get.

Each conversion tracks its input for a while and then holds it. Counting the trigger delay, the hold moments land at:

  • shunt, 31 ticks after the crest
  • tap A, 83 ticks after
  • tap B, 135 ticks after

The drive window closes h ticks after the crest. So tap B at +135 needs a window of at least 135 ticks, plus the time for the terminal to fall, or it samples the brake. 160 ticks is that plus some margin. That’s the whole floor!

Notebook 16 checked this properly. A burst is the servo recording every sample over a short stretch of PWM periods, and folding one onto a single period draws each tap’s whole waveform. Across 64 burst sets from notebook 15, the high-side terminal is half way up 41.5 ticks after switch-on, give or take about a tick, from 28 to 61 °C on the board and in both op-amp modes. So the floor is a timing question.

In a 93-tick window the terminals fall about 107 ticks after the crest. Tap A at +83 still reads 98% of its step, and tap B at +135 reads the brake. On the old firmware the 8% rung read R 3.8 to 5.3% high, and tap B at that rung read 615 counts against 695 at 15%. 615 counts is the brake level. That one was a facepalm.

Sampling Before the Crest

So tap B had to be sampled earlier. The regular scan can’t start before the crest, because the crest is its trigger, and the shunt already has the first slot.

But the CH32V006’s ADC has a second sequence called the injected group. It’s a short list of up to four conversions with its own trigger and its own result registers. Think of it as an interrupt for the ADC. Something else fires it, it converts, and the regular scan carries on. I put tap B alone on the injected group and triggered it from TIM1 channel 4, a timer channel no pin uses, at 1200 - 68 on the way up. That’s 68 ticks before the crest, so the hold lands 37 ticks before the crest and the conversion is done 12 ticks before it.

The 68 comes from one conversion (26 ADC clocks), the trigger delay (2) and a guard (6), times two ticks a clock. The guard is there because a crest trigger that lands during an injected conversion postpones the whole regular scan, and then every other sample moves too.

On the same short window, the samples now land like this.

Here is the timer side:

pub fn configure_compare_trigger(ch: Channel, ccr: u16) {
    let n = (ch as u8 - 1) as usize;
    TIM1.chctlr_output(n / 2).modify(|w| {
        w.set_ocm(n % 2, Ocm::PWMMODE2);
        w.set_ocpe(n % 2, false);
    });
    TIM1.chcvr(n).write_value(ccr);
    TIM1.ccer().modify(|w| w.set_cce(n, true));
}

It puts channel 4 in a PWM mode so its compare makes a trigger event, turns off the compare preload so the value applies right away, writes 1200 - 68, and enables the channel’s output.

The timer runs center-aligned mode 2, which fires compare events only while counting up, so there’s one injected conversion a period. But my first image converted nothing at all. The compare event doesn’t reach the ADC unless the channel’s output enable (CC4E) is set, even though no pin carries channel 4. I found that one on the bench. The pin channel 4 could be routed to stays a plain GPIO, so the output goes nowhere.

The best proof came from a probe image that kept streaming the old tap B sample in a spare column, so one ladder carried both samples of the same terminal in the same rows. At 96 ticks (8% duty), R from the early sample read 0.3% low and R from the old one 3.7% high.

A Facepalm Along the Way

The first bench images of the fix were built from a branch older than the switch to the op-amp’s normal mode from the last post, so they were quietly running high-speed mode. The giveaway was the current’s zero with torque off, about 1104 counts where normal mode sits at 1178.

Sample timing doesn’t care about the op-amp mode, so the timing results stand. But their currents can’t be compared with the normal-mode sessions, so notebook 16 grades every ladder only against its own 30% and 40% rungs, far from any edge. And now I read the zero before anything else.

Picking the New Floor

The early sample has a limit of its own. In a 93-tick window it closes 56 ticks after switch-on, and the low-side terminal is still climbing there, at 79% of its step. That sounds bad, but the low side is a small step, about 90 counts against a 1650-count terminal difference, so the missing part is about 1% of R.

On the ladders the 84-tick rung (7%) reads R about 1% high and the 96-tick rung (8%) 0.4% low, so 93 sits between them. The firmware’s own terminal difference is held at 84 ticks and live at 96, which is how it should be. The servo now publishes 7.7% as its terminal floor, so a host planning a low-duty move can read it.

The part I liked most is that the burst folds predict the ladders. Across 148 rungs from 84 ticks up, the folds read at each layout’s sample moments miss the measured R error by a median of 0.19 points. Graded against the 30 to 40% rungs, the old layout climbs to about +4% under 160 ticks, and the early sample stays inside 1% from 84 ticks up. The predicted and measured curves are side by side in notebook 16.

Reverse Was Still Wrong

Forward looked great. Reverse read 3 to 5% high from 108 to 180 ticks.

In reverse, tap B is the high side, so the early sample now landed on the high-side terminal right after switch-on. I looked at that terminal through a long window, and the trace is in notebook 16.

It jumps to about 2400 counts, sags to about 2330 over the next 150 ticks, then climbs back. The shunt current dips and recovers at the same moments, and current through a fixed resistor only dips if the voltage across it really dipped. So this is the supply rail, and the tap is fine. The grid has no inductance, so its current steps to 1.7 A in one edge, and the bench supply and the board’s capacitors take a moment to catch up.

The early sample sees the rail before the sag, while the shunt at +31 and the other tap see it in the sag. Mix those and R reads high. The high side alone explains 4.4 of the 5.0 points the reverse ladder read at 120 ticks.

A separate floor for reverse would have had to sit near 20% duty, which throws away most of the win. The clean fix was to never sample the high side early. The low side is a small voltage, about 330 mV across the low switch and the shunt, and it barely moves after its edge. So the firmware now swaps the taps with the drive direction. Whichever tap is the low side goes on the injected group at -37, and the high side takes the scan slot at +83, past the sag.

The swap happens on a direction flip, and only in the idle gap after the crest scan. Writing the sequence mid-conversion restarts the group, which would rotate the DMA (direct memory access) ring that copies results into RAM, and every reading would land under the wrong name. The one frame that straddles a flip is mapped by the old order. That’s fine, because a flip restarts the duty from below the floor, so that frame’s terminals are never used.

With the swap, reverse reads -0.3%, -0.8%, -0.4% and +0.2% at 8, 10, 15 and 20% duty, within 0.1 point of forward at every rung. So R from the terminal difference sits within 0.9% from 96 ticks up, both ways.

What It Cost

The V006 has a 50 µs tick and not many cycles to spare. The injected group cost almost nothing, idle load went from 32.86% to 33.12%.

The swap looked worse at first. Idle went from 34.6% to 35.0% and a 20% drive got about 2 points heavier, which is a lot for a match on a two-way enum. A diagnostic build showed the swap instructions weren’t the cost. On this chip a taken branch that lands on an address that is 2 mod 4 pays an extra flash fetch, so shifting code by 2 bytes anywhere in the tick handler moved the load by up to 1.5 points. An LLVM flag, -align-all-nofallthru-blocks=2, aligns jump-only targets to 4 bytes without putting padding in the executed path. Main got about 0.4 points lighter and stopped swinging with code placement, for 586 bytes of image. With that in, the swap costs 0.04 points idle and under a point at 20% drive.

This is the stuff I actually enjoy about a sub-20-cent chip. On a bigger part nobody would ever notice a 2-byte shift.

On a Real Motor

The grid is the worst case for the rail, so the real test is the MG90. The first free-running ladder on the motor put the firmware’s terminal difference within 0.3% of the 20% rung at 8, 10 and 15% duty, with forward and reverse within 0.2% of each other. It was absent at 7% and live at 8%, so the 93-tick floor holds on the motor too. That run isn’t written up as a notebook yet.

The Hardware Fix I Didn’t Do

The plan going in had a second option, 100 nF caps on the taps in place of 100 pF, so each tap reads an average over the period. That would move the floor to about 5% with no firmware change. But every consumer would then need the real ON time or a model of the switch drops, and the fast loop would pick up a couple of periods of lag. The firmware fix got to 7.7% without any of that, so the caps stay at 100 pF.

Caveats

  • One board, one grid, one bench supply. The edges and sample moments are timer facts and should carry over. The size of the reverse error is a supply fact and won’t.
  • Fast decay still floors at 160 ticks. Its terminals come from the scan at the bottom of the count, where tap B still closes 135 ticks in.
  • The back-EMF speed estimate still floored at 160 when I finished this work. The drive pulse comes out shorter than commanded, and my first correction for that made the estimate worse on the MG90. It has since come down to 93 as well.
  • On the images with the injected conversion, tap A reads about 200 counts high at the 72-tick rung, and I don’t know why yet. It’s under every floor, so nothing waits on it.
  • The current has its own 64-tick floor, set by how fast the op-amp settles. Its correction table was measured in high-speed mode and needs a rescale. That’s a separate story.

What’s Next

The back-EMF speed estimate got down to 93 ticks later, and that’s where a slowly creeping servo actually needs it. Why that estimate is hard on a cheap brushed motor in the first place is its own story, and I wrote it up in a separate post.

All the ladders and burst folds are in notebook 16. If you’ve fought ADC sample timing on center-aligned PWM before, or you know where the CC4E requirement is written down, let me know!