Timers, PWM and Sampling Without Jitter

A hardware timer ticks at an exact rate. Let it start the ADC and every sample lands on the tick. Read the ADC inside an interrupt, and busy code shifts each sample by microseconds.

Learn how a microcontroller counts time, turns a count into a servo signal or an audio sample clock, measures a pulse, and samples a signal at exact moments.

Pick how the ADC is started, then raise the other interrupt work. Watch the blue samples drift off the ticks and the rebuilt wave bend. Then we build every part from zero: the counter, PWM, capture, the trigger wire and the aliasing trap.

You need a little C and the idea of a clock (a signal that ticks at a steady rate). We teach the interrupts and the sampling maths we use, inside the chapters.

Part of Firmware from Zero to Expertise. Grounded on the STM32 reference manuals and ST driver headers, Arm’s Cortex-M material, Analog Devices tutorial MT-007 and the free Valvano textbook. The full list is in the Field Guide (Chapter 10).

Start the ADC two ways

40%

A model, not a measurement. Ticks are every 62.5 µs (16 kHz). In ISR mode, the chance that a higher-priority interrupt is still running at the tick is the load, and it then holds the read back by up to 50 µs (illustrative). The timer path adds only a few nanoseconds of converter and clock jitter (illustrative). The 2π·f·σ formula is from Analog Devices MT-007.

Chapter 0

Why a Microcontroller Needs a Clock It Can Trust

See why code that reads a sensor “about 16,000 times a second” is not the same as code that reads it exactly that often

You build a small microphone board. The firmware reads the ADC (the part that turns a voltage into a number) inside a loop. You test it with a pure 2 kHz tone. The recording sounds fine.

Then you add a radio, a display and a motor driver. The tone in the recording now has a hiss under it. Nothing in your audio code changed. The hiss grows each time you add another feature.

The hiss comes from time, not from voltage. Each sample was taken a few microseconds late, and the amount of lateness changed from sample to sample. The program still stores the samples as if they were spaced exactly 62.5 µs apart. The wave it rebuilds is slightly wrong at every point. That error sounds like noise.

The fix is not faster code. The fix is to stop asking code to keep time. A microcontroller has a small piece of hardware built for this job: the timer. This lesson shows what it is, what it does for you, and how it tells the ADC when to sample.

A timer is a counter that never gets busy

A timer is a register (a small memory cell in the chip) that adds one at every tick of a clock. It runs on its own. No instruction has to execute for it to count. Your program can be in the middle of a long function, and the counter still moves exactly one step per tick.

Think of a kitchen timer next to a cook. The cook can be chopping, stirring or answering the phone. The timer still rings on time, because it does not depend on the cook’s attention. Software that watches the clock is the cook looking at his wrist. Hardware that counts is the kitchen timer.

We use one concrete part through the whole lesson: the STM32F411RE, an Arm Cortex-M4 chip on the Nucleo-F411RE board. It runs at up to 100 MHz. One tick of 100 MHz is 10 ns. Its timers TIM2 and TIM5 count with 32 bits, and TIM3 and TIM4 with 16 bits (the same split is listed in the reference manual of the sister part STM32F412, RM0402, whose timer chapter we read; confirm in RM0383 for the F411).

What a register is

We keep saying “register”. Here is what it is on this chip. A register is a 32-bit word at a fixed address in the memory map, but it is wired to hardware instead of to RAM. When you write to it, you change how a peripheral behaves. When you read it, you see what the peripheral is doing now.

The C name TIM3->PSC is just a nicer way to write the address. TIM3 starts at 0x4000 0400, and the prescaler sits 0x28 bytes after the start, so PSC is the word at 0x4000 0428. The header file from ST lists every offset: CR1 at 0x00, CR2 at 0x04, CNT at 0x24, PSC at 0x28, ARR at 0x2C, CCR1 at 0x34. The lesson Bits, Types and the Memory Map shows how to read and write such words safely.

The three jobs of one counter

The same counter does three useful jobs. Each job is a different way to look at the number it holds.

  1. Tick: when the counter reaches a set limit it wraps to zero and raises an update event. That event repeats at a fixed rate. It is a heartbeat.
  2. Compare: a second register holds a value. While the counter is below that value an output pin is high. After that it is low. This makes PWM, a pulse train whose width you choose.
  3. Capture: when an outside signal changes, the hardware copies the counter into a register. The copy tells you when the edge happened, to the nearest tick.

The device below shows all three on a tiny counter that wraps at 10. Move the slider to step time. Switch jobs and watch which register changes.

One counter, three jobs

The warm staircase is the counter, wrapping after 9. Choose a job. Drag the tick slider to step through time.

12

A toy counter with an auto-reload value of 9, a compare value of 4 and outside edges at ticks 4 and 13. Real timers do the same with 16 or 32 bits and a clock of up to 100 MHz on this chip.

Every chapter that follows uses one of these jobs. Chapters 1 to 3 use tick and compare. Chapter 4 uses capture. Chapters 5 to 6 use the tick to start the ADC. Chapters 7 to 9 explain what the samples mean, and what a slightly wrong clock does to them.

The road

  1. The counter: prescaler, auto-reload and the update event.
  2. PWM: a compare register that draws a pulse, from servo to audio DAC.
  3. Choosing the numbers: exact frequency versus fine steps.
  4. Input capture: measure a pulse with the same counter.
  5. Late samples: why an interrupt cannot keep exact time.
  6. The trigger wire: timer to ADC to DMA, with no code in the path.
  7. Aliasing: what slow sampling does to a fast tone.
  8. The filter before the ADC: remove what you cannot sample.
  9. Crystal drift: when two clocks that agree “almost” fill a buffer.
  10. Field Guide: numbers, checklist, core code, sources.
Why does reading the ADC inside a software loop add noise to a recording, even when the loop runs 16,000 times a second on average?

Chapter 1

The Counter: Prescaler, Auto-Reload and the Update Event

Turn a 100 MHz clock into a 50 Hz heartbeat with two numbers, and learn the three ways that goes wrong

You want a pulse every 20 ms to drive a hobby servo. Your chip ticks 100 million times a second. That is 2 million ticks in every 20 ms. A counter register cannot hold 2 million if it has 16 bits, because 16 bits stop at 65,535. You need to slow the clock before you count it.

The timer has two dividers for this. The prescaler (written PSC) slows the clock that feeds the counter. The auto-reload register (written ARR) sets the highest value the counter reaches before it wraps back to zero. Slow the clock first, then choose where to wrap.

The chain, one stage at a time

Follow one tick through the chip. The clock tree gives the timer a clock, called ftimer. On the Nucleo-F411RE at 100 MHz, TIM2 to TIM5 sit on the slow bus APB1, which runs at 50 MHz. The reference manual rule is that a timer on a bus with a divided clock gets twice the bus clock. So the timers see 100 MHz. (We read this rule in the STM32F4 timer chapter of RM0402. Check RM0383 and the clock tree of your own board.)

The prescaler divides that clock by PSC + 1. ST’s driver header states it plainly: the counter clock is fCK_PSC / (PSC[15:0] + 1). So PSC = 0 means “divide by 1”, and PSC = 99 means “divide by 100”. The counter, called CNT, adds one at each divided tick. When it passes ARR it returns to zero. That wrap is the update event.

Because CNT runs from 0 to ARR, it visits ARR + 1 different values before it wraps. That is why the formula carries two “+ 1” terms.

fupdate
How many update events happen each second. This is the heartbeat rate, and later the PWM frequency or the sample rate.
ftimer
The clock that reaches the timer. 100 MHz in our example.
PSC + 1
The prescaler divide ratio. The register holds one less than the ratio.
ARR + 1
The number of counts in one period. The register holds one less than the count.

100 MHz / (99 + 1) = 1 MHz → 1 µs per tick → (19,999 + 1) ticks = 20,000 µs = 20 ms → 50 Hz

That worked example is the servo of the next chapter. Notice the middle step. After the prescaler, one tick lasts exactly 1 µs. A counter that ticks in microseconds is easy to think about: ARR + 1 is the period in microseconds.

Set the two dividers

Pick a preset, then move PSC and ARR. The staircase is the counter over three periods. Tick the box to feed in the wrong timer clock and see the error.

99
19999

The arithmetic is the formula above with ftimer = 100 MHz (TIM2 to TIM5 on a Nucleo-F411RE at 100 MHz SYSCLK). ARR is limited to 65,535 here because TIM3 and TIM4 count with 16 bits; TIM2 and TIM5 count with 32.

Try the servo preset with the box ticked. Your own arithmetic says 50 Hz. The real pin says 100 Hz. Nothing in your code is wrong, only the number you assumed for ftimer.

Three ways it goes wrong

The counter never moves. The symptom is a pin that stays at one level. You measure CNT in the debugger and see it stuck at 0. The cause is that every peripheral sits behind a clock gate that starts closed. The fix is to set the enable bit before you touch any other timer register, for example RCC->APB1ENR |= RCC_APB1ENR_TIM3EN. The lesson First Light: Clock Tree, PLL, Pin Mux covers the gate in detail.

The period is wrong by a small factor. The symptom is a frequency of 49.5 Hz where you wanted 50. You measure it on a scope or a logic analyzer. The cause is almost always a missing “− 1”: PSC = 100 divides by 101. At PSC = 100 and ARR = 19999, fupdate = 100 MHz / (101 × 20,000) = 49.5 Hz. The fix is to write the register as the ratio minus one, and say so in a comment.

The first period is wrong. The symptom is one bad pulse after start-up. The cause is buffering. The prescaler is always buffered, and the auto-reload register is buffered when the ARPE bit is set, so a new value waits for the next update event before it acts. The fix is to write TIM_EGR_UG once. That sets the update-generation bit and loads PSC and ARR at once. (ST’s driver header notes that the prescaler can change on the fly because its register is buffered.) To get the buffered auto-reload behaviour, also set TIM_CR1_ARPE.

c, STM32F411 TIM3 as a 50 Hz heartbeat
/* TIM3 is 16-bit, on APB1. Timer clock = 100 MHz at SYSCLK = 100 MHz. */
RCC->APB1ENR |= RCC_APB1ENR_TIM3EN;   // 1. open the clock gate first
TIM3->PSC = 100 - 1;                  // 2. 100 MHz / 100 = 1 MHz, so 1 us per tick
TIM3->ARR = 20000 - 1;                // 3. 20,000 ticks = 20 ms = 50 Hz
TIM3->EGR = TIM_EGR_UG;               // 4. force an update so PSC and ARR load now
TIM3->CR1 |= TIM_CR1_CEN;             // 5. start counting

The model on this page is not a chip. On a real board you can check each number in a minute. See the note below.

A 16-bit timer has ftimer = 100 MHz, PSC = 99 and ARR = 999. How often does the update event occur?

Chapter 2

PWM: A Compare Register That Draws a Pulse

Use one extra register to turn the counter into a pulse of any width, then use that pulse to steer a servo or to fake an analog voltage

A pin on your chip can only be high or low. It has no “half on”. Yet you want to dim an LED, point a servo or play a sound. You can fake a middle level by switching very fast. If the pin is high for 25% of the time, a slow load such as an LED or a motor responds as if it got a quarter of the power.

That trick is pulse width modulation, or PWM. The pin repeats a cycle at a fixed frequency. You choose how wide the high part of each cycle is. The share of the cycle spent high is the duty cycle.

The compare register

Chapter 1 gave us a counter that wraps every ARR + 1 ticks. PWM needs one more register. Each timer channel has a capture/compare register (CCRx). In output mode, the hardware compares CNT with CCRx at every tick.

In PWM mode 1 the rule is one line. The output is active while CNT is below CCRx, and inactive otherwise. The reference manual says the same: the reference signal is high as long as TIMx_CNT < TIMx_CCRx. You select it by writing 110 into the OCxM bits of the channel’s mode register. Mode 2 is the mirror: low while CNT < CCRx.

Two registers now set two different things. ARR sets how long the cycle lasts, so it sets the PWM frequency. CCRx sets where inside the cycle the pin drops, so it sets the width. The counter is the ruler. CCRx is a mark on the ruler.

duty
The share of one cycle spent high, from 0 to 1.
CCR
How many ticks per cycle the pin stays high. CCR = 0 gives a pin that is always low.
ARR + 1
How many ticks make one cycle.

Set CCR higher than ARR and CNT is always below it, so the pin stays high for the whole cycle: 100% duty. That behaviour follows from the rule. It is a handy way to turn an output fully on.

Two ways to line up the pulses

So far the counter only counts up, then jumps back to zero. That is edge-aligned PWM: every pulse starts at the same moment, the wrap, and the falling edge moves. It is the simplest form, and it is all a servo or an LED needs.

The reference manual also describes a center-aligned mode. The counter counts up to the auto-reload value, then counts back down, and the pulse grows and shrinks around the middle of the cycle. The edges of two channels then stay centred on each other when their widths change. Motor drivers like this because the current ripple stays symmetric. A full up-and-down trip takes about twice as many ticks, so the PWM frequency for the same ARR is about half. Check the exact count in the manual before you rely on it.

Worked example: a hobby servo

A common hobby servo expects a pulse about every 20 ms (50 Hz). The width of the pulse chooses the angle: about 1.0 ms at one end, 1.5 ms at the centre and 2.0 ms at the other end. Treat those three numbers as nominal. Servos differ, so look at your servo’s own data sheet before you drive it to the ends.

Use the setup from Chapter 1: PSC = 99 and ARR = 19999, so one tick is 1 µs and the cycle is 20,000 ticks. Now the pulse width in microseconds is simply the CCR value. CCR = 1500 gives a 1.5 ms pulse, a duty of 1500 / 20000 = 7.5%, and the servo goes to the centre.

PWM as a cheap DAC

Put a resistor and a capacitor after the pin. This is an RC low-pass filter: it passes slow changes and blocks fast ones. The fast PWM edges are smoothed away. What is left is the average voltage, which equals duty × VDD. At 3.3 V and 25% duty the average is 0.825 V.

Now you have a digital-to-analog converter made from a timer. Its resolution is the number of steps per cycle, ARR + 1. With ARR + 1 = 4096 you get 12 bits, and at 100 MHz with PSC = 0 the PWM frequency is 100 MHz / 4096 = 24.4 kHz. A 1 kΩ resistor with a 0.1 µF capacitor has a corner frequency of 1 / (2π × 1000 × 0.0000001) = 1.59 kHz. The next chapter explains why steps and frequency fight each other.

Move the compare mark

Choose a job. Drag CCR. The pin goes low where CNT reaches CCR. On the right you see what the pulse does.

1500

Servo angle is drawn for nominal 1.0, 1.5 and 2.0 ms pulses (illustrative, your servo may differ). The DAC voltage is duty × 3.3 V, the average after an ideal filter. Real filters leave ripple.

Slide the servo CCR below 1000 or above 2000. The picture keeps turning but a real servo may hit its stop and hum. That is a good reason to clamp CCR in code.

Failure: the twitch

Symptom: the servo twitches or the LED flickers each time you change the value. Measurement: a logic analyzer shows one cycle with a very short or very long pulse right at the change. Cause: you wrote CCR while the counter was past the old value but below the new one. The pin switched in the middle of a cycle. Fix: enable the compare preload (the OCxPE bit). Then a new CCR value waits and takes effect at the next update event, at the start of a clean cycle.

c, STM32F411 TIM3 channel 1 as servo PWM on PA6
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
GPIOA->MODER = (GPIOA->MODER & ~(3u << 12)) | (2u << 12);       // PA6 = alternate function
GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFu << 24)) | (2u << 24); // AF2 = TIM3_CH1
TIM3->CCMR1 = (6u << TIM_CCMR1_OC1M_Pos) | TIM_CCMR1_OC1PE;   // PWM mode 1 (110) + preload
TIM3->CCER |= TIM_CCER_CC1E;                                // route the channel to the pin
TIM3->CCR1 = 1500;                                          // 1.5 ms: centre
/* later: clamp, then write. It takes effect at the next update event. */
static inline void servo_us(uint16_t us) { TIM3->CCR1 = us < 1000 ? 1000 : us > 2000 ? 2000 : us; }
With PSC = 99 and ARR = 19999 (1 µs ticks), you write CCR = 1250 in PWM mode 1. What does the pin do?

Chapter 3

Choosing PSC and ARR: Exact Frequency Against Fine Steps

Split one divide ratio into two registers, and see which split gives the right rate and which gives the most steps

You need a 48 kHz sample clock for an audio path. You have a 100 MHz timer clock. How do you pick PSC and ARR? Most people try a few numbers, measure, and adjust. There is a faster way, and it also explains why audio engineers like some crystal frequencies better than others.

Start from the formula in Chapter 1. The update rate depends only on the product (PSC + 1) × (ARR + 1). Call the product D, the total divide ratio. Many pairs of registers give the same D. The product sets the frequency. The split sets everything else.

Step 1: find the total divide ratio

Divide the timer clock by the rate you want. For 16 kHz: D = 100,000,000 / 16,000 = 6,250. That is a whole number, so a pair of registers can hit 16 kHz exactly: PSC = 0 and ARR = 6249 works.

For 48 kHz: D = 100,000,000 / 48,000 = 2,083.33. The product of two whole numbers is a whole number. You cannot make 2,083.33. The nearest choices are 2,083 and 2,084.

With D = 2,083 the rate is 100 MHz / 2,083 = 48,007.68 Hz. That is 7.68 Hz too fast, an error of +160 parts per million (ppm). With D = 2,084 the rate is 47,984.64 Hz, an error of −320 ppm. So you pick 2,083 and live with +160 ppm. We use that number again in Chapter 9, where it causes a real bug.

Step 2: split the ratio

Now split D into PSC + 1 and ARR + 1. For 48 kHz, 2,083 is a prime number. It has no factors besides 1 and itself. So the only exact splits are PSC = 0 with ARR = 2082, or the reverse. In practice you take PSC = 0.

When D has many factors you get a choice. Two goals pull in different directions.

The number of PWM levels gives the resolution in bits: log2(ARR + 1). A PWM frequency of 24.4 kHz at PSC = 0 on this clock gives ARR + 1 = 4,096, which is 12 bits. Ask for 97.7 kHz and you get 1,024 steps, which is 10 bits. A faster carrier is easier to filter but has fewer levels. This is the trade.

Here is the trade for PWM with real numbers. Keep PSC = 0 and the 100 MHz clock. Choose ARR + 1 = 1,024 and you get 10 bits and a carrier of 97.66 kHz. Choose 4,096 and you get 12 bits at 24.41 kHz. Choose 65,536 and you get 16 bits, but the carrier falls to 1.526 kHz, low enough to hear as a whine or to see as flicker. For an LED dimmer 12 bits at 24 kHz is a good middle. For a power stage you may want the higher carrier and accept 10 bits.

A 32-bit timer such as TIM2 changes the other end of the range. It can count to 4,294,967,295, so one second needs only PSC = 0 and ARR = 99,999,999. A 16-bit timer would need the prescaler to share the work. Both reach the same rate. Only the split differs.

Search the register pairs

Each dot is one PSC and ARR pair near your target. Left to right is the number of steps (bits of ARR + 1). Up is the rate error in ppm on a log scale. The bright dot is the pick with the least error and then the most steps.

Computed live in your browser for a 16-bit prescaler (PSC up to 65,535) and ARR up to 65,535, as on TIM3. A 96 MHz clock plan is possible on the F411 by setting the PLL; check your own clock tree. The ppm scale bottoms out at 0.01 ppm, labelled exact.

Pick 48 kHz and flip between the two clocks. At 100 MHz the best error is +160 ppm. At 96 MHz, D = 2,000 exactly, and the error drops to zero. This is why audio boards choose clock plans that are whole multiples of the sample rate.

Failure: the number that looked right

Symptom: your 44.1 kHz recording plays back with a slightly wrong pitch, or a long take slowly drifts away from a video. Measurement: count timer update events against a reference clock for 60 seconds, or look at the update frequency on a frequency counter. Cause: D = 100,000,000 / 44,100 = 2,267.57. Rounding to 2,268 gives 44,091.7 Hz, which is −188 ppm. Fix: change the clock plan so that D is whole, or let a dedicated audio clock source drive the sample clock. Chapter 9 shows what the error does over time.

c, find the best PSC and ARR on a PC or at start-up
typedef struct { uint32_t psc, arr; double err_ppm; } tim_cfg_t;

tim_cfg_t best_cfg(double f_timer, double f_want, uint32_t arr_max) {
    double D = f_timer / f_want;
    tim_cfg_t best = { 0, 0, 1e9 };
    for (uint32_t p = 1; p <= 65536; p++) {         // p = PSC + 1
        uint32_t n = (uint32_t)(D / p + 0.5);          // n = ARR + 1
        if (n < 2 || n > arr_max + 1) continue;
        double e = (f_timer / ((double)p * n) / f_want - 1.0) * 1e6;
        if (e < 0) e = -e;
        if (e < best.err_ppm - 1e-3 || (e < best.err_ppm + 1e-3 && n > best.arr + 1))
            best = (tim_cfg_t){ p - 1, n - 1, e };      // least error, then most steps
    }
    return best;
}
The timer clock is 100 MHz and you want 48 kHz. The ratio D is 2,083.33. What is the best you can do with whole-number registers?

Chapter 4

Input Capture: Time an Edge With the Same Counter

Let the hardware write down when a pin changed, then subtract two numbers to get a pulse width, a period or a speed

A small wheel sensor gives one pulse for each turn. You want to know how fast the wheel spins. One way is to watch the pin in your main loop and note the time when it changes. If your loop is busy for 300 µs, your note is 300 µs late. At high speed that error is large.

Chapter 1 gave you a counter that never gets busy. Input capture uses it as a stopwatch that the pin itself presses. When the pin changes, the hardware copies CNT into the capture register without any code running. Your program can read the number later. The number does not change while it waits.

How the channel works

The same CCR register you used for PWM has a second role. Set the channel to input mode and the hardware does the opposite of compare. Instead of comparing CNT with CCR, it writes CNT into CCR when an edge arrives. The reference manual says it plainly: the capture/compare register latches the value of the counter after a transition is detected.

Four settings shape this.

  1. Which pin. The pin is mapped to the channel as TI1 through the alternate function setting.
  2. Which edge. Rising, falling or both. In the ST driver the default rising setting means the circuit is sensitive to the rising edge of the filtered input.
  3. A filter. A noisy pin may bounce. The input filter only accepts a new level after it sees N matching samples in a row. The manual example waits for 8 consecutive samples.
  4. An event. A capture can raise a flag, an interrupt or a DMA request. If a second edge arrives before you read the first value, an overcapture flag tells you.

From two timestamps to a width

Capture the rising edge, then the falling edge. You have two numbers, t1 and t2. The width is t2 − t1, in ticks. Multiply by the tick length to get seconds. With a 1 MHz counter the answer comes out in microseconds.

Now the key detail. The counter wraps. A 16-bit counter reaches 65,535 and returns to zero. Suppose t1 = 60,000 and the edge falls after the wrap, so t2 = 4,000. Plain subtraction gives −56,000, which is nonsense. But the unsigned subtraction in C does the right thing. In a uint16_t, 4,000 − 60,000 wraps around to 9,536, and 9,536 is exactly how many ticks passed. The wrap in the counter and the wrap in the arithmetic cancel.

That trick works for exactly one wrap. If the pulse lasts longer than a full turn of the counter (65.536 ms for 16 bits at 1 MHz), the answer is too small by 65,536 ticks for each missed turn. Nothing warns you.

Time a pulse that may outlast the counter

The pulse starts at 10 ms. Drag its width. The warm sawtooth is the counter. Each purple tick is a wrap. Watch the measured width when the pulse crosses more than one wrap.

80 ms

Computed exactly: latched = round(t / tick) mod 2bits, measured = (t2 − t1) mod 2bits, the same wrap as unsigned C arithmetic. Resolution is one tick.

Choose 16-bit at 1 MHz and set 80 ms. The device reads 14.464 ms: short by one wrap. Switch to a slower tick or a 32-bit counter and the answer is right. A 32-bit counter at 100 MHz wraps only every 42.9 seconds.

Resolution, and the best use of the clock

One tick is your resolution. To measure a 1 kHz square wave with a 1 MHz tick you read 1,000 ± 1 ticks, an uncertainty of 0.1%. With a 100 MHz tick on a 32-bit timer the count is 100,000 ± 1: 10 ppm. A faster tick gives finer time, until the counter wraps too often to be handy.

One more useful mode: PWM input mode. Two capture registers watch the same pin. One latches on the rising edge and also resets the counter. The other latches on the falling edge. After each cycle, CCR1 holds the period and CCR2 holds the high time. The hardware does the subtraction for you. The manual describes it: two ICx signals are mapped on the same TIx input, active on edges with opposite polarity.

There is a deeper reason to love capture. The timestamp is exact even if your interrupt is slow. The hardware wrote the number at the edge. When the ISR runs 5 µs later, it reads the same value. This is the first hint of the next chapter: use hardware to remember the time, so late code does not matter.

c, STM32F411 TIM2 (32-bit) ch1 capture, width of an active-high pulse
/* TIM2 PSC = 99 gives a 1 MHz tick. CC1 captures the rising edge,
   CC2 (same pin, indirect) captures the falling edge. */
volatile uint32_t t_rise, width_us;
void TIM2_IRQHandler(void) {
    if (TIM2->SR & TIM_SR_CC1IF) { t_rise = TIM2->CCR1; }                // reading CCR1 clears the flag
    if (TIM2->SR & TIM_SR_CC2IF) {
        uint32_t t_fall = TIM2->CCR2;
        width_us = t_fall - t_rise;                                   // unsigned: survives one wrap
    }
}

Failure, as symptom, measurement and fix. The symptom: a flow meter reads 14 ms when the true pulse is 80 ms, but only at slow flow. You measure with a signal generator: short pulses are perfect, and the error appears exactly at 65.536 ms. The fix is to slow the tick, use the 32-bit timer, or count update events in a second variable and add 65,536 ticks for each one.

A 16-bit counter ticks at 1 MHz. You capture t1 = 60,000 and t2 = 4,000 for one pulse (one wrap between them). What width does (uint16_t)(t2 - t1) give?

Chapter 5

Why an Interrupt Cannot Keep Exact Time

Measure how late an interrupt-started sample can be, turn that lateness into a noise floor, and see what budget a 12-bit ADC allows

The usual first design for sampling is simple. A timer interrupt fires at 16 kHz. In the handler, you start the ADC, wait for it, and store the result. It works on the bench. It also contains a flaw that grows with every feature you add to the product. To see it, we first need to know what an interrupt really does.

An interrupt, from zero

An interrupt is a request from hardware: “stop what you are doing and run this function.” The function is the interrupt service routine, or ISR. The chip saves your place, runs the ISR, and then returns you to the exact point you left. (The lesson Interrupts, DMA and the 12 Cycles builds this from the vector table up. Here we need only four facts.)

  1. Each interrupt has a priority. A higher-priority interrupt can break into a lower one.
  2. It takes time to start. Arm lists 12 cycles for a Cortex-M4 with zero-wait-state memory. At 100 MHz that is 120 ns.
  3. An equal or lower priority interrupt must wait until the running ISR ends.
  4. Some code turns interrupts off for a short time, a critical section, to update shared data safely.

Arm says the real latency is often longer than 12 cycles, because a multi-cycle instruction may need to finish first, and memory may add wait states. So 120 ns is the best case.

Where the lateness comes from

Picture the timer tick as a bell that rings at exact times. The ISR is a person who must walk to the ADC when the bell rings. If the person is free, the walk is the same each time. If the person is in the middle of another job, the walk starts late. How late depends on what else is going on: a radio interrupt, a display refresh, a DMA burst that holds the bus.

A constant delay is harmless. If every sample is 1 µs late, the whole recording shifts by 1 µs and the spacing stays equal. The problem is the part that changes from sample to sample. That is jitter: the spread of the timing error around its average.

Turning jitter into noise

Take a sine wave of amplitude A and frequency f. Its steepest slope is 2πfA. If you sample at a moment off by Δt, the value is wrong by up to the slope times Δt. As a share of the amplitude that error is 2πfΔt. Fast signals are hurt more because they change faster.

SNR
The signal-to-noise ratio in decibels that timing jitter alone allows. Higher is cleaner.
f
The frequency of the sine wave, in hertz.
σt
The rms timing jitter, in seconds.

This is the aperture-jitter formula in Analog Devices tutorial MT-007. It assumes jitter is the only noise. Worked values for a 2 kHz tone: σt = 10 µs gives 18 dB. σt = 1 µs gives 38 dB. σt = 3 ns gives 88.5 dB.

Compare these with the ADC. An ideal 12-bit converter reaches 6.02 × 12 + 1.76 = 74 dB. To keep jitter noise below that at 2 kHz, you need σt of 16 ns or less. That is about one and a half ticks of the 100 MHz clock. No software path through an interrupt can promise it.

Here is the jitter number worked by hand, with three samples. Their delays are 0, 0 and 30 µs. The mean delay is 10 µs. The deviations from the mean are −10, −10 and +20. Square them: 100, 100 and 400. The mean of the squares is 200, so the rms jitter is the square root, 14.1 µs. For a 2 kHz tone, 2π × 2,000 × 14.1 µs = 0.178, and 20 log10(1 / 0.178) = 15.0 dB. One late sample in three is enough to ruin the recording.

Measure the lateness

Top: the first 600 µs. Purple blocks are other interrupts running. Yellow bars show how late each sample started. Bottom: how late 400 samples were. Choose a start method and raise the load.

50%

A model. Low priority: with probability equal to the load a blocking ISR still runs and holds the sample back by up to 50 µs. Top priority: 120 ns entry latency plus a rare stall of up to 0.5 µs from a critical section or a multi-cycle instruction. Timer trigger: a few ns. All three are illustrative; measure your own firmware. SNR uses the MT-007 formula at 2 kHz.

Even the top-priority ISR keeps a spread of a few hundredths of a microsecond in this model. Read the device: that lands near 60 dB at 2 kHz, not 74. The timer-triggered line wins because no instruction decides when the sample is taken. In the next chapter we wire it.

Failure: the hiss that grows

Symptom: the recording gets noisier each time a feature is added, and the noise is worse for higher tones. Measurement: toggle a GPIO pin at the top of the sample ISR and trigger a scope on a clean reference tick. Turn on infinite persistence. The edge smears across several microseconds. Fix: take the decision out of software. Let the timer start the ADC, as in Chapter 6, and let DMA store the result.

c, the fragile way: the ISR starts and waits for the ADC
void TIM3_IRQHandler(void) {
    TIM3->SR = ~TIM_SR_UIF;                       // clear the update flag
    ADC1->CR2 |= ADC_CR2_SWSTART;                 // sample begins HERE: after entry latency + any blocking
    while (!(ADC1->SR & ADC_SR_EOC)) { }          // busy-wait: sampling + 12 ADC cycles
    buf[n++ % N] = ADC1->DR;                      // reading DR clears EOC
}
Every sample in a recording is exactly 3 µs late. What does that do to the signal?

Chapter 6

The Trigger Wire: Timer to ADC to DMA With No Code in the Path

Connect the update event to the ADC start input, let DMA store each result, and budget the conversion time against the tick

In Chapter 5 the sample began when software said so. Now we want the sample to begin when the clock says so. Inside the chip there are internal wires between peripherals that bypass the CPU. One of them runs from a timer to the ADC. It is as if the timer had its own finger on the ADC’s start button.

Three hand-offs

Follow one sample from tick to memory. Three hardware blocks pass it along. The CPU runs no instruction on the way.

  1. Timer to trigger output. The timer can publish an event on an internal line called TRGO (trigger output). The field MMS in the control register CR2 chooses which event. Setting MMS to 010 selects the update event, the wrap you built in Chapter 1. ST’s driver names it TRGO_UPDATE: the update event is used as trigger output.
  2. Trigger to ADC start. The ADC has a field EXTSEL that chooses which line starts a conversion, and EXTEN that chooses the edge. On the STM32F4 ADC, EXTSEL = 0110 selects TIM2 TRGO. EXTEN = 01 means rising edge. The ADC then starts one conversion at each pulse. Compare this with SWSTART, the bit your ISR set in Chapter 5.
  3. ADC to memory. When the conversion ends the ADC raises its end-of-conversion flag. With the DMA bit set, that flag becomes a request to the DMA controller, a small engine that copies data without the CPU. DMA copies the 12-bit result from the ADC data register into a buffer in RAM, then moves to the next slot.

A circular buffer lets DMA wrap back to the start, forever. DMA also raises a half-transfer and a full-transfer interrupt. Those two interrupts are the only times your code runs. With a 512-sample buffer at 16 kHz, you process 256 samples every 16 ms. The samples were taken long before your code touches them, and their spacing was set by hardware.

The time budget

The trigger starts a conversion. The conversion takes time. Total conversion time is the sampling time plus 12 ADC clock cycles at 12-bit resolution (reference manual). The sampling time is a field you choose: 3, 15, 28, 56, 84, 112, 144 or 480 cycles. A longer sampling time lets a high-impedance source charge the ADC input fully, but costs time.

The ADC clock comes from the APB2 bus clock divided by 2, 4, 6 or 8. Take /4 on a 100 MHz bus: 25 MHz, so one ADC cycle is 40 ns. (Keep the clock under the limit in the chip’s data sheet.) With 84 cycles of sampling the conversion takes (84 + 12) / 25 MHz = 3.84 µs. At 16 kHz the tick is 62.5 µs. The ADC is busy for 6.1% of each tick.

(84 + 12) cycles × 40 ns = 3.84 µs  <  62.5 µs tick → 6.1% busy

The rule is simple: the conversion must finish before the next tick. Choose 480 cycles of sampling and the time is 19.68 µs, which still fits at 16 kHz and fails at 200 kHz, where the tick is only 5 µs.

Send a tick down the wire

Choose the sample rate and the ADC sampling time. Press Send one tick and follow the dot through four blocks. The bar underneath shows the conversion time against the tick.

ADC clock = 100 MHz / 4 = 25 MHz; conversion = sampling + 12 cycles at 12 bit; EXTSEL and sampling-time codes are from ST’s driver headers and the reference manual (RM0402 is the same ADC family; confirm against RM0383 for the F411). The 512-sample circular buffer is a design choice, not a chip limit.

The code

c, STM32F411: TIM2 TRGO starts ADC1 channel 0 (PA0), DMA fills a ring buffer
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;  RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
TIM2->PSC = 0;  TIM2->ARR = 6250 - 1;                 // 100 MHz / 6250 = 16 kHz exactly
TIM2->CR2 = (2u << TIM_CR2_MMS_Pos);              // MMS = 010: update event drives TRGO

ADC->CCR   = (1u << ADC_CCR_ADCPRE_Pos);          // ADCCLK = PCLK2 / 4 = 25 MHz
ADC1->SMPR2 = (4u << ADC_SMPR2_SMP0_Pos);         // 84 cycles of sampling
ADC1->SQR3  = 0;                                  // first (only) conversion: channel 0
ADC1->CR2   = ADC_CR2_EXTEN_0                        // trigger on rising edge
             | (6u << ADC_CR2_EXTSEL_Pos)             // EXTSEL = 0110: TIM2 TRGO
             | ADC_CR2_DMA | ADC_CR2_DDS              // DMA request on every end of conversion
             | ADC_CR2_ADON;                          // power the ADC
/* DMA2 stream 0, channel 0 (ADC1): source = &ADC1->DR, destination = buf,
   16-bit, circular, N = 512, half and full transfer interrupts on. */
TIM2->CR1 |= TIM_CR1_CEN;                              // last: start the clock

void DMA2_Stream0_IRQHandler(void) {                  // every 256 samples = 16 ms
    if (DMA2->LISR & DMA_LISR_HTIF0) { DMA2->LIFCR = DMA_LIFCR_CHTIF0; process(&buf[0],   256); }
    if (DMA2->LISR & DMA_LISR_TCIF0) { DMA2->LIFCR = DMA_LIFCR_CTCIF0; process(&buf[256], 256); }
}

The jitter that remains is the ADC’s own: the trigger must line up with the ADC clock, so expect an uncertainty of about one ADC clock period, 40 ns at 25 MHz. Spread evenly over 40 ns, that is 11.5 ns rms. By the formula of Chapter 5, a 2 kHz tone keeps 76.8 dB, above the 74 dB of a 12-bit ADC. Confirm the real figure in the data sheet and with a measurement.

Failure: it never converts

Symptom: the buffer stays at zero, or the ADC converts once. Measurement: in the debugger, read TIM2->CNT (it should move), TIM2->CR2 (MMS bits), ADC1->CR2 (EXTEN, EXTSEL, ADON) and ADC1->SR (EOC). Cause: the usual three: MMS left at 000, EXTEN left at 00 (trigger off), or EXTSEL set to a neighbour. Fix: set all three, and check the errata sheet for your exact part number.

Which setting makes the update event of TIM2 start ADC1 conversions on the STM32F4?

Chapter 7

Aliasing: What Slow Sampling Does to a Fast Tone

Sample a 7 kHz tone at 8 kHz on purpose, watch it turn into 1 kHz, and learn the one rule that predicts every case

In an old film, a stagecoach wheel sometimes seems to turn backwards. The wheel is not reversing. The camera takes 24 pictures a second, and each picture finds the spokes a little short of where they were. Your eye links the pictures into a slow, wrong motion. An ADC is that camera. It looks at a voltage at fixed moments. Between the moments it sees nothing. If the signal moves too fast, the pictures link up into a slower signal that was never there.

Sampling, from zero

To sample a signal is to read its value at equal time steps and keep only those values. The sample rate fs is how many readings per second. The step is Ts = 1 / fs, and it is exactly the update period you set in Chapters 1 and 3. (The lesson Discrete Signals builds the full theory. Here is the part you need.)

Take a cosine of frequency f. At the n-th sample the time is n / fs, so the value is cos(2π · f · n / fs). Only the ratio f / fs matters: it is how many turns of the wave fit in one step.

Now change f by exactly fs. The ratio grows by 1, which is one extra whole turn per step. A whole turn returns the cosine to the same value. So the new tone gives identical samples. Once sampled, f and f + fs cannot be told apart. The same holds for f + 2fs, and for the mirror image −f.

Check with numbers. Sample at fs = 8,000 Hz. A 7,000 Hz tone has ratio 0.875. A 1,000 Hz tone has ratio 0.125. At n = 1 the first gives cos(2π × 0.875) = 0.7071 and the second gives cos(2π × 0.125) = 0.7071. The same value, at every n. The 7 kHz tone is an alias of 1 kHz.

falias
The frequency you will see in the recorded samples. It always lies between 0 and fs / 2.
f
The real frequency of the tone at the input.
k
How many whole sample rates to subtract to land closest to zero.
fs
The sample rate. Half of it, fs / 2, is the Nyquist frequency: the highest tone that samples can hold unambiguously.

f = 7,000 Hz, fs = 8,000 Hz → f / fs = 0.875 → k = 1 → |7,000 − 8,000| = 1,000 Hz

Walk the formula along a sweep at fs = 8,000 Hz. A 1 kHz tone shows as 1 kHz. A 3 kHz tone shows as 3 kHz. A 5 kHz tone is above Nyquist (4 kHz) and shows as |5,000 − 8,000| = 3 kHz. A 7 kHz tone shows as 1 kHz. A tone at exactly 8 kHz shows as 0 Hz: every sample lands at the same point of the wave, so the data looks like a constant level. A 9 kHz tone shows as 1 kHz again. The apparent pitch rises to Nyquist, then falls back to zero, like a ball bouncing between two walls. The name for this is folding.

Alias a sine on purpose

The grey wave is the real tone. The dots are the samples taken in 1 ms. The blue wave is the slowest wave that fits the dots. Drag the tone above half the sample rate and watch the blue wave stop following the grey one.

7.0 kHz

Computed exactly with the formula above. Samples are of cos(2πft). At exactly fs / 2 the samples alternate between two values and depend on the phase, so that case is drawn at one fixed phase.

Try the preset button at 8 kHz, then switch to 48 kHz. The same 7 kHz tone is now far below Nyquist, which is 24 kHz, and the samples follow it faithfully.

Why this is a hardware lesson

Aliasing is permanent. After sampling, the 7 kHz tone and the 1 kHz tone have the same numbers. No software, however clever, can separate them. You must remove the high tone before the ADC (Chapter 8) or raise fs. That is why the sample rate is a timer setting and an analog design decision together.

Failure, as symptom, measurement and fix. The symptom: a whistle at a strange pitch in a recording that only appears when a motor driver runs. The measurement: feed the ADC a sine from a generator and sweep it upward while you watch the spectrum of the recording. The peak rises, reaches fs / 2, then turns around and falls. Where it turns around is your Nyquist frequency. The fix: add a low-pass filter ahead of the ADC, or sample faster.

c, predict what a tone will look like after sampling
#include <math.h>
float alias_hz(float f, float fs) {
    float k = roundf(f / fs);       // nearest whole number of sample rates
    return fabsf(f - k * fs);        // always in 0 .. fs/2
}
/* alias_hz(7000, 8000)   = 1000
   alias_hz(11000, 16000) = 5000
   alias_hz(11000, 8000)  = 3000   (11 kHz folds to 3 kHz at 8 kHz) */
An ADC samples at 16 kHz. A switching regulator whistles at 11 kHz at its input. At which frequency does that whistle appear in the data?

Chapter 8

The Filter Before the ADC: Remove What You Cannot Sample

Put a low-pass filter in front of the converter, size it for the tone you fear, and see why oversampling makes the filter cheaper

Your 16 kHz microphone board works well in the lab. Then you place it next to a switching power supply that whistles at 11 kHz. Your recording now has a clear 5 kHz tone in it. You did not hear a 5 kHz tone in the room. You know the answer from Chapter 7: the 11 kHz noise folded to |11 − 16| = 5 kHz.

You cannot remove it in software, because after sampling it looks like real 5 kHz sound. So you must stop it before it reaches the ADC. A low-pass filter passes slow signals and weakens fast ones. When it sits before the ADC to guard against aliasing it is called an anti-alias filter.

The simplest filter: one resistor and one capacitor

Put a resistor R in series with the signal, and a capacitor C from the ADC pin to ground. Slow changes pass because the capacitor has time to follow. Fast changes are shorted to ground by the capacitor. The corner frequency fc = 1 / (2πRC) marks the middle of the change. For R = 1 kΩ and C = 0.1 µF, fc = 1.59 kHz.

The filter weakens a tone of frequency f by the factor 1 / √(1 + (f / fc)2). Far above fc that falls by 20 dB for every tenfold increase in frequency. This is a gentle slope. A second-order filter falls by 40 dB per tenfold, with the factor 1 / √(1 + (f / fc)4) in the Butterworth form.

A(f)
How many decibels the filter takes off a tone of frequency f. Bigger is better for an unwanted tone.
f
The frequency of the tone, in hertz.
fc
The corner frequency of the filter.
2n
Twice the order n. One for the RC filter, two for a second-order filter.

Worked example. Wanted tone: 1 kHz. Pest: 11 kHz. Use the RC filter with fc = 2 kHz. At 1 kHz: A = 10 log10(1 + 0.25) = 0.97 dB, almost no loss. At 11 kHz: A = 10 log10(1 + 5.52) = 14.9 dB. The pest is 14 dB weaker than the wanted tone. That helps, but is it enough?

Filter, then sample

Teal: a wanted 1 kHz tone. Grey: an 11 kHz pest. The bars show what is left after the filter. The purple dashed line is Nyquist. Where the pest lands in the samples is shown by the red-tinted bar once it folds.

2 kHz

Ideal filter responses from the formula above, not a circuit simulation. Both tones start with equal strength. The corner slider is logarithmic from 200 Hz to 20 kHz. The goal of 74 dB is the ideal 12-bit signal-to-noise ratio (6.02 × 12 + 1.76).

At 16 kHz with the RC filter the pest is 14 dB below the wanted tone. A 12-bit ADC can resolve 74 dB. The leftover pest is a big error. Try 2nd order and a lower corner: it improves but cannot get near 74 dB without also hurting the wanted tone. Now switch to 48 kHz. The pest at 11 kHz is below Nyquist, so it does not fold at all. It stays at 11 kHz, where a digital filter can cut it with no loss to the wanted tone.

Oversampling: sample faster than you need

That last result is a standard design trick. Oversample the signal, say at 48 kHz for a 16 kHz product. The Nyquist frequency is now 24 kHz, so the analog filter can be gentle: its corner can sit well above the wanted band and it only has to deal with things above 24 kHz. Then filter and decimate in software, which means keep every third sample after a digital low-pass. Digital filters are sharp, exact and cost no parts.

The price is time and bandwidth. At 48 kHz the ADC runs three times as often. Chapter 6 told you the conversion must fit inside the tick: (84 + 12) cycles = 3.84 µs, against a 20.8 µs tick, still fine. DMA moves three times more samples. A rule of thumb from converter design says that averaging four noisy samples can gain about one bit, if the noise is random and wide enough. Treat it as a hint to test, not a promise.

Failure, as symptom, measurement and fix. The symptom: a tone that moves when you change the sample rate. The measurement: record with the pest source on, change fs from 16 to 14 kHz and watch the tone. A real sound stays put. An alias moves, here from 5 kHz to 3 kHz. The fix: filter ahead of the ADC, and oversample so that the filter can stay gentle.

c, decimate by 4 with a crude box average (a real design uses a longer filter)
/* ADC runs at 64 kHz. We want 16 kHz. in[] holds 12-bit unsigned samples. */
void decimate4(const uint16_t *in, int16_t *out, int n_out) {
    for (int i = 0; i < n_out; i++) {
        uint32_t s = in[4*i] + in[4*i+1] + in[4*i+2] + in[4*i+3];
        out[i] = (int16_t)(((int32_t)(s >> 2) - 2048) << 4);   // remove DC, scale to 16 bit
    }
}

A box average is a weak filter: its notches are narrow and its stopband is poor. The lesson on discrete signals and the microphone lessons (microphone arrays) show better ones.

Why does oversampling at 48 kHz let you use a simpler analog filter than sampling at 16 kHz, for a signal that matters only up to 6 kHz?

Chapter 9

When Two Clocks Almost Agree: Drift and the Buffer That Fills

Turn a rate error of a few hundred parts per million into samples per second, and find out when a buffer between two clocks breaks

Your board records audio on a timer-triggered ADC and sends it to a speaker driver that has its own clock. In the lab you play ten seconds and it sounds perfect. A customer plays a two-hour call and hears a click every minute or so. Nothing is broken. The two clocks are slightly different, and one of them has been gaining on the other the whole time.

What a ppm is

A clock error is quoted in parts per million, or ppm. One ppm means an error of one part in a million. If a clock runs at +160 ppm, it ticks 160 extra times for every million ticks.

You met a real one in Chapter 3. The 48 kHz sample clock built from a 100 MHz timer ran at 48,007.68 Hz: 7.68 Hz fast, which is 160 ppm. The other end of the system runs at a clean 48,000 Hz. The gap is 7.68 samples a second.

Small numbers become large with time. At 160 ppm the clocks drift apart by 160 µs every second. After one hour that is 0.576 s, which equals 27,648 samples. After one day it is 13.8 s.

drift
How many samples per second the faster side gains on the slower side.
fs
The nominal sample rate, 48,000 Hz here.
ppm
The rate error between the two clocks, in parts per million.

48,000 × 160 / 1,000,000 = 7.68 samples per second

The buffer between two clocks

Between a producer and a consumer you place a FIFO, a queue of samples in RAM. The producer pushes at its rate. The consumer pops at its own. If the rates match, the level of the queue stays put. If the producer is faster, the level climbs by 7.68 samples each second. Start the queue half full. A FIFO of 1,024 samples then has 512 samples of room above the middle, and it overflows after 512 / 7.68 = 66.7 seconds. If the producer is slower the queue drains and the consumer runs dry. That underrun is an underrun click or a repeated block of audio. Both ends of the failure are loud.

Note the pitch. A 160 ppm error shifts every tone by 1200 × log2(1.00016) = 0.28 cents, where one cent is a hundredth of a semitone. That is far too small to hear. The buffer fails long before the pitch matters. This is why drift is a system bug rather than an audio-quality bug.

Fill the buffer between two clocks

The line is the FIFO fill over ten minutes. It starts half full. Drag the clock error. Then turn on the fix, which drops or repeats one sample when the level drifts.

+160 ppm

Computed from drift = 48,000 × ppm / 106 samples per second, starting at half full. The fix is modelled as one dropped (or repeated) sample whenever the level moves 16 samples from the middle; real systems also trim the clock or use a rate converter. The ppm values are illustrative except +160, the rounding error of Chapter 3.

At +160 ppm and 1,024 samples the line hits the top at 66.7 s. A bigger buffer only delays the same failure: 4,096 samples last 267 s. Only a fix that acts on the rate lasts forever.

How big can the error be?

Our 160 ppm came from rounding. Other errors come from the oscillator itself. A crystal’s data sheet gives its tolerance in ppm. A chip’s built-in RC oscillator is usually specified in percent instead. One percent is 10,000 ppm. At 48 kHz that is a drift of 480 samples every second, so even a 4,096-sample FIFO that starts half full fails in 2,048 / 480 = 4.3 seconds.

Temperature also moves a crystal, a little, during use. So a number measured once on the bench is not a promise for the field. This is why designs measure the error continuously, through the queue level, rather than trusting a constant.

Three fixes

  1. Share one clock. Let one device be the master and the other follow its clock. In an I2S link the master supplies the bit clock. The error disappears because there is only one clock. (See Digital Audio on the Wire.)
  2. Watch the level, then nudge the rate. The queue fill is a free measurement of the error. Use it to trim a clock or to drop and repeat one sample now and then. The device above does the second. A change of one sample in 48,000 is a step of 0.28 cents and cannot be heard.
  3. Convert the rate. An asynchronous sample-rate converter in software or hardware interpolates between samples to match the consumer’s clock exactly.

Clock error is a wider topic: crystals vary with temperature, and a counter can wrap. The lesson Crystals, RTCs and Drift picks it up. Our job here is to know the number and to design for it.

Failure, as symptom, measurement and fix. The symptom: a click or a glitch at fixed intervals, say every 67 s. The measurement: print the FIFO fill level once a second. It ramps in one direction and the glitch happens when it reaches a limit. The fix: one of the three above, chosen by cost.

c, keep a FIFO centred by dropping or repeating one sample
/* Called once per DMA half-buffer. level = samples waiting, cap = FIFO size. */
int adjust(int level, int cap) {
    int err = level - cap / 2;
    if (err >  16) return -1;     // producer ahead: drop one sample
    if (err < -16) return +1;     // producer behind: repeat one sample
    return 0;
}
A producer runs 100 ppm fast at 48,000 Hz into a 2,048-sample FIFO that starts half full. About how long until it overflows?

Chapter 10

Field Guide: Numbers, Checklist, Core Code and Sources

Keep this page open on your desk the next time a pin, a servo or a sample clock does not do what you wrote

One counter, three jobs. Tick makes a clock. Compare makes PWM. Capture makes a stopwatch. Two integers, PSC and ARR, set the rate, and only their product matters for the rate. The split sets the tick length and the number of steps. When you must sample at exact times, do not ask code to do it. Wire the timer to the ADC, let DMA store the result, and put a filter in front. Then check the two clocks you connect, because a few hundred ppm still breaks a buffer.

The numbers, in one table

QuantityValueWhere it came from
Update rateftimer / ((PSC + 1)(ARR + 1))ST driver header: CK_CNT = fCK_PSC / (PSC + 1); the counter runs 0 to ARR (RM0402 ch. 17)
Timer clock on a Nucleo-F411RE100 MHz (APB1 50 MHz doubled)Rule read in RM0402 (STM32F412); confirm in RM0383 and your clock tree
Servo cycle50 Hz; 1.0, 1.5, 2.0 msOpenMV servo tutorial; nominal, check your servo
Servo setupPSC = 99, ARR = 19999, CCR 1000 to 2000Worked in Chapters 1 and 2
PWM mode 1High while CNT < CCR; duty = CCR / (ARR + 1)ST driver header; RM0402 17.3.9
48 kHz from 100 MHzARR = 2082: 48,007.68 Hz, +160 ppmComputed (Chapter 3)
16 kHz from 100 MHzARR = 6249: exactComputed
Counter wrap16 bit at 1 MHz: 65.536 ms; 32 bit at 100 MHz: 42.95 sComputed
ADC triggerTIM2 TRGO = EXTSEL 0110; TIM2 CC2 = 0011; MMS 010 = updateST LL driver header; ST LL driver header, ADC trigger list (RM0402 table)
Conversion timesampling + 12 ADC cycles (12 bit); 84 + 12 at 25 MHz = 3.84 µsRM0402 ADC chapter; computed
Interrupt entry12 cycles on Cortex-M4, zero wait states: 120 ns at 100 MHz; often moreArm blog on interrupt latency
Jitter limit on SNR20 log10(1 / (2π f σt)); 16 ns allows 74 dB at 2 kHzAnalog Devices MT-007; computed
Alias|f − k fs|, k nearest whole numberStandard sampling theory
Clock driftfs × ppm / 106 samples per second; 160 ppm at 48 kHz: 7.68Computed

The terms, quickly

TermMeaningRegister (TIM, STM32F4)
PrescalerDivides the counter clock by PSC + 1PSC, offset 0x28
Auto-reloadHighest count; wraps and fires the update eventARR, 0x2C
CounterThe value that ticks upCNT, 0x24
Capture/compareOutput compare mark, or input capture latchCCR1, 0x34; CCMR1, 0x18; CCER, 0x20
Update generationForce the buffered PSC and ARR to load nowEGR.UG, 0x14
Trigger outputPublish an internal event to other peripheralsCR2.MMS, 0x04
JitterSample-to-sample spread of the timing errorNone; you measure it

Checklist before you trust a timer

  1. Clock gate. Is the peripheral enable bit set before any other write?
  2. Timer clock. Did you read ftimer from the clock tree, with the APB doubling rule?
  3. The +1s. Are PSC and ARR written as ratio minus one, with a comment?
  4. Load. Did you write UG once so the buffered values apply now?
  5. PWM. Is preload on, the channel enabled in CCER, the pin in alternate function, and CCR clamped?
  6. Capture. Does the longest pulse fit one counter turn? Is an input filter set for a noisy pin?
  7. Sampling. Does the timer start the ADC, with MMS, EXTSEL and EXTEN all set? Does conversion time fit inside the tick?
  8. Aliasing. Is there a filter before the ADC, and is the loudest pest tone below Nyquist or weak enough?
  9. Two clocks. Do you know the ppm between producer and consumer, and what keeps the buffer centred?

The core as code

c, the whole lesson in one start-up function (STM32F411, 16 kHz, PA0)
void sample_clock_start(void) {
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;                 // 1 clock gates first
    RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
    TIM2->PSC = 0;  TIM2->ARR = 6250 - 1;               // 2 100 MHz / 6250 = 16 kHz, exact
    TIM2->CR2 = (2u << TIM_CR2_MMS_Pos);               // 3 update event drives TRGO
    ADC->CCR = (1u << ADC_CCR_ADCPRE_Pos);             // 4 ADCCLK = PCLK2 / 4
    ADC1->SMPR2 = (4u << ADC_SMPR2_SMP0_Pos);            // 5 84 cycles: 3.84 us total
    ADC1->CR2 = ADC_CR2_EXTEN_0 | (6u << ADC_CR2_EXTSEL_Pos)  // 6 TIM2 TRGO, rising edge
                | ADC_CR2_DMA | ADC_CR2_DDS | ADC_CR2_ADON;
    dma_ring_start(adc_buf, 512);                       // 7 DMA2 stream 0, circular
    TIM2->EGR = TIM_EGR_UG;                             // 8 load PSC and ARR
    TIM2->CR1 |= TIM_CR1_CEN;                           // 9 go
}

Keep going

Sources and credit

There are no slides for this session. We built it from primary sources that we opened. Where a fact is for the STM32F411 but the text we read was for a sibling part, we say so.

The takeaway. Do not make code keep time. Let one counter keep it, let the counter start the ADC, and protect the ADC with a filter. Then every sample lands on the tick.

Go back to the instrument at the top and try the timer trigger at full load. Then open Present to explain the chain from tick to buffer in your own words, or Teach to draw it on a whiteboard.

Timers, PWM and Sampling Without Jitter
Back to the lessons · Interrupts and DMA