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:
| Item | Meaning |
|---|---|
| Target frequency | The 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 frequency | The 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 polarity | The division of a fast external reference (1, 2, 4 ... 128) and the active edge of the pin. |
| Error limit | The frequency error in ppm that is still considered synchronized (derived from the target and the oscillator step). |
| Trimming mode | Automatic (the hardware adjusts the trim after every event) or manual (the application writes the trim, for a fast start from a known value). |
Rules:
Crs_Initconfigures the source, the frequencies and the limit and leaves the trimming stopped;Crs_Set_AutoTrimActivestarts it. The module checks that the oscillator is running (an error otherwise - the RCC module starts it).- The configuration is changed only while the automatic trimming is stopped.
Crs_Get_SyncStatereturnsCRS_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_FrequencyErrorreturns the last error and its direction.Crs_Set_Trimmingwrites a manual trim (for example the value stored from the last run) andCrs_Get_Trimmingreads the current one, so an application can start from a known trim and reach the synchronization immediately.Crs_Set_SoftwareSyncgenerates one synchronization event by the software (a test or a one-shot calibration).- 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.
| Family | Branch | Clock recovery | Status |
|---|---|---|---|
| STM32H5 | Dev/STM32H5 | CRS of the HSI48, 6-bit trim, sources USB SOF / LSE / CRS_SYNC pin, TrustZone aliases | planned (first) |
| STM32U5 | Dev/STM32U5 | CRS | planned |
| STM32G4, STM32L4 | Dev/STM32G4, Dev/STM32L4 | CRS on the lines with the HSI48 | planned |
| STM32H7 | Dev/STM32H7 | CRS on the lines with the HSI48 | planned |
| STM32U3 | Dev/STM32U3 | device dependent | planned |
| STM32F4, STM32F7 | Dev/STM32F4, Dev/STM32F7 | no CRS on the device - the module is a stub that returns CRS_REQUEST_ERROR | planned |
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)
| Group | Functions |
|---|---|
| Module management | Crs_Get_ModuleVersion, Crs_Init, Crs_Deinit, Crs_Task, Crs_Get_DefaultConfig |
| Control | Crs_Set_AutoTrimActive, Crs_Set_AutoTrimInactive, Crs_Set_Trimming, Crs_Get_Trimming, Crs_Set_SoftwareSync |
| State | Crs_Get_SyncState, Crs_Get_FrequencyError |
| Interrupts | Crs_Set_IrqPriority / Get, the callbacks are a part of the configuration |
| Pins | Crs_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.
| Type | Meaning |
|---|---|
crs_Config_t | Synchronization source, synchronization frequency, target frequency, prescaler, polarity, the start trim, callbacks, interrupt priority |
crs_SyncState_t | CRS_SYNC_OFF, CRS_SYNC_TRIMMING, CRS_SYNC_OK, CRS_SYNC_WARNING, CRS_SYNC_ERROR |
crs_FreqError_t | The error in counter ticks and the direction (CRS_ERROR_DIR_UP / DOWN) |
crs_Trimming_t | The 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_WARNINGorCRS_SYNC_ERRORappears, 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 / syncmust 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_SYNCpin - 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 enumlist with exactly the items that are valid for the device line; a pin is an itemCRS_<SIGNAL>_PIN_<INSTANCE>_P<port><pin>and there is an*_UNUSEDitem. 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_Initchecks 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:
| Path | Content |
|---|---|
README.md | README of the family: the instances of the device, specifics, errata, status |
Crs_Port.h, Crs_Types.h | Public interface (identical in all families) |
Crs*.c, Crs.h | Implementation of the family |
CMakeLists.txt | Library Crs_Lib of the EmBi platform |
Tests/UnitTests | Unit tests (Unity + CMock + RegMem) |
Tests/IntegrationTests | Integration 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 )
- Link
Crs_Libto your CMake library. - Include
Crs_Port.hin your project. - 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
- Mr.Nobody - embedbits.com
Contributions are welcome! Please open a pull request.