Перейти до основного вмісту

LPUSART MCAL Module

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

This module provides an abstraction layer for the low-power UART (LPUARTx) of STM32 MCUs: an asynchronous serial interface that works from a 32.768 kHz clock and receives while the MCU sleeps. It offers the initialization, the communication parameters, the hardware flow control and the RS-485 driver enable, the wake-up from Stop mode and the data transfers in DMA, interrupt or polling mode. It is a low-level MCAL module: it owns the LPUART hardware, the application and the other modules never touch the registers.

The public interface (LpUsart_Port.h, LpUsart_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 USART module serves the USART / UART peripherals that are clocked from the high speed clocks. The LPUART is a different peripheral with a dual clock domain: the bus clock for the registers and an independent kernel clock (the LSE of 32.768 kHz, the HSI, the system clock ...) for the communication. With the LSE alone it communicates from 300 up to 9600 baud, and it can wait for a frame in the Stop mode and wake the MCU up by a start bit, a received byte or an address match. It is the serial port of a battery powered node that must be reachable without staying awake.
  • The interface is identical with the Usart module. Applications and middlewares that use Usart_Port.h (ModBus, CRSF, a terminal, a GNSS parser ...) switch to the LPUART by changing the prefix: the same data configuration (TxMode / RxMode DMA - ISR - POLL, a one shot or a circular receive buffer, the end of message by the idle line, the callbacks of the transmission, the half / full buffer, the end of message and the errors), the same functions for the baudrate, the data width, the stop bits, the parity, the flow control and the driver enable.
  • The LPUART has its own limits - the baudrate depends on the kernel clock (LPUARTDIV), there is no oversampling, no receiver timeout, no auto baudrate detection, no synchronous / smartcard / IrDA / LIN mode. The module reports an unsupported request as an error instead of silently ignoring it; the supported subset is listed below.
  • The module hides the differences between the families: the kernel clock sources, the FIFO, the wake-up options and the interrupt lines differ, the interface stays the same.

What the module is not: it does not select the oscillators (the RCC module starts the LSE / HSI kernel clock that was selected) and it does not enter the low-power mode (power module, future). It does not implement a protocol on the top of the serial line.


Concept​

An instance is identified by lpUsart_PeriphId_t. The communication uses the same model as the Usart module:

ItemMeaning
Kernel clocklpUsart_ClkSrc_t - the sources the instance offers (bus clock, system clock, HSI, LSE, PLL outputs ...). The baudrate is calculated from its frequency (read from the RCC module).
BaudrateRequired in baud; the module calculates LPUARTDIV (20 bit, minimum 0x300, so the baudrate is at most one third of the kernel clock) and reports the achieved baudrate. A kernel clock that cannot make the baudrate is an error.
FrameData width 7 / 8 / 9 bits, 1 or 2 stop bits, parity none / even / odd, MSB / LSB first, polarity of the pins, swap of the TX and RX pins.
Data handlinglpUsart_DataConfig_t: transmission and reception are configured independently as NONE, DMA, ISR or POLL (served by LpUsart_Task).
Wake-uplpUsart_WakeUpSource_t: start bit, received byte (RXNE), address match of the multiprocessor mode. The wake-up needs a kernel clock that runs in Stop mode.

Rules:

  1. LpUsart_Init configures the instance (clock, frame, baudrate, pins, data handling, interrupt) and enables it.
  2. The frame parameters and the baudrate are changed only on a disabled instance (LpUsart_Set_PeriphInactive); otherwise the call returns an error and nothing changes.
  3. The reception can be started and stopped (LpUsart_Set_RxStart / LpUsart_Set_RxStop) without a new initialization; the transmission is a request with a buffer (LpUsart_Set_TxStart) that finishes with the complete callback.
  4. The receive FIFO and the transmit FIFO (where the instance has them) are used by the module internally and are not visible to the application; the DMA request lines are handled by the module.
  5. Before the MCU enters the Stop mode the application checks LpUsart_Get_TxState (a transmission in progress prevents it); a frame that starts while the MCU sleeps is received by the instance and the MCU wakes up on the selected event.

Supported subset of the Usart interface:

FeatureLPUART
Baudrate, data width, stop bits, parity, bit order, pin polarity, pin swapyes
Hardware flow control (RTS / CTS) and driver enable (DE) with polarity, assertion and deassertion timeyes
Half-duplex single-wire modeyes
Data handling in DMA / ISR / POLL, one shot and circular receive buffer, end of message by the idle lineyes
Wake-up from Stop mode (start bit, received byte, address match), multiprocessor mute modeyes
Oversampling selection, receiver timeout (USART_RX_END_TIMEOUT), auto baudrate detectionno - the call returns LPUSART_REQUEST_ERROR
Synchronous (SPI master / slave), smartcard, IrDA, LIN modeno

Supported families​

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

FamilyBranchInstancesStatus
STM32H5Dev/STM32H5LPUART1, FIFOs on the transmitter and the receiver, DMA (GPDMA), wake-up from Stop mode, kernel clock selected in the RCC (bus clock 3, PLL2 Q, PLL3 Q, HSI, CSI, LSE)planned (first)
STM32U5Dev/STM32U5LPUART1planned
STM32G4, STM32L4Dev/STM32G4, Dev/STM32L4LPUART1planned
STM32H7Dev/STM32H7LPUART1planned
STM32F4, STM32F7Dev/STM32F4, Dev/STM32F7not on most devices (device dependent)planned
STM32U3Dev/STM32U3device dependentplanned

A function without a meaning in a family stays in the interface, returns LPUSART_REQUEST_ERROR and suppresses the unused parameters (for example the FIFO threshold on a device without FIFO, the wake-up from Stop on a family where the LPUART does not offer it).


Public interface in short (proposal)​

The functions have the same names, parameters and meaning as in Usart_Port.h, only the prefix is LpUsart_ / lpUsart_.

GroupFunctions
Module managementLpUsart_Get_ModuleVersion, LpUsart_Init, LpUsart_Deinit, LpUsart_Task, LpUsart_Get_DefaultConfig
Peripheral controlLpUsart_Set_PeriphActive, LpUsart_Set_PeriphInactive, LpUsart_Get_PeriphState
Communication settingsLpUsart_Set_Baudrate / Get, Set_DataWidth / Get, Set_StopBits / Get, Set_Parity / Get, Set_BitOrder / Get, Set_FlowControl / Get, Set_HalfDuplexState / Get, Set_PinLevels / Get, Set_PinSwap / Get
Driver enableLpUsart_Set_DriverEnableState, Set_DriverEnablePolarity, Set_AssertDeassertTimes (each with Get)
Clock and wake-upLpUsart_Set_ClkSrc / Get, LpUsart_Set_WakeUpSource / Get, LpUsart_Set_WakeUpActive, LpUsart_Set_WakeUpInactive, LpUsart_Set_MuteMode, LpUsart_Set_AddressMatch
Data transferLpUsart_Set_DataConfig / Get, LpUsart_Set_TxStart, Set_TxStop, Get_TxState, Set_RxStart, Set_RxStop, Get_RxState, Get_RxCount, Get_TxRegisterAddr, Get_RxRegisterAddr
InterruptsLpUsart_Set_IrqPriority / Get, LpUsart_Set_InterruptsActive, LpUsart_Set_InterruptsInactive, the enable / state / callback functions of the events (RX not empty, TX empty, TX complete, idle, error, wake-up)
PinsLpUsart_InitRxGpio, LpUsart_InitTxGpio, LpUsart_InitDeGpio, LpUsart_InitCtsGpio, LpUsart_InitRtsGpio
lpUsart_ModuleVersion_t LpUsart_Get_ModuleVersion ( void );

lpUsart_RequestState_t LpUsart_Init ( lpUsart_BusConfig_t * const lpUsartConfig );
lpUsart_RequestState_t LpUsart_Deinit ( lpUsart_PeriphId_t lpUsartId );
void LpUsart_Task ( void );
lpUsart_RequestState_t LpUsart_Get_DefaultConfig ( lpUsart_BusConfig_t * const lpUsartConfig );

lpUsart_RequestState_t LpUsart_Set_Baudrate ( lpUsart_PeriphId_t lpUsartId, lpUsart_Baudrate_t baudrate );
lpUsart_RequestState_t LpUsart_Get_Baudrate ( lpUsart_PeriphId_t lpUsartId, lpUsart_Baudrate_t * const baudrate );

lpUsart_RequestState_t LpUsart_Set_WakeUpSource ( lpUsart_PeriphId_t lpUsartId, lpUsart_WakeUpSource_t wakeUpSource );
lpUsart_RequestState_t LpUsart_Set_WakeUpActive ( lpUsart_PeriphId_t lpUsartId );
lpUsart_RequestState_t LpUsart_Set_WakeUpInactive ( lpUsart_PeriphId_t lpUsartId );

lpUsart_RequestState_t LpUsart_Set_DataConfig ( lpUsart_PeriphId_t lpUsartId, const lpUsart_DataConfig_t * const dataConfig );
lpUsart_RequestState_t LpUsart_Set_TxStart ( lpUsart_PeriphId_t lpUsartId, const lpUsart_TxData_t * const txData, lpUsart_TxDataCnt_t txSize );
lpUsart_RequestState_t LpUsart_Set_TxStop ( lpUsart_PeriphId_t lpUsartId );
lpUsart_RequestState_t LpUsart_Get_TxState ( lpUsart_PeriphId_t lpUsartId, lpUsart_FunctionState_t * const txState );
lpUsart_RequestState_t LpUsart_Set_RxStart ( lpUsart_PeriphId_t lpUsartId );
lpUsart_RequestState_t LpUsart_Set_RxStop ( lpUsart_PeriphId_t lpUsartId );
lpUsart_RequestState_t LpUsart_Get_RxCount ( lpUsart_PeriphId_t lpUsartId, lpUsart_RxDataCnt_t * const rxCnt );

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

TypeMeaning
lpUsart_BusConfig_tInstance, kernel clock, baudrate, frame, flow control, driver enable, pins, data handling, wake-up
lpUsart_DataConfig_tSame as usart_DataConfig_t: TxMode, RxMode, receive buffer and its mode, end of message mode, DMA channels and priorities, interrupt priority, callbacks (TX complete, RX half, RX complete, RX end, error)
lpUsart_ClkSrc_tLPUSART_CLK_SRC_<instance>_<source> - only the sources of the instance
lpUsart_WakeUpSource_tLPUSART_WAKEUP_NONE, LPUSART_WAKEUP_START_BIT, LPUSART_WAKEUP_RX_NOT_EMPTY, LPUSART_WAKEUP_ADDRESS_MATCH
lpUsart_RxEndMode_tLPUSART_RX_END_NONE, LPUSART_RX_END_IDLE (the timeout variant of the Usart module is not offered)
lpUsart_RxPin_t, lpUsart_TxPin_t, ...Encoded pins LPUSART_*_PIN_BUSx_Pyy, LPUSART_*_PIN_UNUSED - only the pins of the device

Usage​

Receiving while the MCU sleeps​

#include "LpUsart_Port.h"

static lpUsart_RxData_t rxBuffer[ 64u ];

static void App_MessageReceived( lpUsart_RxDataCnt_t rxCnt )
{
/* a complete message (the line was idle after the data), the MCU is awake */
}

static const lpUsart_DataConfig_t lpUsartData =
{
.TxMode = LPUSART_XFER_MODE_ISR,
.RxMode = LPUSART_XFER_MODE_DMA,
.RxBuffer = rxBuffer,
.RxBufferSize = sizeof( rxBuffer ),
.RxBufferMode = LPUSART_BUFFER_ONE_SHOT,
.RxEndMode = LPUSART_RX_END_IDLE,
.RxEndCallback = App_MessageReceived,
.IrqPriority = 5u,
};

lpUsart_BusConfig_t lpUsartConfig;

(void)LpUsart_Get_DefaultConfig( &lpUsartConfig );

lpUsartConfig.PeriphId = LPUSART_PERIPH_1;
lpUsartConfig.ClkSrc = LPUSART_CLK_SRC_LPUSART1_LSE; /* 32.768 kHz, runs in Stop mode */
lpUsartConfig.Baudrate = 9600u;
lpUsartConfig.DataConfig = &lpUsartData;
lpUsartConfig.RxPin = LPUSART_RX_PIN_BUS1_PB7;
lpUsartConfig.TxPin = LPUSART_TX_PIN_BUS1_PB6;

(void)LpUsart_Init( &lpUsartConfig );
(void)LpUsart_Set_WakeUpSource( LPUSART_PERIPH_1, LPUSART_WAKEUP_START_BIT );
(void)LpUsart_Set_WakeUpActive( LPUSART_PERIPH_1 );
(void)LpUsart_Set_RxStart( LPUSART_PERIPH_1 );

/* enter the Stop mode, the first byte of a message wakes the MCU up */

Sending a buffer​

static const lpUsart_TxData_t hello[] = "wake-up";

(void)LpUsart_Set_TxStart( LPUSART_PERIPH_1, hello, sizeof( hello ) - 1u );
/* the TX complete callback (if configured) reports the end; LpUsart_Get_TxState tells whether the line is still busy */

Behaviour and limits​

  • Baudrate range. baudrate <= kernelClock / 3; with the LSE the useful range is 300 ... 9600 baud (the accuracy of the crystal is the limit). A higher baudrate needs a faster kernel clock, which does not run in Stop mode (HSI kernel clock request can keep it for the wake-up on the families that offer it).
  • Wake-up. The wake-up works only with a kernel clock that runs in Stop mode and with the selected wake-up source enabled; the first received byte can be lost on some families if the wake-up is slower than the frame (documented in the README of the family and in the errata).
  • Stop mode and transmission. A running transmission has to finish before the MCU enters Stop mode (LpUsart_Get_TxState); the module does not delay the sleep.
  • Callbacks run in the interrupt (ISR / DMA mode) or in LpUsart_Task (POLL mode); keep them short.
  • Errors. Overrun, noise, framing and parity errors are reported by the error callback with the error mask; the flags are cleared by the module.
  • Not part of the first version: LIN / smartcard / IrDA / synchronous modes (not in the hardware), the Modbus and other protocol layers (middlewares), the autonomous mode of the families that have it.

Dependencies​

  • Rcc - peripheral clock, kernel clock source selection and frequency, request of the oscillator in Stop mode
  • Nvic - interrupt of the instance
  • Gpio - RX, TX, DE, CTS and RTS pins
  • Gpdma - DMA transfers of the transmission and the reception
  • RAL (Register Abstraction Layer) - used internally to access the registers

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


Testing​

  • Unit tests (host, Unity + CMock + RegMem): the baudrate calculation for every kernel clock (the limit kernelClock / 3, the rounding, the rejected baudrates), the rules of the rejected calls on an enabled instance, the data handling in ISR / POLL / DMA (circular and one shot buffer, the end of message by the idle line), the error mapping, the unsupported requests.
  • Integration tests (target, probe-rs): the loop-back at 9600 baud from the LSE, the wake-up from Stop mode by the start bit and by the received byte, the DMA reception of a message, the RS-485 driver enable timing.

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 LPUSART_<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. LpUsart_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 LpUsart_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 (lpUsart_FunctionState_t, lpUsart_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 LPUSART_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
LpUsart_Port.h, LpUsart_Types.hPublic interface (identical in all families)
LpUsart*.c, LpUsart.hImplementation of the family
CMakeLists.txtLibrary LpUsart_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 LpUsart_Lib )
  1. Link LpUsart_Lib to your CMake library.
  2. Include LpUsart_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.