Skip to main content

CRS MCAL Module

Supported STM32 families: H5 · H7
Not supported: F4, F7, G4, L4, U3, U5

This module provides an abstraction layer for the clock recovery system (CRS) of STM32 MCUs: the automatic trimming of the 48 MHz internal oscillator (HSI48) against a reference - the start-of-frame packets of the USB, the 32.768 kHz LSE or a signal on a pin - so that the oscillator is accurate enough for a crystal-less USB and for other interfaces that need a precise 48 MHz without an external crystal. It offers the selection and the scaling of the synchronization source, the automatic and the manual trimming, the error limit, the status and the interrupts. It is a low-level MCAL module: it owns the CRS hardware, the application and the other modules never touch the registers.

The public interface (Crs_Port.h, Crs_Types.h) is identical for all supported families. The implementation for a family lives in its own branch (Dev/<Family> for development, Releases/<Family> for the released versions), so a module or an application written against the interface does not change when the MCU family changes.

This README is the landing page and the specification of the interface (master). The family branches contain their own README with everything that is specific to the family: the instances of the device, their settings and the status of the implementation.

Status: design. No implementation exists yet, the interface below is a proposal. Stories and branches follow.


Intent and purpose​

  • The HSI48 is a free-running RC oscillator: after the factory calibration it is accurate to a few percent, which is not enough for the USB full-speed (0.25 %) and is marginal for other protocols. The CRS compares the oscillator with a reference, counts the frequency error over every reference period and trims the oscillator by itself, without the CPU, until the error is inside the limit. A USB device then needs no crystal at all.
  • The user describes what the clock is and what the reference is - "48 MHz, synchronized to the USB frame at 1 kHz" - and the module calculates the reload value of the counter, the frequency error limit and the prescaler, selects the synchronization source, starts the automatic trimming and reports when the synchronization is reached.
  • The status matters: a device that starts the USB communication before the oscillator is trimmed fails to enumerate. The module gives a synchronized state (CRS_SYNC_OK), the warning (the error is close to the limit) and the error (the trim reached its limit or the reference is missing) and tells the direction of the error.
  • The module hides the differences between the families: the width of the trim value, the synchronization sources, the oscillator that is trimmed (HSI48) and the interrupt line differ, the interface stays the same.

What the module is not: it does not enable the HSI48 itself (the RCC module starts the oscillator when a peripheral selects it) and it does not handle the USB - the Usb module asks for the synchronization when it starts in the crystal-less mode.


Concept​

The CRS has a 16-bit down counter that is reloaded by every synchronization event and a capture of the counter value at the event; the difference from the expected value is the frequency error and its sign is the direction. The module works with:

ItemMeaning
Target frequencyThe frequency of the trimmed oscillator in Hz (48 MHz).
Synchronization source (crs_SyncSource_t)CRS_SYNC_SRC_USB_SOF (the start-of-frame of the USB, 1 kHz), CRS_SYNC_SRC_LSE (32.768 kHz), CRS_SYNC_SRC_PIN (an external signal on the CRS_SYNC pin) - only the sources of the device.
Synchronization frequencyThe frequency of the reference in Hz (after the prescaler); the module calculates the reload value target / sync - 1 and rejects a combination that does not fit the 16-bit counter.
Prescaler and polarityThe division of a fast external reference (1, 2, 4 ... 128) and the active edge of the pin.
Error limitThe frequency error in ppm that is still considered synchronized (derived from the target and the oscillator step).
Trimming modeAutomatic (the hardware adjusts the trim after every event) or manual (the application writes the trim, for a fast start from a known value).

Rules:

  1. Crs_Init configures the source, the frequencies and the limit and leaves the trimming stopped; Crs_Set_AutoTrimActive starts it. The module checks that the oscillator is running (an error otherwise - the RCC module starts it).
  2. The configuration is changed only while the automatic trimming is stopped.
  3. Crs_Get_SyncState returns CRS_SYNC_OFF, CRS_SYNC_TRIMMING (the error is outside the limit, the trim is moving), CRS_SYNC_OK, CRS_SYNC_WARNING (the error is above half of the limit), CRS_SYNC_ERROR (the trim is at its limit, or the reference does not arrive); Crs_Get_FrequencyError returns the last error and its direction.
  4. Crs_Set_Trimming writes a manual trim (for example the value stored from the last run) and Crs_Get_Trimming reads the current one, so an application can start from a known trim and reach the synchronization immediately.
  5. Crs_Set_SoftwareSync generates one synchronization event by the software (a test or a one-shot calibration).
  6. The callbacks (expected synchronization, synchronization OK, warning, error) are called from the interrupt; the flags are cleared by the module.

Supported families​

Every family gets its own story, its own tasks and its own branches Dev/<Family> and Releases/<Family> cut from this master.

FamilyBranchClock recoveryStatus
STM32H5Dev/STM32H5CRS of the HSI48, 6-bit trim, sources USB SOF / LSE / CRS_SYNC pin, TrustZone aliasesplanned (first)
STM32U5Dev/STM32U5CRSplanned
STM32G4, STM32L4Dev/STM32G4, Dev/STM32L4CRS on the lines with the HSI48planned
STM32H7Dev/STM32H7CRS on the lines with the HSI48planned
STM32U3Dev/STM32U3device dependentplanned
STM32F4, STM32F7Dev/STM32F4, Dev/STM32F7no CRS on the device - the module is a stub that returns CRS_REQUEST_ERRORplanned

A function without a meaning in a family stays in the interface, returns CRS_REQUEST_ERROR and suppresses the unused parameters (for example a synchronization source the device does not have, the manual trim on a family without it).


Public interface in short (proposal)​

GroupFunctions
Module managementCrs_Get_ModuleVersion, Crs_Init, Crs_Deinit, Crs_Task, Crs_Get_DefaultConfig
ControlCrs_Set_AutoTrimActive, Crs_Set_AutoTrimInactive, Crs_Set_Trimming, Crs_Get_Trimming, Crs_Set_SoftwareSync
StateCrs_Get_SyncState, Crs_Get_FrequencyError
InterruptsCrs_Set_IrqPriority / Get, the callbacks are a part of the configuration
PinsCrs_InitSyncGpio
crs_ModuleVersion_t Crs_Get_ModuleVersion ( void );

crs_RequestState_t Crs_Init ( const crs_Config_t * const crsConfig );
crs_RequestState_t Crs_Deinit ( void );
void Crs_Task ( void );
crs_RequestState_t Crs_Get_DefaultConfig ( crs_Config_t * const crsConfig );

crs_RequestState_t Crs_Set_AutoTrimActive ( void );
crs_RequestState_t Crs_Set_AutoTrimInactive ( void );
crs_RequestState_t Crs_Set_Trimming ( crs_Trimming_t trimming );
crs_RequestState_t Crs_Get_Trimming ( crs_Trimming_t * const trimming );
crs_RequestState_t Crs_Set_SoftwareSync ( void );

crs_RequestState_t Crs_Get_SyncState ( crs_SyncState_t * const syncState );
crs_RequestState_t Crs_Get_FrequencyError ( crs_FreqError_t * const frequencyError );

Every function returns CRS_REQUEST_OK / CRS_REQUEST_ERROR and checks its parameters and the state of the module before it touches a register.

TypeMeaning
crs_Config_tSynchronization source, synchronization frequency, target frequency, prescaler, polarity, the start trim, callbacks, interrupt priority
crs_SyncState_tCRS_SYNC_OFF, CRS_SYNC_TRIMMING, CRS_SYNC_OK, CRS_SYNC_WARNING, CRS_SYNC_ERROR
crs_FreqError_tThe error in counter ticks and the direction (CRS_ERROR_DIR_UP / DOWN)
crs_Trimming_tThe trim value of the oscillator (the width of the family)

Usage​

Crystal-less USB: HSI48 synchronized to the USB frame​

#include "Crs_Port.h"

crs_Config_t crsConfig;
crs_SyncState_t syncState = CRS_SYNC_OFF;

(void)Crs_Get_DefaultConfig( &crsConfig );

crsConfig.SyncSource = CRS_SYNC_SRC_USB_SOF;
crsConfig.SyncFrequency = 1000u; /* one frame per millisecond */
crsConfig.TargetFrequency = 48000000u;

(void)Crs_Init( &crsConfig );
(void)Crs_Set_AutoTrimActive();

/* the Usb module connects after: */
for( uint32_t tryIdx = 0u; ( CRS_SYNC_OK != syncState ) && ( 1000u > tryIdx ); tryIdx++ )
{
(void)Crs_Get_SyncState( &syncState );
}

Calibration against the LSE and a stored trim​

crsConfig.SyncSource = CRS_SYNC_SRC_LSE;
crsConfig.SyncFrequency = 32768u;
crsConfig.StartTrimming = storedTrimming; /* the value read by Crs_Get_Trimming at the last run */
(void)Crs_Init( &crsConfig );
(void)Crs_Set_AutoTrimActive();

Behaviour and limits​

  • USB frame. The USB source works only while the host sends the frames (a connected, not suspended bus); in the suspend the synchronization is lost and CRS_SYNC_WARNING or CRS_SYNC_ERROR appears, the trim keeps the last value.
  • Range. The trim range covers the oscillator spread; a value at the end of the range (CRS_SYNC_ERROR) means the reference does not match the target (a wrong frequency in the configuration, a missing signal).
  • Counter range. target / sync must fit the 16-bit reload, so a 48 MHz target needs a synchronization of at least about 732 Hz; the module rejects the rest (a faster reference is divided by the prescaler of the source).
  • Time to lock. The automatic trimming needs a number of synchronization events (milliseconds with the USB frame); the stored trim shortens it.
  • Not part of the first version: the trimming of the other oscillators (MSI with the LSE on the families that have the hardware PLL mode is a feature of the RCC module), the history of the trim for the temperature drift, the combination with the SOF interrupt of the Usb module.

Dependencies​

  • Rcc - peripheral clock, reset, the HSI48 oscillator (checks and requests it)
  • Nvic - interrupt
  • Gpio - the CRS_SYNC pin
  • Usb - the consumer of the synchronized clock (the USB source of the frames is a hardware signal)
  • RAL (Register Abstraction Layer) - used internally to access the registers

All mandatory RCC, NVIC and GPIO configurations are handled internally.


Testing​

  • Unit tests (host, Unity + CMock + RegMem): the reload value and the error limit calculation for the supported source / frequency combinations and the rejected ones, the state machine of the synchronization (trimming, OK, warning, error), the rules of the rejected changes while the trimming runs, the manual trim, the callbacks.
  • Integration tests (target, probe-rs): the HSI48 trimmed against the LSE measured by a timer, the lock time, the error state with the missing reference, the USB enumeration without a crystal.

Interface conventions​

The module follows the common rules of the MCAL layer, so that it behaves like the other modules:

  • Lists instead of free members. Everything that the hardware restricts (the pins, the kernel clock sources, the DMA channels, the triggers and the other selectable sources) is a typedef enum list with exactly the items that are valid for the device line; a pin is an item CRS_<SIGNAL>_PIN_<INSTANCE>_P<port><pin> and there is an *_UNUSED item. A choice that is not in the list cannot be written.
  • Own peripheral only. The module calls only the registers / LL functions of its own peripheral. The clocks, the interrupts, the pins, the DMA and the EXTI lines go through the API of the Rcc, Nvic, Gpio, Gpdma and Exti modules; a missing function is added to that module, it is not bypassed.
  • Init verifies itself. Crs_Init checks the result at the end; when it is not as required, the module is deinitialized and an error is returned. The waiting for the hardware is a loop on the register state with a timeout, never a blind delay.
  • Transfer modes. Where the module moves data, the POLL (served by Crs_Task), ISR and DMA modes have the same configuration structure, the same request and the same callbacks (error, half transfer, transfer complete).
  • Flags and states are enums of the module (crs_FunctionState_t, crs_FlagState_t), the limits and the constants are named, there are no magic numbers in the interface.
  • Unsupported functions stay. A function without a meaning in a family keeps its signature, suppresses the unused parameters and returns CRS_REQUEST_ERROR.
  • Documentation. Every function and type has a Doxygen description, the main header has the \defgroup.

Repository layout and branches​

The master holds this README and the license. The family branches (Dev/<Family>, Releases/<Family>) hold:

PathContent
README.mdREADME of the family: the instances of the device, specifics, errata, status
Crs_Port.h, Crs_Types.hPublic interface (identical in all families)
Crs*.c, Crs.hImplementation of the family
CMakeLists.txtLibrary Crs_Lib of the EmBi platform
Tests/UnitTestsUnit tests (Unity + CMock + RegMem)
Tests/IntegrationTestsIntegration tests on the target (probe-rs)

A change of the public interface is made in all families.


CMake integration​

target_link_libraries( User_Lib PRIVATE Crs_Lib )
  1. Link Crs_Lib to your CMake library.
  2. Include Crs_Port.h in your project.
  3. Configure the module as needed for your hardware.

License​

This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).

You are free to use, modify, and share this work for non-commercial purposes, provided appropriate credit is given.

See LICENSE.md for full terms or visit creativecommons.org/licenses/by-nc/4.0.


Authors​

Contributions are welcome! Please open a pull request.