A chip tells time by counting the ticks of a crystal, and no two crystals tick at the same speed. Two clocks that are each 20 parts per million off drift 144 ms apart in one hour.
Learn how a microcontroller keeps time, how wrong that time gets, and how to write firmware that survives a counter wrapping back to zero.
Drag the two ppm sliders, then pick one minute, one hour or one day. Watch the two clocks pull away from true time and from each other. Then we build, piece by piece, the crystal, the counter and the code underneath.
You need a little C and the idea of a timer (a counter that adds one on every tick of a clock). We build the rest from zero.
Part of the Firmware from Zero to Expertise series. Built from primary sources: ST application note AN4759, the Nordic nRF52840 product specification, vendor 32.768 kHz crystal datasheets, the FAA directive AD 2015-09-07, and the book by Lee and Seshia, Introduction to Embedded Systems. Full list in the Field Guide.
A model: ideal clocks with a constant error each, no temperature change. The arithmetic is exact: offset = error in ppm × 10−6 × seconds elapsed.
Chapter 0
Watch two good clocks disagree about one event, and see why a firmware engineer must know how far.
You clap your hands next to a small wearable. Inside it sit two boards. One board listens through a microphone. The other board feels motion with a motion sensor. Both boards write down when the clap happened.
You hope the two notes say the same time. They do not. Each board counts time with its own crystal. The two crystals tick at slightly different speeds. After a day, the boards disagree about the clap by more than a second. Your audio and your motion data no longer line up.
This lesson explains why that happens, how big the error is, and what firmware must do about it. It also covers a second trap. A counter that holds time is a fixed-size box. When it fills, it wraps back to zero. A program that forgets this works for weeks and then fails on one unlucky day.
A clock on a chip is a counter that adds one on every tick of an oscillator. Read the counter, and you have a time. Two clocks can disagree in two different ways, and we will name them now because the rest of the series uses them.
The offset is how far apart two clocks read at one moment. If board A says 10.000 s and board B says 10.144 s, the offset is 144 ms. The drift is how fast the offset grows. If the offset grows by 144 ms every hour, the drift is 144 ms per hour. Offset is a position. Drift is a speed.
You can fix an offset once, by setting one clock to match the other. You cannot fix drift that way. The offset grows back. That is why a single clock set at the factory is never enough, and why Chapter 9 asks how often two clocks must talk.
A timestamp is a number that a chip attaches to a reading: “this sample was true at tick 1,234,567.” Everything that comes later depends on that promise. A filter that fuses a camera with a motion sensor assumes the two stamps use one timeline. A recording of a brain signal next to a video assumes the same.
The promise is only as good as the clock behind it. A stamp from a clock that is 20 ppm off carries that error into every later step. No clever software downstream can remove an error it cannot see. This is why timekeeping is a firmware problem, and why we study it before we study how to stamp events at the pin (the next lesson, timestamp at the pin) or how to join many chips onto one timeline (syncing many MCUs).
The robot lesson Sensors and Actuators Integration asks “what time is it?” from the robot’s side. It gives the rule: stamp as close to the physics as you can, and never trust the time a message arrived. This lesson goes one level down. It asks what the clock under the stamp is made of.
Here is the wearable made concrete. Both boards were set to the same time at the factory. One crystal runs 20 ppm fast, the other 20 ppm slow. Those are ordinary values for a plain crystal. Drag the hours forward and watch the two stamps of the same clap pull apart. The read-out also counts the gap in samples of 48 kHz audio, the rate of a typical microphone.
Each board wrote the time of the clap on its own clock. The bar between the two stamps is the offset. Drag the hours since the boards were set.
Illustrative: board A runs +20 ppm and board B runs −20 ppm, so they differ by 40 ppm. Offset = 40 × 10−6 × seconds elapsed. The 48,000 samples per second is a common audio rate.
After 12 hours the boards disagree by 1.73 s. That is 82,944 audio samples. The audio engineer sees the clap in one place and the motion engineer sees it 1.73 s earlier. After three days the gap is 10.4 s. Nothing broke. Both crystals are inside their rating. The error is simply what a plain crystal does.
40 ppm × 43,200 s = 40 × 10−6 × 43,200 s = 1.728 s (12 hours)
We build the answer from the bottom. First the crystal and the counter. Then the unit that measures their error, parts per million. Then what moves the error: the part, the temperature and the age. Then the clock tree of a real chip, the real-time clock and its calibration, and the counters that wrap. The last devices turn all of it into a rule for how often two clocks must resync.
This lesson builds on timers, PWM and sampling, where a timer counted clock ticks to make a period. Here we ask how good the ticks themselves are.
Chapter 1
Build a clock from a crystal and a counter, and see why 32,768 is the magic number.
Think of a swing in a park. It swings back and forth at a steady rate, set by the length of its chains. Push it a little on each pass, and it keeps going. Now count the swings. You have a clock. A chip clock works the same way, with a swing that is a thousand times smaller and a hundred thousand times faster.
Every digital clock has two parts. One part makes a steady beat. The other part counts the beats. The beat maker is an oscillator: a circuit that produces a repeating signal. The counter is a register that adds one on every beat. Time is the count times the length of one beat.
The best common beat maker is a crystal: a sliver of quartz cut into a shape, here a tiny tuning fork. Quartz is piezoelectric. That word means two things. If you bend it, it makes a voltage. If you apply a voltage, it bends. So a crystal can be both a spring and a sensor.
Connect the crystal to an amplifier that feeds its own voltage back to it. The crystal bends, makes a voltage, the amplifier boosts it, and the crystal bends again. The loop settles at the one rate where the fork rings most easily. That rate is its natural frequency, and it is set by the size and cut of the quartz. It is very steady, because quartz hardly stretches or ages.
Watch crystals ring at 32.768 kHz, which means 32,768 beats each second. Most other crystals on a microcontroller board ring at several MHz. The tuning-fork shape suits the slow rate. It also needs very little power, so it can run for years on a coin cell.
Why this odd number? Because 32,768 is 215. A binary counter divides by two on every bit. Bit 0 flips on every beat, so it runs at half the crystal rate. Bit 1 flips on every second flip of bit 0, so it runs at a quarter. Each bit halves the rate again. After 15 bits, the rate is 32,768 / 32,768 = 1 beat per second.
32,768 Hz ÷ 215 = 1 Hz (fifteen divide-by-two stages)
A 15-bit divider is cheap and exact. No arithmetic is needed to turn a crystal into a second. That is why nearly every real-time clock in the world uses 32,768 Hz. Try the counter below. Drag the tick count, and watch each bit light up.
Each box is one bit of the counter. The number under a box is how fast that bit flips. Drag the tick count from 0 up to 32,768, or pick a preset.
A model of a ripple divider: the count is exact, the crystal is ideal. Real parts add the errors the next chapters measure. Frequency of bit k = 32,768 / 2k+1 Hz.
At 16,384 ticks, only the top bit is set, and half a second has passed. At 32,767 ticks, every bit is set. One more tick, and all fifteen bits fall to zero. The carry out of the top bit is the 1 Hz pulse. That carry is the tick of the calendar.
On an STM32 the real-time clock (RTC, Chapter 5) has two dividers in a row. A 7-bit asynchronous prescaler divides first, then a 15-bit synchronous prescaler divides again. With the usual values they divide by 128 and then by 256. Check the product: 128 × 256 = 32,768. The result is the 1 Hz tick that drives the calendar. The formula is f1Hz = fRTCCLK / ((PREDIV_A + 1) × (PREDIV_S + 1)). The names PREDIV_A and PREDIV_S come from the ST reference manuals; confirm the field widths in your part’s manual.
The CPU needs a faster clock than one second. Cortex-M cores include SysTick, a 24-bit counter that counts down from a reload value and fires an interrupt at zero. Set the reload to fcpu/1000 − 1, and the interrupt fires every millisecond. For a 168 MHz core, that reload is 167,999. The handler adds one to a variable, and that variable is your millisecond tick count.
c/* 1 kHz tick from SysTick on a 168 MHz Cortex-M (illustrative values) */ static volatile uint32_t g_ms; // the clock: a counter of 1 ms beats void SysTick_Handler(void) { g_ms++; } // runs once per millisecond void tick_init(void) { SysTick->LOAD = 168000000/1000 - 1; // 167999 = 168,000 beats minus one SysTick->VAL = 0; SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; }
Look at what this clock is made of. The count is exact. The beat comes from the CPU clock, which comes from some oscillator. If that oscillator is 20 ppm fast, then every millisecond in g_ms is 20 ppm short. The code cannot tell. The counter faithfully counts a wrong beat. Chapter 4 shows which oscillator feeds which counter.
On real hardware. On an STM32 Nucleo board, route the RTC’s 1 Hz signal to a pin (or toggle a pin in a one-second RTC interrupt). Connect a logic analyser or an oscilloscope and measure the period over 100 cycles. The next chapter shows how to turn what you read into ppm.
Chapter 2
Turn a clock accuracy in ppm into milliseconds lost per hour, per day and per year.
A data sheet says a crystal is “±20 ppm”. A friend says it is “a bit loose”. Another says “that is a second and a half a day”. All three are the same claim. This chapter gives you the one multiplication that turns the data sheet into days and seconds.
Parts per million (ppm) is a fraction: one part in a million, written 10−6. It is like a percent, but a percent is one part in a hundred. So 1 % equals 10,000 ppm. A clock with an error of 1 ppm gains or loses one microsecond in every second.
That one fact is enough to do all the arithmetic. If the error is ε ppm, then in t seconds the clock is wrong by ε × 10−6 × t seconds. The sign matters. A crystal that rings fast makes more ticks per true second, so the counter reads ahead of true time. A crystal that rings slow makes the counter fall behind.
Take ε = 20 ppm. Each time scale is the same multiplication with a different t.
1 minute: 20 × 10−6 × 60 s = 1.2 ms
1 hour: 20 × 10−6 × 3,600 s = 72 ms
1 day: 20 × 10−6 × 86,400 s = 1.728 s
1 year: 20 × 10−6 × 31,557,600 s = 631 s (10.5 minutes, using a 365.25-day year)
A shortcut helps you in the lab. 1 ppm is 3.6 ms per hour, 86.4 ms per day, and 31.6 s per year. Multiply by your ppm. A 500 ppm clock loses 1.8 s per hour and 43.2 s per day. Try your own number below.
The yellow bar is your clock. The grey bars are other ppm values, drawn on the same log scale. Drag the ppm, then pick how long it runs.
Exact arithmetic, not a model: offset = ppm × 10−6 × seconds. A year is 365.25 days. The grey reference values are round numbers for scale, not parts.
Notice what the log scale shows. Going from 1 ppm to 500 ppm multiplies the error by 500, but it only moves the bar a few steps across. The log scale hides how big the gap is. On a linear scale the 500 ppm bar would be 500 times longer.
The offset between two clocks depends on the difference of their errors. Clock A at +20 ppm and clock B at −20 ppm differ by 40 ppm. Clock A at +20 ppm and clock B at +20 ppm do not drift apart at all. They are both wrong, but they are wrong together.
Strictly, the ratio of two rates is (1 + εA)/(1 + εB). For errors of tens of ppm, that equals 1 + (εA − εB) to within a few parts in 1010. So subtraction is exact enough for any firmware use.
Count your oscillator’s ticks over a time you trust, and compare with what you expected. A trusted time can come from a GPS pulse-per-second signal, a lab frequency counter, or a better clock on the bench. Over a window of T seconds, the expected count is fnominal × T.
Worked example. Count a 32,768 Hz oscillator for exactly 32 s. The expected count is 32,768 × 32 = 1,048,576. You count 1,048,597. The difference is 21 ticks. The error is 21 / 1,048,576 = 20.0 ppm fast. The oscillator rings at 32,768 × (1 + 20 × 10−6) = 32,768.66 Hz.
c/* error in ppm from a tick count over a trusted window */ double ppm_error(uint64_t counted, double f_nominal_hz, double window_s) { double expected = f_nominal_hz * window_s; // 32768 * 32 = 1048576 return ((double)counted - expected) / expected * 1e6; // 1048597 gives +20.0 }
A longer window gives a finer answer. One tick out of 1,048,576 is 0.95 ppm, so a 32 s window can only resolve about one ppm. To see 0.1 ppm, count for about 320 s. This trade shows up again in the RTC calibration window of Chapter 5.
On real hardware. Take two boards (two STM32 Nucleo boards work), and toggle one pin per second from each RTC. Capture both pins on one logic analyser for an hour. The distance between matching edges at the end, divided by 3,600 s, is the difference of the two ppm figures.
Chapter 3
Find the three sources of error in a real crystal: its tolerance, the temperature and its age.
You test a wearable on your desk. Its clock drifts by 2 ms an hour, which is fine. You ship it. A customer wears it on a ski slope, and the clock loses a quarter of a second an hour. Same board, same firmware, same crystal. Only the temperature changed.
A real crystal is wrong for three reasons that stack on top of each other. We take them in the order a designer meets them: the part you bought, the temperature it sits in, and the years it spends there.
No two crystals ring at exactly the same frequency. The quartz is cut by a machine, and the cut is never perfect. The frequency tolerance on the data sheet says how far the ring rate can be from the nominal value at room temperature, on the day it was made. Plain 32.768 kHz parts commonly list tolerances in the tens of ppm. For the lessons here we use ±20 ppm as an illustrative figure. Read the line for your part.
The circuit also matters. A crystal rings at a slightly different frequency depending on the small capacitors around it, called the load capacitance. A board with the wrong capacitors shifts every unit the same way. Designers sometimes use this on purpose to trim a design toward zero error.
Quartz changes its stiffness with temperature, so the ring rate changes too. For the tuning-fork cut used in watch crystals, the change has a simple shape: a parabola. The ring rate is highest at one temperature, the turnover temperature. It falls on both sides, slowly near the peak and fast far from it.
Other vendors list almost the same numbers. Geyer, Taitien, Fox and Mercury data sheets give K between −0.03 and −0.04 ppm per °C squared and turnover at 25 ± 5 °C. Use −0.034 as a typical value, not a guarantee. Read the maximum for your part.
Worked example with K = −0.034 and T0 = 25 °C. The sign is always minus: the clock slows on both sides of the peak.
At 45 °C: −0.034 × (45 − 25)2 = −0.034 × 400 = −13.6 ppm, or 49 ms lost each hour
At 0 °C: −0.034 × 625 = −21.3 ppm, or 76.5 ms lost each hour
At −20 °C: −0.034 × 2,025 = −68.9 ppm, or 248 ms lost each hour, 5.95 s each day
At 85 °C: −0.034 × 3,600 = −122.4 ppm, or 441 ms lost each hour, 10.6 s each day
The parabola explains the ski slope. Near 25 °C the error is small and flat. Far from it the error grows with the square of the distance. Drag the temperature in the device and watch the point climb the curve.
The curve is the typical 32.768 kHz tuning-fork error. The marker is your crystal. Turn on the worst-case band to add tolerance and first-year aging on top.
Curve: Δf/f = −0.034 × (T − 25)2 ppm, typical values from the Raltron R38 data sheet. The band adds an illustrative ±20 ppm tolerance and the data sheet’s ±3 ppm first-year aging; it is a sketch, not a limit for any one part.
Now compare two boards. One rides in a pocket at 35 °C. The other sits in a cold car at −10 °C. The pocket board is at −3.4 ppm. The car board is at −0.034 × 1,225 = −41.7 ppm. The difference from temperature alone is 38.3 ppm, or 138 ms each hour. Both crystals are healthy.
A crystal’s rate also creeps over the years, as the mounting settles and stray material moves on the surface. This is aging. The data sheets above give ±3 ppm in the first year for most parts, and a looser ±5 ppm for one of them (Transko). Aging is small next to temperature. But it is the one error that a factory calibration cannot remove, because it happens after the unit ships.
Many chips include a free oscillator built from a resistor and a capacitor. It needs no external part. It also drifts much more. The nRF52840 data sheet lists its low-frequency RC oscillator (LFRC) as 32.768 kHz ±500 ppm. That is 25 times looser than the illustrative ±20 ppm crystal. At 500 ppm a clock errs by 1.8 s each hour and 43.2 s each day.
Nordic adds a calibration task for the LFRC. It briefly runs the high-frequency crystal as a reference, compares the two, and retunes the RC. You pay a few milliseconds of power now and then, and you get a clock that follows temperature. Chapter 4 shows where that sits among the other sources.
Symptom. Logs from field units disagree with the cloud by seconds, but only for units in cold sites. Measurement. Output the RTC’s calibration pin (a 512 Hz signal on STM32 parts) and watch its frequency while you cool the board with freeze spray. Plot ppm against temperature. If you see a downward parabola, the cause is temperature. Fix. Calibrate near the temperature where the product lives, add a temperature sensor and a correction table, or resync often enough that the parabola never has time to matter (Chapter 9).
On real hardware. On an STM32 Nucleo, enable the RTC calibration output and read the 512 Hz pin with a frequency counter. Cool the board gently with freeze spray (a short burst only) or warm it with a hairdryer, and record frequency against a thermometer taped to the crystal. Do not leave the board cold and wet.
Chapter 4
Follow a timestamp counter back to the oscillator that feeds it, and read its error off the source.
You open the data sheet of a microcontroller and find a picture with boxes and arrows, called the clock tree. It looks like wiring for a city. It is the answer to one question: which oscillator makes the ticks that this counter counts?
That question decides your timestamp error. A counter cannot be more accurate than the oscillator behind it. So we follow a counter back to its source, the way you would follow a river to its spring.
A typical microcontroller has up to four oscillators. Two of them are crystals that you add to the board. Two are small RC circuits inside the chip.
The nRF52840 also offers a third low-frequency source, the LFSYNT. It builds 32.768 kHz from the high-frequency clock. It needs no 32 kHz crystal, but the high-frequency clock must stay on, so the chip uses more power. Its accuracy equals the accuracy of that high-frequency clock.
A PLL (phase-locked loop) is a circuit that multiplies a clock. An 8 MHz crystal goes in, and 168 MHz comes out. It multiplies the frequency. It does not change the fractional error. If the 8 MHz crystal is 30 ppm fast, the 168 MHz clock is 30 ppm fast. Dividers behave the same way. So SysTick, the timers and the UART baud clock that hang off the CPU clock all share the error of the crystal at the top of the tree.
This is why the lesson names every counter by its source. The RTC counts the LSE. The millisecond tick of Chapter 1 counts a divided HSE. They are two clocks on one chip, and they drift apart from each other.
A wearable wakes for 10 % of the time and sleeps for 90 %. In sleep it stops the high-speed crystal to save power. The CPU clock stops too. SysTick, which counts the CPU clock, stops counting. The low-speed crystal and the RTC keep running. (Check your part’s manual: in deep modes the clock gating differs, but the idea holds.)
After one hour of true time, the SysTick count has 6 minutes in it and the RTC count has 60 minutes. A timestamp from SysTick is 54 minutes short. This is a bigger error than any ppm figure. It comes from a clock that was off, not a clock that was slow.
Pick the oscillator that feeds your timestamp counter. The highlighted path is the clock tree. Then switch on sleep, where the board stops its fast crystal 90 % of the time.
Error sizes: the RC figure (±500 ppm) is the nRF52840 LFRC specification. The crystal figures (±20 ppm for 32 kHz, ±30 ppm for MHz) are illustrative. The sleep case assumes the CPU clock stops in sleep and the RTC does not; real parts differ by mode.
The tree gives a design rule. Use the oscillator that runs in every power state as the master clock for timestamps. Read the fast counter for fine detail while awake, and tie it back to the master at each wake. Chapter 8 shows how to join a fast and a slow counter into one long timestamp.
c/* nRF52840: run the low-frequency clock from the 32.768 kHz crystal (LFXO). Register names are from the nRF52840 product specification. */ NRF_CLOCK->LFCLKSRC = CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos; NRF_CLOCK->EVENTS_LFCLKSTARTED = 0; NRF_CLOCK->TASKS_LFCLKSTART = 1; while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0) { } // the crystal needs time to start /* If you kept the on-chip RC (LFRC), recalibrate it now and then. The calibration briefly needs the high-frequency crystal as a reference. */ NRF_CLOCK->EVENTS_DONE = 0; NRF_CLOCK->TASKS_CAL = 1; // DONE event fires when it is finished
Symptom. Samples logged in a burst look right. Then the timeline has a hole after every sleep, and the gaps add up to minutes. Measurement. Read the RTC and the millisecond tick together before and after one sleep. If the tick advanced 40 ms while the RTC advanced 1.0 s, the tick stops in sleep. Fix. Stamp with the RTC, or add the sleep duration from the RTC to the tick at every wake.
On real hardware. On an nRF52840 DK, run RTC0 from the LFRC and RTC1 from a TIMER fed by the high-frequency crystal. Toggle two pins once per second from the two and view them on one logic analyser. After a minute, measure the gap. Then start the LFRC calibration task and measure again.
Chapter 5
Measure the error of a real-time clock and cancel almost all of it with the smooth calibration registers.
Your wearable shows the date on its screen. The crystal behind it is 8 ppm fast. After a month, the date is correct but the time is off by 20 s. The customer notices, because the phone beside it says something else. You cannot swap the crystal. What can you do in firmware?
You can make the clock skip a few ticks. If the oscillator is a little fast, delete a few of its beats before the counter sees them. The counter then runs at the true rate. This is what the RTC (real-time clock) does. It is a counter block, fed by the 32.768 kHz crystal, that keeps the date and time, runs through sleep, and often survives a reset on a backup battery.
STM32 RTCs from the families covered by ST application note AN4759 offer smooth digital calibration. The word “smooth” matters. A rough fix would delete all the ticks at once, once per window, and the time would jump. Smooth calibration spreads the deleted ticks evenly across the window.
The window is 32 seconds by default. In 32 s at 32,768 Hz the RTC sees 220 = 1,048,576 pulses. Each deleted pulse is one part in 1,048,576, which is 0.954 ppm. So the step size of the correction is 0.954 ppm.
Two fields set the correction. CALM is a 9-bit number of pulses to mask (delete) in each window, from 0 to 511. CALP is one bit. When it is set, the RTC adds 512 pulses per window. Together they give a net change from −511 to +512 pulses.
The formula is in ST AN4759. At the two limits it gives the range in the data: CALM = 511 and CALP = 0 gives −511 / (1,048,576 + 511) = −487.1 ppm. CALM = 0 and CALP = 1 gives +512 / (1,048,576 − 512) = +488.5 ppm. So the RTC can pull a crystal in by almost 500 ppm in either direction, in steps of 0.954 ppm. One caution from the F4 reference manual: CALP cannot be set when the asynchronous prescaler PREDIV_A is below 3.
You cannot calibrate what you have not measured. STM32 parts can send the RTC clock to a pin. The pin signal is called RTC_OUT_CALIB, and its nominal rate is 512 Hz, which is 32,768 divided by 64. Measure its frequency with a counter, averaged over at least one window, and turn it into ppm.
The ST community article gives a worked case. A board shows about 512.004 Hz. The error is (512.004 − 512) / 512 = 7.8 ppm fast. We want to delete about 7.8 × 1.0486 = 8.2 pulses per window, so CALM = 8 and CALP = 0. The HAL call is shown below.
Residual: (1 + 7.8125 × 10−6) × (1 − 8 / 1,048,584) − 1 = 0.18 ppm (0.66 ms each hour)
The leftover 0.18 ppm is the step rounding: you can delete 8 pulses or 9, not 8.2. Before the correction, the same clock gained 28 ms each hour. After it, 0.66 ms. Try the device with your own crystal error.
Set the crystal error you measured. The top bar is one 32 s window of 1,048,576 pulses, with the deleted or added pulses marked. The bottom bars compare the error before and after.
The CALM and CALP choice and the residual use the formula from ST AN4759 with the default 32 s window; the crystal error is a number you pick, not a measurement. The marks are drawn evenly but fewer than the true count when there are many.
The device also shows the first limit of calibration. Slide to −300 ppm (a slow crystal). The RTC has to add pulses: CALP = 1 and CALM = 512 minus the net. The residual is still tiny. Only past about 488 ppm does the register run out of room.
c/* STM32 HAL: apply smooth calibration (CALP = 0, CALM = 8 deletes 8 pulses per 32 s) */ HAL_RTCEx_SetSmoothCalib(&hrtc, RTC_SMOOTHCALIB_PERIOD_32SEC, RTC_SMOOTHCALIB_PLUSPULSES_RESET, // CALP = 0 0x8); // CALM = 8 /* Pick CALP and CALM from a measured error (ppm, positive = crystal fast). */ void calib_for_ppm(double ppm, int *calp, int *calm) { int net = (int)lround(-ppm * 1048576.0 / 1e6); // pulses to add (+) or delete (-) if (net > 512) net = 512; if (net < -511) net = -511; if (net <= 0) { *calp = 0; *calm = -net; } else { *calp = 1; *calm = 512 - net; } }
Symptom. The clock keeps good time in the lab and drifts in a cold warehouse. Measurement. Repeat the 512 Hz measurement at the field temperature. If the ppm moved by the parabola of Chapter 3, the setting is correct for 25 °C and wrong elsewhere. Fix. Calibration cancels the error now. For a product with a wide temperature range, either apply a new CALM from a temperature table, or resync against a reference (Chapter 9).
Shorter windows (the CALW16 and CALW8 bits) exist too. They settle faster but give a coarser step, because fewer pulses fit in the window. The default 32 s gives the finest step.
On real hardware. On an STM32 Nucleo with a 32.768 kHz crystal fitted, enable the RTC calibration output (512 Hz) on its pin. Read it with a frequency counter, or with an oscilloscope measuring the period over 32 cycles. Compute the ppm with the formula above and call HAL_RTCEx_SetSmoothCalib. Then repeat the measurement. The pin’s new frequency should sit within about 1 ppm of 512 Hz.
Chapter 6
Work out when a counter of a given width and speed returns to zero.
Look at the odometer of a car. It shows six digits. After 999,999 km it shows 000,000 again. The car did not become new. The display ran out of room. Every counter in a chip is such an odometer, and each one has a number of digits it cannot exceed.
A counter that holds N bits can show 2N different values, from 0 to 2N − 1. One more tick, and it returns to 0. This is a wrap (also called an overflow or a rollover). The question for firmware is not whether a counter wraps. It always does. The question is how long that takes.
Work a few cases by hand. A 16-bit timer at 1 MHz wraps in 65,536 / 1,000,000 = 65.5 ms. The SysTick of a Cortex-M is 24 bits wide. On a 168 MHz core it wraps in 16,777,216 / 168,000,000 = 0.0999 s. A 32-bit counter of microseconds wraps in 4,294,967,296 / 1,000,000 = 4,295 s, which is 71.6 minutes. A 32-bit counter of milliseconds wraps in 4,294,967 s, which is 49.7 days.
Nordic publishes its own numbers for the 24-bit RTC in the nRF52840. At 32.768 kHz with no prescaler, one tick is 30.517 µs and the counter wraps every 512 seconds. The product specification lists the longest wrap at 582.542 hours, with a 12-bit prescaler set to its maximum (125 ms per tick). The hardware raises an OVRFLW event when the counter goes from 0xFFFFFF to 0. It also gives a task, TRIGOVRFLW, which sets the counter to 0xFFFFF0 so you can test the wrap in seconds instead of minutes.
The danger is that tests never last long enough. Your bench test runs for a day. A 32-bit millisecond counter first wraps at day 49.7. The code passes every test and fails in the field, once, about seven weeks after the unit ships.
A real case. In 2015 the US FAA issued airworthiness directive AD 2015-09-07 for the Boeing 787. It said a software counter inside the generator control units overflows after 248 days of continuous power. The generators then go into failsafe mode, and the airplane could lose all AC electrical power. The interim fix was to cut power at intervals not longer than 120 days. A later directive in 2018 required new software. The directive does not state the counter width. Our own arithmetic shows that a signed 32-bit count of hundredths of a second reaches 231 at 248.55 days, which matches. Treat that match as a clue and not as a fact about that unit.
C gives the two kinds very different rules. An unsigned counter wraps in a defined way: 0xFFFFFFFF + 1 is 0. A signed counter that passes its largest value has no defined result in C. The compiler may assume it never happens and delete your checks. Use unsigned types for time counters, and let the wrap happen on purpose.
The device below turns the formula into a picture. Choose a width and a rate. A bar on a log axis shows the wrap time, next to a bench test of one day and a product life of ten years.
Pick the counter width, then the tick rate. The yellow marker is the wrap time. Landmarks show a one-day bench test and a ten-year product life.
Exact arithmetic: 2N / f. The 32.768 kHz, 24-bit case matches the Nordic nRF52840 value of 512 s. A year is 365.25 days.
Look at the 32-bit, 168 MHz case: it wraps every 25.6 s. A counter that fast cannot hold the time of a whole session. It is a stopwatch, good for short intervals, not a clock. The 64-bit rows never wrap in a product life, which is why Chapter 8 builds one from smaller pieces.
Symptom. A device hangs or sends an odd timestamp once, after weeks of uptime, and a reboot clears it. Measurement. Compute 2N / f for every counter in the code. Any value shorter than the product life is a suspect. Then force the counter near its end (start it at 0xFFFFFFF0, or fire TRIGOVRFLW on the nRF52840) and run the code. Fix. Use unsigned arithmetic for differences (Chapter 7), or widen the counter (Chapter 8).
On real hardware. On an nRF52840 DK, trigger the RTC overflow task, count the OVRFLW events over a few minutes and check that the interval equals 512 s with a prescaler of 0. On an STM32 Nucleo, start a 32-bit timer from 0xFFFFFF00 and watch your tick function across the wrap with a debugger.
Chapter 7
Break a timeout with a wrapped counter, then fix it with one line of unsigned subtraction.
You write a timeout. Send the request, wait up to 100 ms for the reply, and give up if none comes. The code is two lines and it passes every test. Then, once in a long while, a request fails at once with “timeout”, before it left the chip. Nothing is wrong with the network. The counter wrapped in the middle of the wait.
cuint32_t deadline = g_ms + 100; // wait up to 100 ms while (!reply_ready()) { if (g_ms >= deadline) return ERR_TIMEOUT; // BUG near the wrap }
Take g_ms = 4,294,967,280, which is 16 ms before the 32-bit counter wraps. The deadline is 4,294,967,280 + 100 = 4,294,967,380. That number does not fit in 32 bits. The sum wraps to 4,294,967,380 − 4,294,967,296 = 84. Now the test reads 4294967280 >= 84, which is true. The code times out at once, 100 ms early.
The reverse bug is rarer and worse. Suppose the deadline fits but g_ms later wraps past it. For a short time after the deadline the test is true. After the wrap g_ms is small again and the test reads false. A timeout that fired has now un-fired. Code that checks only once per loop may miss it entirely.
Do not ask “is now past the deadline?” as two points on a line. Ask “how many ticks since I started?” and compare that with the timeout. Subtract the start from now. In C, unsigned subtraction wraps the same way as unsigned addition. So the difference is correct even when now has wrapped and start has not.
Worked example. The start was 4,294,967,280. Now, 36 ms later, the counter has wrapped and reads 20. Compute 20 − 4294967280 in 32-bit unsigned arithmetic:
20 − 4,294,967,280 = −4,294,967,260, and −4,294,967,260 + 4,294,967,296 = 36
The answer is 36 ticks, which is the true elapsed time. The wrap cancelled itself. This holds because the arithmetic is modular: every result is taken modulo 232, like hours on a clock face where 2 o’clock minus 11 o’clock is 3 hours.
c/* Safe pattern 1: store the start, compare the elapsed time. */ uint32_t start = g_ms; while (!reply_ready()) { if ((uint32_t)(g_ms - start) >= 100) return ERR_TIMEOUT; // works across the wrap } /* Safe pattern 2: keep a deadline, compare the signed difference. */ uint32_t deadline = g_ms + 100; if ((int32_t)(g_ms - deadline) >= 0) return ERR_TIMEOUT; // works if timeouts < 2^31 ticks
The signed form deserves one more look. g_ms - deadline is an unsigned difference. If now is just past the deadline, the difference is a small positive number. If now is still before the deadline, the difference wraps to a huge unsigned number, and the cast to int32_t turns it into a small negative one. The sign tells before or after. It stays correct as long as the two times are less than 231 ticks apart: 24.9 days at 1 kHz. (The cast of an out-of-range value to a signed type is implementation-defined in C, and every common embedded compiler uses the two’s-complement result. Pattern 1 avoids the question.)
The timer starts a few milliseconds before the 32-bit counter wraps. Each strip shows, for every moment after the start, whether that test says the time is up. Green is right. Red is wrong. Drag the start closer to the wrap.
Exact 32-bit arithmetic run in your browser: a 1 kHz counter, start = 232 minus the slider value. The three tests are the buggy compare, the signed-difference compare and the elapsed-time compare from the code above.
Slide the start to 1 ms before the wrap. The buggy test fires on the very first tick, goes quiet on the second, and fires again at the true deadline. Slide it to 300 ms and the deadline never meets the wrap inside the window, so the bug seems to vanish. That is why it is hard to find: it only shows when the start sits within one timeout of the wrap.
First, the subtraction trick measures an interval up to 232 ticks (231 for the signed form). A longer wait is ambiguous: if the counter went round once while you slept, the difference looks the same as if no time had passed. Check the counter more often than its wrap period, or widen it (Chapter 8). Second, the trick needs both values in the same unsigned type and width. Mixing a 16-bit hardware timer with a 32-bit variable breaks the cancellation.
On real hardware. You do not need a board for the first test. Compile the compare on your host, set the start to 0xFFFFFFF0 and run it. On an nRF52840 DK, fire the RTC TRIGOVRFLW task (it sets the counter to 0xFFFFF0) and watch your timeout code on the real peripheral. The same idea applies on an STM32: write the timer register directly to a value near its maximum.
Chapter 8
Extend a 24-bit hardware counter to 64 bits, and keep a late interrupt from costing you 512 seconds.
The always-on RTC of an nRF52840 is a good clock for a wearable. It runs from a 32.768 kHz source, uses very little current, and survives sleep. But it is only 24 bits wide. It wraps every 512 seconds. You want a stamp that stays unique for days. How do you make a long number from a short counter?
The idea is the same as an odometer with a trip counter next to it. Keep a second variable, ovf, that counts how many times the hardware counter has wrapped. Glue the two together: the wrap count forms the high bits and the hardware counter forms the low 24 bits.
ticks = ovf × 224 + counter, seconds = ticks / 32,768
The hardware helps. When the counter goes from 0xFFFFFF to 0, the RTC raises an OVRFLW event. You enable that event, take an interrupt, and add one to ovf. Make ovf a 64-bit or at least a 32-bit variable. Then your extended counter has 24 + 32 = 56 bits. At 32.768 kHz that lasts about 70 thousand years.
Worked example. At true time 512.1 s the tick count is 512.1 × 32,768 = 16,780,493. One wrap has happened (16,777,216 ticks). So ovf = 1 and the hardware counter holds 16,780,493 − 16,777,216 = 3,277. Glue: 1 × 16,777,216 + 3,277 = 16,780,493 ticks, which is 512.1 s. It works, as long as ovf is right.
The wrap lands between your two reads. To get a stamp you read ovf and then read the counter. They are two separate reads. Suppose ovf is 0, the wrap happens, and then you read the counter. You now hold ovf = 0 with a counter near 0. The stamp says 0.1 s, but the truth is 512.1 s. The error is exactly 224 ticks, or 512 s. Reading in the other order gives an error of +512 s.
The interrupt is late. The hardware event fired, but your overflow handler has not run yet. Maybe interrupts were masked for 200 ms by a flash write, or a higher-priority handler was busy. In that gap ovf is stale. Every stamp in the gap is 512 s short. This one is easy to miss, because a short test never masks interrupts for that long.
Both bugs give the same size of error: one full wrap, 512 s. If your logs show a stamp that jumps back by exactly 512.0 s, this is the cause.
The repair has two parts. First, read ovf twice, before and after the counter, and retry if they differ. That catches a wrap and its handler landing between the reads. Second, look at the hardware event flag. If the event is set, the wrap happened but the handler has not counted it. If the counter you read is small, the wrap came before your read, so add one. If the counter is large, you read before the wrap, so do not.
c/* 24-bit RTC extended to 64 bits (sketch; register names from the nRF52840 specification). Setup: enable the OVRFLW event and its interrupt first; it is off by default. */ static volatile uint32_t g_ovf; // number of wraps so far void RTC0_IRQHandler(void) { if (NRF_RTC0->EVENTS_OVRFLW) { NRF_RTC0->EVENTS_OVRFLW = 0; g_ovf++; } } uint64_t rtc_ticks(void) { uint32_t hi, lo; do { hi = g_ovf; lo = NRF_RTC0->COUNTER; // 24 bits } while (hi != g_ovf); // a wrap and its handler fell between the reads: retry if (NRF_RTC0->EVENTS_OVRFLW && lo < 0x800000) { hi++; // wrapped, handler has not run yet } return ((uint64_t)hi << 24) | lo; }
The device below runs both readers on a virtual RTC. Choose a moment, a hazard, and a reader. The chips jump to the dangerous moments.
The timeline shows true time and the 512 s wrap lines. Pick a hazard, a reader, and a moment. Use the chips to land just after a wrap.
A model of the nRF52840 RTC counting at 32.768 kHz with prescaler 0 (24-bit, wraps every 512 s). “Wrap between reads” applies within 2 ms of a wrap; “Interrupt is late” assumes the overflow handler runs 300 ms after the wrap. Both numbers are illustrative.
Try the chip “Wrap + 1 ms” with the hazard “Wrap between reads” and the naive reader. The stamp is 512 s too low. Switch to the careful reader and the error is zero. Then try the late interrupt at “Wrap + 100 ms”. The careful reader works there only because it checks the event flag.
Symptom. A single sample in a recording has a time 512.0 s earlier than its neighbours, once every few hours. Measurement. Plot the difference between consecutive stamps. A spike of exactly −512.000 s (or +512 s) is a wrap-glue error. Check whether it appears within a few milliseconds of a multiple of 512 s. Fix. Use the careful read, keep interrupt-off sections short, and in the logger drop or repair any stamp that goes backwards.
On real hardware. On an nRF52840 DK, configure RTC0 with prescaler 0, call the TRIGOVRFLW task to jump the counter near the end, and log the extended stamp every 10 ms for a minute. Add a deliberate 300 ms interrupt-off loop right after a wrap and run the log again. The naive reader should show the 512 s step. The careful one should not.
Chapter 9
Turn a ppm gap and an error budget into the longest time two clocks can go without talking.
You build the wearable with two boards. The audio board and the motion board must agree on the time of every event to within 1 ms. The boards cannot share a crystal. You cannot make the crystals perfect. So the boards must talk to each other now and then and correct their clocks. How often?
Every correction costs something. It uses radio time or a wire, it uses energy, and it takes a little CPU. You want to correct as rarely as the error budget allows. This chapter turns that wish into one formula.
Right after a sync, the two clocks agree up to the error of the sync itself. Call that error e0. Then the clocks drift apart at the ppm gap d that you met in Chapter 2. After T seconds the offset has grown by d × 10−6 × T. At the next sync the offset drops back to e0. The picture is a sawtooth: a ramp up, a drop, a ramp up again.
Worked example. The gap is 40 ppm (Chapter 0’s +20 and −20). The budget is 1 ms. Each sync is perfect, so e0 = 0.
Tmax = 0.001 s / (40 × 10−6) = 25 s (3,456 syncs per day)
Now give each sync an error of 100 µs. The sync eats part of the budget before the drift starts: Tmax = (1,000 µs − 100 µs) / 40 ppm = 22.5 s. If the sync error is as large as the budget, no period works. You need a better sync, not a faster one.
The same boards with a 100 µs budget need a sync every 2.5 s. The same boards with a 10 ms budget need one every 250 s. The budget moves the period by a factor of ten for each step. Drag the three knobs in the device to feel it.
The saw is the offset between two clocks across four resync periods. The dashed line is your budget. Red marks the part of the saw above it. Set the gap, the budget and the period.
A model with a constant ppm gap and a fixed sync error. Real gaps wander with temperature (Chapter 3), so treat Tmax as a starting point and measure. The resync period slider is logarithmic, from 1 s to 3,600 s.
A common first move is to calibrate. Chapter 5 shows an RTC pulled to within about 1 ppm. If two calibrated boards differ by 2 ppm and each sync is perfect, a 1 ms budget allows a period of 500 s, twenty times longer than 25 s. Calibration and resync work together: one shrinks d, the other resets the offset.
There is a smarter option. After two syncs you can compute how fast the offset grew. That is the gap d itself. If you then correct for d in software, the offset grows only by the part you got wrong. Suppose you estimate the gap to within 2 ppm. Now the saw grows at 2 ppm, not 40. The period for a 1 ms budget goes from 25 s to 500 s.
This is the idea behind the next lessons. Timestamp at the pin shrinks e0 by stamping in hardware. Syncing many MCUs estimates offset and skew with a least-squares fit or a Kalman filter (see the Kalman filter lesson). Prove the sync checks the result in recorded data.
c/* The budget formula, and a drift-corrected conversion (offset and skew come from your syncs). */ double max_resync_s(double budget_s, double sync_err_s, double gap_ppm) { if (sync_err_s >= budget_s) return 0; // the sync alone breaks the budget return (budget_s - sync_err_s) / (gap_ppm * 1e-6); // 0.001 / 40e-6 = 25 s } /* local ticks -> reference time, using the last sync (t0_ref at tick0) and a skew estimate. */ double to_ref(uint32_t tick, uint32_t tick0, double t0_ref, double hz, double skew_ppm) { double local_s = (double)(uint32_t)(tick - tick0) / hz; // wrap-safe elapsed (Chapter 7) return t0_ref + local_s * (1.0 - skew_ppm * 1e-6); }
Symptom. Audio and motion line up for the first minute, then drift apart in steady steps, and the gap is largest just before a resync message. Measurement. Plot the offset against time since the last sync. A straight ramp whose slope is the gap in ppm confirms drift. A ramp that changes slope with the room temperature confirms Chapter 3. Fix. Resync at least every Tmax, calibrate to shrink the gap, and estimate the slope so that you correct what you can predict.
On real hardware. Take two STM32 Nucleo boards (or one nRF52840 DK and one Nucleo). Send a one-byte sync pulse from board A to board B over a wire, and have B log its tick count at each pulse edge. Plot B’s tick difference minus the expected count against time. The slope is the ppm gap. Change the sync period and compare the saw with the device above.
Chapter 10
Keep the numbers, the checklist, the core code and the sources on one page.
You can now follow a timestamp down to the crystal behind it, say how many milliseconds it loses in an hour, cancel most of that error in an RTC, and write code that survives a counter wrapping. This page keeps what you need at the bench.
A chip keeps time by counting the ticks of an oscillator. The oscillator is wrong by some ppm, and every ppm is a microsecond per second. A plain 32.768 kHz crystal is wrong by tens of ppm, and by more as the temperature leaves 25 °C, following a parabola. An on-chip RC oscillator is wrong by hundreds. Every counter inherits the error of the oscillator behind it, and a counter that stops in sleep adds an error of its own. An RTC can cancel its crystal error to about 1 ppm by deleting or adding pulses in a 32 s window. Every counter wraps after 2N / f seconds. Compare elapsed ticks with unsigned subtraction, extend short counters carefully, and resync two clocks at least every (B − e0) / d seconds.
| What | Number | Why it matters |
|---|---|---|
| 1 ppm | 1 µs per second; 3.6 ms per hour; 86.4 ms per day; 31.6 s per year | The one conversion for all drift arithmetic |
| 20 ppm (illustrative) | 72 ms per hour; 1.728 s per day | A plain crystal drifts visibly in a day |
| Two clocks at +20 and −20 ppm | 144 ms apart after 1 hour; 1.73 s after 12 hours | Offsets add; the gap is the ppm difference |
| 32.768 kHz tuning-fork crystal, temperature | K = −0.034 ± 0.006 ppm/°C²; turnover 25 ± 5 °C (Raltron R38) | Slow on both sides of the peak; −13.6 ppm at 45 °C, −68.9 ppm at −20 °C |
| Crystal aging | ±3 ppm in year one (R38 and others; one part lists ±5) | Cannot be calibrated out at the factory |
| nRF52840 LFRC | 32.768 kHz ±500 ppm | 1.8 s per hour; recalibrate with the CAL task |
| 32,768 Hz | 215; 128 × 256 = 32,768 in the STM32 RTC prescalers | Fifteen halvings give 1 Hz exactly |
| STM32 RTC smooth calibration | 32 s window of 220 pulses; 0.954 ppm step; −487.1 to +488.5 ppm | Cancels crystal error to about 1 ppm (AN4759) |
| RTC_OUT_CALIB | 512 Hz nominal | The pin you measure to find the ppm |
| Wrap times | 16-bit at 1 MHz: 65.5 ms; 24-bit SysTick at 168 MHz: 99.9 ms; 32-bit at 1 MHz: 71.6 min; 32-bit at 1 kHz: 49.7 days | 2N / f decides which counters need care |
| nRF52840 RTC | 24 bits, wraps every 512 s at prescaler 0; up to 582.542 h at 4095 | Extend it in software |
| Boeing 787 generator control units | counter overflow after 248 days; interim power cycle every 120 days at most | A wrap can ground a fleet (FAA AD 2015-09-07) |
| Resync period | Tmax = (B − e0) / d; 25 s at 40 ppm and 1 ms | Sets the cost of keeping boards in step |
These are the five small routines of the lesson in one place. They are sketches: the register names for the nRF52840 and STM32 come from the vendor documents listed below.
c/* 1. ppm from a count over a trusted window (Chapter 2) */ double ppm_error(uint64_t counted, double f_hz, double window_s) { double exp = f_hz * window_s; return ((double)counted - exp) / exp * 1e6; } /* 2. crystal ppm at a temperature (Chapter 3): K = -0.034, turnover 25 C (typical values) */ double xtal_ppm(double temp_c) { return -0.034 * (temp_c - 25.0) * (temp_c - 25.0); } /* 3. wrap-safe timeout (Chapter 7) */ bool expired(uint32_t now, uint32_t start, uint32_t timeout) { return (uint32_t)(now - start) >= timeout; } /* 4. 24-bit RTC to 64-bit ticks (Chapter 8): see rtc_ticks() with the retry and the OVRFLW flag */ /* 5. longest safe resync period (Chapter 9) */ double max_resync_s(double b, double e0, double gap_ppm) { return b > e0 ? (b - e0) / (gap_ppm * 1e-6) : 0; }
This lesson builds on timers, PWM and sampling. The next three finish the time-sync story: stamping at the pin, syncing many MCUs and proving the sync offline. The planned network-time lessons on PTP and gPTP (not built yet) continue for Ethernet-class systems.
No course slides sit behind this lesson. It is built from primary documents we opened ourselves.
HAL_RTCEx_SetSmoothCalib).What is a model here. All devices are in-page models. The ppm arithmetic, the temperature parabola with the vendor constants, the RTC calibration formula, the wrap times and the wrap-safe compares are exact. The crystal tolerance (±20 ppm), the MHz crystal (±30 ppm), the sleep fraction and the sync errors are illustrative. We did not verify the accuracy of STM32 internal RC oscillators, so none is quoted. The Boeing counter width is our arithmetic, not a statement of the directive.
Now press Present or Teach and explain, from memory, why two good clocks disagree after an hour, how an RTC cancels its own error, and what goes wrong when a counter wraps. Then go back to the two clocks at the top, set both clocks to the same ppm, and explain why the gap stays at zero even though both are still wrong.