ST UM3029 Low Layer Drivers User Manual

June 10, 2024
ST

UM3029 Low Layer Drivers

Product Information

The product is a set of HAL (Hardware Abstraction Layer) drivers
for STM32C0 microcontrollers. The HAL drivers consist of a set of
functions covering the most common peripheral features and are
designed to offer a rich set of APIs and to interact easily with
the application upper layers. Each driver is driven by a common API
which standardizes the driver structure, functions, and parameter
names. The HAL drivers include a set of driver modules, each module
being linked to a standalone peripheral or functional mode.

Acronyms and Definitions

Acronym Definition
ADC Analog-to-digital converter
ANSI American national standards institute
API Application programming interface
BSP Board support package
CMSIS Cortex microcontroller software interface standard
CPU Central processing unit
CRC CRC calculation unit
CSS Clock security system
DLYB Delay block
DMA Direct memory access
DMAMUX Advanced-control, general-purpose or basic timer
EXTI Universal asynchronous receiver/transmitter
FLASH Universal synchronous receiver/transmitter
GPIO Voltage reference buffer
HAL Hardware Abstraction Layer
I2C Inter-Integrated Circuit
I2S Integrated Interchip Sound
ICACHE Instruction cache
IRDA Infrared data association
IWDG Independent watchdog
MCO Microcontroller clock output
MPU Memory protection unit
MSP Main stack pointer
NVIC Nested vectored interrupt controller
PPP Peripheral/module driver name
PWR Power control
RCC Reset and clock control
RTC Real-time clock
SMBUS System management bus
SPI Serial peripheral interface
SRAM Static random-access memory
SysTick System tick timer
TIM Timer
UART Universal asynchronous receiver/transmitter
USART Universal synchronous receiver/transmitter
VREFBUF Voltage reference buffer
WWDG Window watchdog

Product Usage Instructions

To use the product, follow these steps:

  1. Download and install the necessary software from the
    STMicroelectronics website.

  2. Include the necessary HAL driver files in your project, such as
    stm32c0xx_hal_ppp.c, stm32c0xx_hal_ppp.h, stm32c0xx_hal_ppp_ex.c,
    and stm32c0xx_hal_ppp_ex.h.

  3. Initialize the HAL drivers using the stm32c0xx_hal.c and
    stm32c0xx_hal.h files.

  4. Use the standardized APIs provided by the HAL drivers to
    interact with the peripherals on the STM32C0 microcontroller.

  5. Refer to the user manual for further information on specific
    APIs and peripheral features.

UM3029
User manual
Description of STM32C0 HAL and low-layer drivers
Introduction
STM32Cube is an STMicroelectronics original initiative to significantly improve developer productivity by reducing development effort, time and cost. STM32Cube covers the STM32 portfolio. STM32Cube includes: · STM32CubeMX, a graphical software configuration tool that allows the generation of C initialization code using graphical
wizards. · A comprehensive embedded software platform, delivered per Series (such as STM32CubeC0 for STM32C0 Series)
­ The STM32Cube HAL, STM32 abstraction layer embedded software ensuring maximized portability across the STM32 portfolio. HAL APIs are available for all peripherals.
­ Low-layer APIs (LL) offering a fast light-weight expert-oriented layer which is closer to the hardware than the HAL. LL APIs are available only for a set of peripherals.
­ A consistent set of middleware components such as Azure® RTOS ThreadX, FileX and LevelX The HAL driver layer provides a simple, generic multi-instance set of APIs (application programming interfaces) to interact with the upper layer (application, libraries and stacks). The HAL driver APIs are split into two categories: generic APIs, which provide common and generic functions for all the STM32 series and extension APIs, which include specific and customized functions for a given line or part number. The HAL drivers include a complete set of ready-to-use APIs that simplify the user application implementation. For example, the communication peripherals contain APIs to initialize and configure the peripheral, manage data transfers in polling mode, handle interrupts or DMA, and manage communication errors. The HAL drivers are feature-oriented instead of IP-oriented. For example, the timer APIs are split into several categories following the IP functions, such as basic timer, capture and pulse width modulation (PWM). The HAL driver layer implements run- time failure detection by checking the input values of all functions. Such dynamic checking enhances the firmware robustness. Run-time detection is also suitable for user application development and debugging. The LL drivers offer hardware services based on the available features of the STM32 peripherals. These services reflect exactly the hardware capabilities, and provide atomic operations that must be called by following the programming model described in the product line reference manual. As a result, the LL services are not based on standalone processes and do not require any additional memory resources to save their states, counter or data pointers. All operations are performed by changing the content of the associated peripheral registers. Unlike the HAL, LL APIs are not provided for peripherals for which optimized access is not a key feature, or for those requiring heavy software configuration and/or a complex upper-level stack. The HAL and LL are complementary and cover a wide range of application requirements: · The HAL offers high-level and feature- oriented APIs with a high-portability level. These hide the MCU and peripheral
complexity from the end-user. · The LL offers low-level APIs at register level, with better optimization but less portability. These require deep knowledge of
the MCU and peripheral specifications. The HAL- and LL-driver source code is developed in Strict ANSI-C, which makes it independent of the development tools. It is checked with the CodeSonar® static analysis tool. It is fully documented. They are compliant with MISRA C®:2012 standard. This user manual is structured as follows: · Overview of HAL drivers · Overview of low-layer drivers · Cohabiting of HAL and LL drivers · Detailed description of each peripheral driver: configuration structures, functions, and how to use the given API to build
your application

UM3029 – Rev 1 – September 2022 For further information contact your local STMicroelectronics sales office.

www.st.com

1
Note:

UM3029
General information
General information
The STM32CubeC0 MCU Package runs on STM32C0 32-bit microcontrollers based on the Arm® Cortex®-M processor. Arm is a registered trademark of Arm Limited (or its subsidiaries) in the US and/or elsewhere.

UM3029 – Rev 1

page 2/1419

UM3029
Acronyms and definitions

2

Acronyms and definitions

Acronym ADC ANSI API BSP
CMSIS CPU CRC CSS DLYB DMA
DMAMUX EXTI FLASH GPIO HAL I2C I2S
ICACHE IRDA IWDG MCO MPU MSP NVIC PPP PWR RCC RTC
SMBUS SPI
SRAM SysTick
TIM UART USART VREFBUF WWDG

Table 1. Acronyms and definitions
Definition Analog-to-digital converter American national standards institute Application programming interface
Board support package Cortex microcontroller software interface standard
Central processing unit CRC calculation unit Clock security system Delay block Direct memory access
Direct memory access request multiplexer External interrupt/event controller Flash memory General purpose I/Os Hardware abstraction layer Inter-integrated circuit Inter-integrated sound Instruction cache Infrared data association Independent watchdog Microcontroller clock output Memory protection unit MCU specific package Nested vectored interrupt controller STM32 peripheral or block Power controller Reset and clock controller Real-time clock System management bus Serial peripheral interface SRAM external memory System tick timer
Advanced-control, general-purpose or basic timer Universal asynchronous receiver/transmitter Universal synchronous receiver/transmitter Voltage reference buffer Window watchdog

UM3029 – Rev 1

page 3/1419

UM3029
Overview of HAL drivers

3

Overview of HAL drivers

The HAL drivers are designed to offer a rich set of APIs and to interact easily with the application upper layers.
Each driver consists of a set of functions covering the most common peripheral features. The development of each driver is driven by a common API which standardizes the driver structure, the functions and the parameter names.
The HAL drivers include a set of driver modules, each module being linked to a standalone peripheral. However, in some cases, the module is linked to a peripheral functional mode. As an example, several modules exist for the USART peripheral: UART driver module, USART driver module, SMARTCARD driver module and IRDA driver module.
The HAL main features are the following:
· Cross-family portable set of APIs covering the common peripheral features as well as extension APIs in case of specific peripheral features.
· Three API programming models: polling, interrupt and DMA.
· APIs are RTOS compliant:
­ Fully reentrant APIs
­ Systematic usage of timeouts in polling mode
· Support of peripheral multi-instance allowing concurrent API calls for multiple instances of a given peripheral (such as USART1 or USART2)
· All HAL APIs implement user-callback functions mechanism:
­ Peripheral Init/DeInit HAL APIs can call user-callback functions to perform peripheral system level Initialization/De-Initialization (clock, GPIOs, interrupt, DMA)
­ Peripherals interrupt events
­ Error events
· Object locking mechanism: safe hardware access to prevent multiple spurious accesses to shared resources.
· Timeout used for all blocking processes: the timeout can be a simple counter or a timebase.

UM3029 – Rev 1

page 4/1419

3.1
3.1.1
3.1.2

UM3029
HAL and user-application files

HAL and user-application files
HAL driver files HAL drivers are composed of the following set of files:

Table 2. HAL driver files

File

Description

stm32c0xx_hal_ppp.c

Main peripheral/module driver file It includes the APIs that are common to all STM32 devices. Example: stm32c0xx_hal_adc.c, stm32c0xx_hal_irda.c.

stm32c0xx_hal_ppp.h

Header file of the main driver C file
It includes common data, handle and enumeration structures, define statements and macros, as well as the exported generic APIs. Example:stm32c0xx_hal_adc.h,stm32c0xx_hal_irda.h.

stm32c0xx_hal_ppp_ex.c

Extension file of a peripheral/module driver. It includes the specific APIs for a given part number or family, as well as the newly defined APIs that overwrite the default generic APIs if the internal process is implemented in different way.
Example:stm32c0xx_hal_adc_ex.c,stm32c0xx_hal_flash_ex.c.

stm32c0xx_hal_ppp_ex.h

Header file of the extension C file
It includes the specific data and enumeration structures, define statements and macros, as well as the exported device part number specific APIs Example: stm32c0xx_hal_adc_ex.h,stm32c0xx_hal_flash_ex.h.

stm32c0xx_hal.c stm32c0xx_hal.h

This file is used for HAL initialization and contains DBGMCU, Remap and Time Delay based on SysTick APIs.
stm32c0xx_hal.c header file

Template file to be copied to the user application folder stm32c0xx_hal_msp_template.c It contains the MSP initialization and de- initialization (main routine and callbacks) of the
peripheral used in the user application.
stm32c0xx_hal_conf_template.h Template file allowing to customize the drivers for a given application

stm32c0xx_hal_def.h

Common HAL resources such as common define statements, enumerations, structures and macros

User-application files The minimum files required to build an application using the HAL are listed in the table below:

Table 3. User-application files

File system_stm32c0xx.c
startup_stm32c0xx.s stm32c0xx_flash.icf
(optional) stm32c0xx_hal_msp.c stm32c0xx_hal_conf.h

Description
This file contains SystemInit() that is called at startup just after reset and before branching to the main program. It does not configure the system clock at startup (contrary to the standard library). This is to be done using the HAL APIs in the user files. It allows relocating the vector table in internal SRAM.
Toolchain specific file that contains reset handler and exception vectors.
For some toolchains, it allows adapting the stack/heap size to fit the application requirements.
Linker file for EWARM toolchain allowing mainly adapting the stack/heap size to fit the application requirements.
This file contains the MSP initialization and de-initialization (main routine and callbacks) of the peripheral used in the user application.
This file allows the user to customize the HAL drivers for a specific application.

UM3029 – Rev 1

page 5/1419

Note:

UM3029
HAL and user-application files

File stm32c0xx_it.c/.h
main.c/.h

Description It is not mandatory to modify this configuration. The application can use the default configuration without any modification.
This file contains the exceptions handler and peripherals interrupt service routine, and calls HAL_IncTick() at regular time intervals to increment a local variable (declared in stm32c0xx_hal.c) used as HAL timebase. By default, this function is called each 1ms in Systick ISR. .
The PPP_IRQHandler() routine must call HAL_PPP_IRQHandler() if an interrupt based process is used within the application.
This file contains the main program routine, mainly: · Call to HAL_Init() · assert_failed() implementation · system clock configuration · peripheral HAL initialization and user application code.

The STM32Cube package comes with ready-to-use project templates, one for each supported board. Each project contains the files listed above and a preconfigured project for the supported toolchains. Each project template provides empty main loop function and can be used as a starting point to get familiar with project settings for STM32Cube. Its features are the following:
· It contains the sources of HAL, CMSIS and BSP drivers which are the minimal components to develop a code on a given board.
· It contains the include paths for all the firmware components. · It defines the STM32 device supported, and allows configuring the CMSIS and HAL drivers accordingly. · It provides ready to use user files preconfigured as defined below:
­ HAL is initialized ­ SysTick ISR implemented for HAL_GetTick() ­ System clock configured with the selected device frequency.
If an existing project is copied to another location, then include paths must be updated.

UM3029 – Rev 1

page 6/1419

Figure 1. Example of project template

UM3029
HAL data structures

3.2
3.2.1

HAL data structures
Each HAL driver can contain the following data structures: · Peripheral handle structures · Initialization and configuration structures · Specific process structures.
Peripheral handle structures The APIs have a modular generic multi-instance architecture that enables working with several IP instances simultaneously. PPP_HandleTypeDef *handle is the main structure that is implemented in the HAL drivers. It handles the peripheral/module configuration and registers and embeds all the structures and variables needed to follow the peripheral device flow.

UM3029 – Rev 1

page 7/1419

Note:

UM3029
HAL data structures
The peripheral handle is used for the following purposes:
· Multi-instance support: each peripheral/module instance has its own handle. As a result instance resources are independent.
· Peripheral process intercommunication: the handle is used to manage shared data resources between the process routines. Example: global pointers, DMA handles, state machine.
· Storage : this handle is used also to manage global variables within a given HAL driver.
An example of peripheral structure is shown below:
typedef struct { USART_TypeDef Instance; / USART registers base address / USART_InitTypeDef Init; / Usart communication parameters / uint8_t pTxBuffPtr;/ Pointer to Usart Tx transfer Buffer / uint16_t TxXferSize; / Usart Tx Transfer size / __IO uint16_t TxXferCount;/ Usart Tx Transfer Counter / uint8_t pRxBuffPtr;/ Pointer to Usart Rx transfer Buffer / uint16_t RxXferSize; / Usart Rx Transfer size / __IO uint16_t RxXferCount; / Usart Rx Transfer Counter / DMA_HandleTypeDef hdmatx; / Usart Tx DMA Handle parameters / DMA_HandleTypeDef hdmarx; / Usart Rx DMA Handle parameters / HAL_LockTypeDef Lock; / Locking object / __IO HAL_USART_StateTypeDef State; / Usart communication state / __IO HAL_USART_ErrorTypeDef ErrorCode;/ USART Error code */ }USART_HandleTypeDef;
1. The multi-instance feature implies that all the APIs used in the application are reentrant and avoid using global variables because subroutines can fail to be reentrant if they rely on a global variable to remain unchanged but that variable is modified when the subroutine is recursively invoked. For this reason, the following rules are respected: ­ Reentrant code does not hold any static (or global) non-constant data: reentrant functions can work with global data. For example, a reentrant interrupt service routine can grab a piece of hardware status to work with (for example serial port read buffer) which is not only global, but volatile. Still, typical use of static variables and global data is not advised, in the sense that only atomic readmodify-write instructions should be used in these variables. It should not be possible for an interrupt or signal to occur during the execution of such an instruction. ­ Reentrant code does not modify its own code.
2. When a peripheral can manage several processes simultaneously using the DMA (full duplex case), the DMA interface handle for each process is added in the PPP_HandleTypeDef.
3. For the shared and system peripherals, no handle or instance object is used. The peripherals concerned by this exception are the following: ­ GPIO ­ SYSTICK ­ NVIC ­ PWR ­ RCC ­ FLASH

UM3029 – Rev 1

page 8/1419

3.2.2
Note: 3.2.3

UM3029
HAL data structures
Initialization and configuration structure These structures are defined in the generic driver header file when it is common to all part numbers. When they can change from one part number to another, the structures are defined in the extension header file for each part number.
typedef struct { uint32_t BaudRate; /!< This member configures the UART communication baudrate./ uint32_t WordLength; /!< Specifies the number of data bits transmitted or received in a frame./ uint32_t StopBits; /!< Specifies the number of stop bits transmitted./ uint32_t Parity; /!< Specifies the parity mode. / uint32_t Mode; /!< Specifies wether the Receive or Transmit mode is enabled or disabled./ uint32_t HwFlowCtl; /!< Specifies wether the hardware flow control mode is enabled or disabled./ uint32_t OverSampling; /!< Specifies wether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8)./ }UART_InitTypeDef;
The config structure is used to initialize the sub-modules or sub-instances. See below example: HAL_ADC_ConfigChannel (ADC_HandleTypeDef hadc, ADC_ChannelConfTypeDef sConfig)
Specific process structures The specific process structures are used for specific process (common APIs). They are defined in the generic driver header file. Example:
HAL_PPP_Process (PPP_HandleTypeDef hadc,PPP_ProcessConfig sConfig)

UM3029 – Rev 1

page 9/1419

3.3
Note: Note:

UM3029
API classification

API classification
The HAL APIs are classified into the following categories:
· Generic APIs: common generic APIs applying to all STM32 devices. These APIs are consequently present in the generic HAL driver files of all STM32 microcontrollers.
HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef hadc); HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef hadc); HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef hadc); HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef hadc); HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef hadc); HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef hadc); void HAL_ADC_IRQHandler(ADC_HandleTypeDef hadc);
· Extension APIs: This set of API is divided into two sub-categories :
­ Family specific APIs: APIs applying to a given family. They are located in the extension HAL driver file (see example below related to the ADC).
HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef
hadc,uint32_t SingleDiff); uint32_t HAL_ADCEx_Calibration_GetValue(ADC_HandleTypeDef* hadc, uint32_t SingleDiff);
­ Feature/Device specific APIs: these APIs are implemented in the extension file and delimited by specific define statements relative to CMSIS bits or features and depending on device part number.
The data structure related to the specific APIs is delimited by the device part number define statement. It is located in the corresponding extension header C file. The following table summarizes the location of the different categories of HAL APIs in the driver files.

Common APIs Family specific APIs Device specific APIs

Table 4. API classification Generic file X –

Extension file X X X

Family specific APIs are only related to a given family. This means that if a specific API is implemented in another family, and the arguments of this latter family are different, additional structures and arguments might need to be added. The IRQ handlers are used for common and family specific processes.

UM3029 – Rev 1

page 10/1419

3.4

UM3029
Devices supported by HAL drivers

Devices supported by HAL drivers

Table 5. List of devices supported by HAL drivers

IP/module stm32c0xx_hal.c stm32c0xx_hal_adc.c stm32c0xx_hal_adc_ex.c stm32c0xx_hal_cortex.c stm32c0xx_hal_crc.c stm32c0xx_hal_crc_ex.c stm32c0xx_hal_dma.c stm32c0xx_hal_dma_ex.c stm32c0xx_hal_exti.c stm32c0xx_hal_flash.c stm32c0xx_hal_flash_ex.c stm32c0xx_hal_gpio.c stm32c0xx_hal_i2c.c stm32c0xx_hal_i2c_ex.c stm32c0xx_hal_i2s.c stm32c0xx_hal_irda.c stm32c0xx_hal_iwdg.c stm32c0xx_hal_msp_template.c stm32c0xx_hal_pwr.c stm32c0xx_hal_pwr_ex.c stm32c0xx_hal_rcc.c stm32c0xx_hal_rcc_ex.c stm32c0xx_hal_rtc.c stm32c0xx_hal_rtc_ex.c stm32c0xx_hal_smartcard.c stm32c0xx_hal_smartcard_ex.c stm32c0xx_hal_smbus.c stm32c0xx_hal_smbus_ex.c stm32c0xx_hal_spi.c stm32c0xx_hal_spi_ex.c stm32c0xx_hal_tim.c stm32c0xx_hal_tim_ex.c stm32c0xx_hal_uart.c stm32c0xx_hal_uart_ex.c stm32c0xx_hal_usart.c stm32c0xx_hal_usart_ex.c stm32c0xx_hal_wwdg.c

STM32C031xx Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

STM32C011xx Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

UM3029 – Rev 1

page 11/1419

UM3029
HAL driver rules

3.5
3.5.1

HAL driver rules
HAL API naming rules The following naming rules are used in HAL drivers:

Table 6. HAL API naming rules

File names
Module name
Function name
Handle name
Init structure
name
Enum name

Generic stm32c0xx_hal_ppp (c/h)
HAL_PPP_Function HAL_PPP_FeatureFunction_MODE
PPP_HandleTypedef PPP_InitTypeDef
HAL_PPP_StructnameTypeDef

Family specific APIs stm32c0xx_hal_ppp_ex (c/h)
HALPPP MODULE HAL_PPPEx_Function HAL_PPPEx_FeatureFunction_MODE
NA
NA
NA

Device specific APIs stm32c0xx_ hal_ppp_ex (c/h)
HAL_PPPEx_Function HAL_PPPEx_FeatureFunction_MODE
NA PPP_InitTypeDef
NA

· The PPP prefix refers to the peripheral functional mode and not to the peripheral itself. For example, if the USART, PPP can be USART, IRDA, UART or SMARTCARD depending on the peripheral mode.
· The constants used in one file are defined within this file. A constant used in several files is defined in a header file. All constants are written in uppercase, except for peripheral driver function parameters.
· typedef variable names should be suffixed with _TypeDef.
· Registers are considered as constants. In most cases, their name is in uppercase and uses the same acronyms as in the STM32C0 reference manuals.
· Peripheral registers are declared in the PPP_TypeDef structure (for example ADCTypeDef) in stm32c0xxx.h header file:
stm32c0xxx.h corresponds to stm32c031xx.h and stm32c011xx.h.
· Peripheral function names are prefixed by HAL
, then the corresponding peripheral acronym in uppercase followed by an underscore. The first letter of each word is in uppercase (for example HAL_UART_Transmit()). Only one underscore is allowed in a function name to separate the peripheral acronym from the rest of the function name.
· The structure containing the PPP peripheral initialization parameters are named PPP_InitTypeDef (for example ADC_InitTypeDef).
· The structure containing the Specific configuration parameters for the PPP peripheral are named PPP_xxxxConfTypeDef (for example ADC_ChannelConfTypeDef).
· Peripheral handle structures are named PPP_HandleTypedef (e.g DMA_HandleTypeDef)
· The functions used to initialize the PPP peripheral according to parameters specified in PPP_InitTypeDef are named HAL_PPP_Init (for example HAL_TIM_Init()).
· The functions used to reset the PPP peripheral registers to their default values are named HAL_PPP_DeInit (for example HAL_TIM_DeInit()).
· The MODE suffix refers to the process mode, which can be polling, interrupt or DMA. As an example, when the DMA is used in addition to the native resources, the function should be called: HAL_PPP_Function_DMA().
· The Feature prefix should refer to the new feature. Example: HAL_ADCEx_InjectedStart()() refers to the injection mode.

UM3029 – Rev 1

page 12/1419

UM3029
HAL driver rules

3.5.2 Note:

HAL general naming rules · For the shared and system peripherals, no handle or instance object is used. This rule applies to the
following peripherals:
­ GPIO ­ SYSTICK ­ NVIC ­ RCC ­ FLASH Example: The HAL_GPIO_Init() requires only the GPIO address and its configuration parameters.
HAL_StatusTypeDef HAL_GPIO_Init (GPIO_TypeDef GPIOx, GPIO_InitTypeDef Init) { /GPIO Initialization body / }
· The macros that handle interrupts and specific clock configurations are defined in each peripheral/module driver. These macros are exported in the peripheral driver header files so that they can be used by the extension file. The list of these macros is defined below:
This list is not exhaustive and other macros related to peripheral features can be added, so that they can be used in the user application.

Table 7. Macros handling interrupts and specific clock configurations

Macros

Description

__HAL_PPP_ENABLE_IT(HANDLE, INTERRUPT) Enables a specific peripheral interrupt

__HAL_PPP_DISABLE_IT(HANDLE, INTERRUPT)

Disables a specific peripheral interrupt

__HAL_PPP_GET_IT (HANDLE, INTERRUPT ) Gets a specific peripheral interrupt status

__HAL_PPP_CLEAR_IT (HANDLE, INTERRUPT ) Clears a specific peripheral interrupt status

__HAL_PPP_GET_FLAG (HANDLE, FLAG) Gets a specific peripheral flag status

__HAL_PPP_CLEAR_FLAG (HANDLE, FLAG) Clears a specific peripheral flag status

HAL_PPP_ENABLE(HANDLE__)

Enables a peripheral

HAL_PPP_DISABLE(HANDLE__)

Disables a peripheral

HAL_PPP_XXXX (HANDLE, PARAM__)

Specific PPP HAL driver macro

HAL_PPPGET IT_SOURCE (HANDLE, INTERRUPT __)

Checks the source of specified interrupt

· NVIC and stm32c0xx_hal_cortex.c are two Arm® Cortex® core features. The APIs related to these features are located in the stm32c0xx_hal_cortex.c file.
· When a status bit or a flag is read from registers, it is composed of shifted values depending on the number of read values and of their size. In this case, the returned status width is 32 bits. Example:
STATUS = XX | (YY << 16) or STATUS = XX | (YY << 8) | (YY << 16) | (YY << 24).
· The PPP handles are valid before using the HAL_PPP_Init() API. The init function performs a check before modifying the handle fields.
HAL_PPP_Init(PPP_HandleTypeDef) if(hppp == NULL)
{ return HAL_ERROR; }

UM3029 – Rev 1

page 13/1419

3.5.3
3.6

UM3029
HAL generic APIs

· The macros defined below are used: ­ Conditional macro:

define ABS(x) (((x) > 0) ? (x) : -(x))

­ Pseudo-code macro (multiple instructions macro):

define HAL_LINKDMA(HANDLE, __PPP_DMAFIELD, DMAHANDLE) do{

(HANDLE)->__PPP_DMAFIELD = &(DMAHANDLE); (DMAHANDLE).Parent = (HANDLE); } while(0)

HAL interrupt handler and callback functions Besides the APIs, HAL peripheral drivers include:
· HAL_PPP_IRQHandler() peripheral interrupt handler that should be called from stm32c0xx_it.c · User callback functions.
The user callback functions are defined as empty functions with “weak” attribute. They have to be defined in the user code. There are three types of user callbacks functions:
· Peripheral system level initialization/ de-Initialization callbacks: HAL_PPP_MspInit() and HAL_PPP_MspDeInit
· Process complete callbacks : HAL_PPP_ProcessCpltCallback · Error callback: HAL_PPP_ErrorCallback.

Table 8. Callback functions

Callback functions

Example

HAL_PPP_MspInit() / _DeInit()

Example: HAL_USART_MspInit()
Called from HAL_PPP_Init() API function to perform peripheral system level initialization (GPIOs, clock, DMA, interrupt)

Example: HAL_USART_TxCpltCallback HAL_PPP_ProcessCpltCallback
Called by peripheral or DMA interrupt handler when the process completes

HAL_PPP_ErrorCallback

Example: HAL_USART_ErrorCallback Called by peripheral or DMA interrupt handler when an error occurs

HAL generic APIs
The generic APIs provide common generic functions applying to all STM32 devices. They are composed of four APIs groups:
· Initialization and de-initialization functions:HAL_PPP_Init(), HAL_PPP_DeInit() · IO operation functions: HAL_PPP_Read(), HAL_PPP_Write(),HAL_PPP_Transmit(), HAL_PPP_Receive() · Control functions: HAL_PPP_Set (), HAL_PPP_Get (). · State and Errors functions: HAL_PPP_GetState (), HAL_PPP_GetError ().
For some peripheral/module drivers, these groups are modified depending on the peripheral/module implementation.
Example: in the timer driver, the API grouping is based on timer features (such as PWM, OC and IC).
The initialization and de-initialization functions allow initializing a peripheral and configuring the low-level resources, mainly clocks, GPIO, alternate functions (AF) and possibly DMA and interrupts. The HAL_DeInit() function restores the peripheral default state, frees the low-level resources and removes any direct dependency with the hardware.
The IO operation functions perform a row access to the peripheral payload data in write and read modes.
The control functions are used to change dynamically the peripheral configuration and set another operating mode.

UM3029 – Rev 1

page 14/1419

3.7
3.7.1

UM3029
HAL extension APIs

The peripheral state and errors functions allow retrieving in run time the peripheral and data flow states, and identifying the type of errors that occurred. The example below is based on the ADC peripheral. The list of generic APIs is not exhaustive. It is only given as an example.

Table 9. HAL generic APIs

Function group Initialization group
IO operation group
Control group State and Errors
group

Common API name

Description

HAL_ADC_Init()

This function initializes the peripheral and configures the low -level resources (clocks, GPIO, AF..)

HAL_ADC_DeInit()

This function restores the peripheral default state, frees the lowlevel resources and removes any direct dependency with the hardware.

HAL_ADC_Start ()

This function starts ADC conversions when the polling method is used

HAL_ADC_Stop ()

This function stops ADC conversions when the polling method is used

This function allows waiting for the end of conversions when the HAL_ADC_PollForConversion() polling method is used. In this case, a timout value is specified by
the user according to the application.

HAL_ADC_Start_IT()

This function starts ADC conversions when the interrupt method is used

HAL_ADC_Stop_IT() HAL_ADC_IRQHandler()

This function stops ADC conversions when the interrupt method is used
This function handles ADC interrupt requests

HAL_ADC_ConvCpltCallback()

Callback function called in the IT subroutine to indicate the end of the current process or when a DMA transfer has completed

HAL_ADC_ErrorCallback()

Callback function called in the IT subroutine if a peripheral error or a DMA transfer error occurred

HAL_ADC_ConfigChannel()

This function configures the selected ADC regular channel, the corresponding rank in the sequencer and the sample time

HAL_ADC_AnalogWDGConfig This function configures the analog watchdog for the selected ADC

HAL_ADC_GetState()

This function allows getting in run time the peripheral and the data flow states.

HAL_ADC_GetError()

This fuction allows getting in run time the error that occurred during IT routine

HAL extension APIs
HAL extension model overview The extension APIs provide specific functions or overwrite modified APIs for a specific family (series) or specific part number within the same family. The extension model consists of an additional file, stm32c0xx_hal_ppp_ex.c, that includes all the specific functions and define statements (stm32c0xx_hal_ppp_ex.h) for a given part number. Below an example based on the ADC peripheral:

Table 10. HAL extension APIs

Function group HAL_ADCEx_CalibrationStart() HAL_ADCEx_Calibration_GetValue()

Common API name This function is used to start the automatic ADC calibration
This function is used to get the ADC calibration factor

UM3029 – Rev 1

page 15/1419

3.7.2

UM3029
HAL extension APIs
HAL extension model cases The specific peripheral features can be handled by the HAL drivers in five different ways. They are described below.
Adding a part number-specific function When a new feature specific to a given device is required, the new APIs are added in the stm32c0xx_hal_ppp_ex.c extension file. They are named HAL_PPPEx_Function().
Figure 2. Adding device-specific functions

Example: stm32c0xx_hal_pwr_ex.c/h #if defined(PWR_SHDW_SUPPORT) void HAL_PWREx_EnterSHUTDOWNMode(void); #endif
Adding a family-specific function In this case, the API is added in the extension driver C file and named HAL_PPPEx_Function ().
Figure 3. Adding family-specific functions

Adding a new peripheral (specific to a device belonging to a given family)
When a peripheral which is available only in a specific device is required, the APIs corresponding to this new peripheral/module (newPPP) are added in a new stm32c0xx_hal_newppp.c. However the inclusion of this file is selected in the stm32c0xx_hal_conf.h using the macro:

define HAL_NEWPPP_MODULE_ENABLED

UM3029 – Rev 1

page 16/1419

Figure 4. Adding new peripherals

UM3029
HAL extension APIs

Example: stm32c0xx_hal_adc.c/h
Updating existing common APIs In this case, the routines are defined with the same names in the stm32c0xx_hal_ppp_ex.c extension file, while the generic API is defined as weak, so that the compiler overwrites the original routine by the new defined function.
Figure 5. Updating existing APIs

Updating existing data structures
The data structure for a specific device part number (for example PPP_InitTypeDef) can have different fields. In this case, the data structure is defined in the extension header file and delimited by the specific part number define statement.

UM3029 – Rev 1

page 17/1419

UM3029
File inclusion model

3.8

File inclusion model

The header of the common HAL driver file (stm32c0xx_hal.h) includes the common configurations for the whole HAL library. It is the only header file that is included in the user sources and the HAL C sources files to be able to use the HAL resources.

Figure 6. File inclusion model

A PPP driver is a standalone module which is used in a project. The user must enable the corresponding USE_HAL_PPP_MODULE define statement in the configuration file.
/ @file stm32c0xx_hal_conf.h @author MCD Application Team @version VX.Y.Z @date dd-mm-yyyy @brief This file contains the modules to be used ** (…)

define HAL_USART_MODULE_ENABLED #define HAL_IRDA_MODULE_ENABLED #define

HAL_DMA_MODULE_ENABLED #define HAL_RCC_MODULE_ENABLED (…)

UM3029 – Rev 1

page 18/1419

3.9 3.10

UM3029
HAL common resources

HAL common resources
The common HAL resources, such as common define enumerations, structures and macros, are defined in stm32c0xx_hal_def.h.The main common define enumeration is HAL_StatusTypeDef.
· HAL Status The HAL status is used by almost all HAL APIs, except for boolean functions and IRQ handler. It returns the status of the current API operations. It has four possible values as described below:
Typedef enum { HAL_OK = 0x00, HAL_ERROR = 0x01, HAL_BUSY = 0x02, HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef;
· HAL Locked The HAL lock is used by all HAL APIs to prevent accessing by accident shared resources.
typedef enum { HAL_UNLOCKED = 0x00, /!<Resources unlocked / HAL_LOCKED = 0x01 /!< Resources locked / } HAL_LockTypeDef;
In addition to common resources, the stm32c0xx_hal_def.h file calls the stm32c0xx.h file in CMSIS library to get the data structures and the address mapping for all peripherals:
­ Declarations of peripheral registers and bits definition. ­ Macros to access peripheral registers hardware (such as Write register or Read register). · Common macros ­ Macro defining HAL_MAX_DELAY

define HAL_MAX_DELAY 0xFFFFFFFF

­ Macro linking a PPP peripheral to a DMA structure pointer:

define HAL_LINKDMA(HANDLE, __PPP_DMAFIELD, DMAHANDLE) do{

(HANDLE)->__PPP_DMAFIELD = &(DMAHANDLE); (DMAHANDLE).Parent = (HANDLE); } while(0)

HAL configuration
The configuration file, stm32c0xx_hal_conf.h, allows customizing the drivers for the user application. Modifying this configuration is not mandatory: the application can use the default configuration without any modification.
To configure these parameters, the user should enable, disable or modify some options by uncommenting, commenting or modifying the values of the related define statements as described in the table below:

Table 11. Define statements used for HAL configuration

Configuration item HSE_VALUE
HSE_STARTUP_TIMEOUT HSI_VALUE
HSI48_VALUE
LSI_VALUE

Description
Defines the value of the external oscillator (HSE) expressed in Hz. The user must adjust this define statement when using a different crystal value.
Timeout for HSE start-up, expressed in ms
Defines the value of the internal oscillator (HSI) expressed in Hz.
Defines the value of the Internal High Speed oscillator for USB expressed in Hz. The real value may vary depending on the variations in voltage and temperature.
Defines the default value of the Low-speed internal oscillator (LSI) expressed in Hz.

Default Value 48 000 000 Hz
100 48 000 000 Hz 48 000 000 Hz
32000 Hz

UM3029 – Rev 1

page 19/1419

Note:
3.11
3.11.1
3.11.2

UM3029
HAL system peripheral handling

Configuration item
LSE_VALUE LSE_STARTUP_TIMEOUT
VDD_VALUE

Description
Defines the value of the external oscillator (LSE) expressed in Hz. The user must adjust this define statement when using a different crystal value.
Timeout for LSE start-up, expressed in ms
VDD value

USE_RTOS

Enables the use of RTOS

PREFETCH_ENABLE

Enables prefetch feature

INSTRUCTION_CACHE_ENABLE Enables ICACHE feature

Default Value
32768 Hz
5000 3300 (mV) FALSE (for future
use) FALSE TRUE

The stm32c0xx_hal_conf_template.h file is located in the HAL drivers Inc folder. It should be copied to the user folder, renamed and modified as described above. By default, the values defined in the stm32c0xx_hal_conf_template.h file are the same as the ones used for the examples and demonstrations. All HAL include files are enabled so that they can be used in the user code without modifications.

HAL system peripheral handling
This section gives an overview of how the system peripherals are handled by the HAL drivers. The full API list is provided within each peripheral driver description section.

Clocks Two main functions can be used to configure the system clock:
· HAL_RCC_OscConfig (RCC_OscInitTypeDef RCC_OscInitStruct). This function configures/enables multiple clock sources (HSE, HSI, LSE, LSI).
· HAL_RCC_ClockConfig (RCC_ClkInitTypeDef
RCC_ClkInitStruct, uint32_t FLatency). This function
­ selects the system clock source ­ configures AHB and APB1 clock dividers ­ configures the number of Flash memory wait states ­ updates the SysTick configuration when HCLK clock changes.
Some peripheral clocks are not derived from the system clock (such as RTC). In this case, the clock configuration is performed by an extended API defined in stm32c0xx_hal_rcc_ex.c: HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit). Additional RCC HAL driver functions are available:
· HAL_RCC_DeInit() Clock de-initialization function that returns clock configuration to reset state · Get clock functions that allow retreiving various clock configurations (such as system clock, HCLK or
PCLK1) · MCO and CSS configuration functions
A set of macros are defined in stm32c0xx_hal_rcc.h and stm32c0xx_hal_rcc_ex.h. They allow executing elementary operations on RCC block registers, such as peripherals clock gating/reset control:
· HAL_PPP_CLK_ENABLE/__HAL_PPP_CLK_DISABLE to enable/disable the peripheral clock · HAL_PPP_FORCE_RESET/HAL_PPP_RELEASE_RESET to force/release peripheral reset · HAL_PPP_CLK_SLEEP_ENABLE/HAL_PPP_CLK_SLEEP_DISABLE to enable/disable the peripheral
clock during Sleep mode. · HAL_PPP_IS_CLK_ENABLED/HAL_PPP_IS_CLK_DISABLED to query about the enabled/disabled
status of the peripheral clock. · __HAL_PPP_IS_CLK_SLEEP_ENABLED/
HAL_PPP_IS_CLK_SLEEP_DISABLED to query about the
enabled/disabled status of the peripheral clock during Sleep mode.

GPIOs GPIO HAL APIs are the following:

UM3029 – Rev 1

page 20/1419

UM3029
HAL system peripheral handling

· HAL_GPIO_Init() / HAL_GPIO_DeInit() · HAL_GPIO_ReadPin() / HAL_GPIO_WritePin() · HAL_GPIO_TogglePin ().
In addition to standard GPIO modes (input, output, analog), the pin mode can be configured as EXTI with interrupt or event generation. When selecting EXTI mode with interrupt generation, the user must call HAL_GPIO_EXTI_IRQHandler() from stm32c0xx_it.c and implement HAL_GPIO_EXTI_Rising_Callback() and/or HAL_GPIO_EXTI_Falling_Callback(). The table below describes the GPIO_InitTypeDef structure field.

Table 12. Description of GPIO_InitTypeDef structure

Structure field Pin
Mode
Pull Speed

Description
Specifies the GPIO pins to be configured. Possible values: GPIO_PIN_x or GPIO_PIN_All, where x[0..15] Specifies the operating mode for the selected pins: GPIO mode or EXTI mode. Possible values are: · GPIO mode
­ GPIO_MODE_INPUT : Input floating ­ GPIO_MODE_OUTPUT_PP : Output push-pull ­ GPIO_MODE_OUTPUT_OD : Output open drain ­ GPIO_MODE_AF_PP : Alternate function push-pull ­ GPIO_MODE_AF_OD : Alternate function open drain ­ GPIO_MODE_ANALOG : Analog mode ­ GPIO_MODE_ANALOG_ADC_CONTROL: ADC analog mode · External Interrupt mode ­ GPIO_MODE_IT_RISING : Rising edge trigger detection ­ GPIO_MODE_IT_FALLING : Falling edge trigger detection ­ GPIO_MODE_IT_RISING_FALLING : Rising/Falling edge trigger detection · External Event mode ­ GPIO_MODE_EVT_RISING : Rising edge trigger detection ­ GPIO_MODE_EVT_FALLING : Falling edge trigger detection ­ GPIO_MODE_EVT_RISING_FALLING: Rising/Falling edge trigger detection
Specifies the Pull-up or Pull-down activation for the selected pins. Possible values are: GPIO_NOPULL GPIO_PULLUP GPIO_PULLDOWN
Specifies the speed for the selected pins Possible values are: GPIO_SPEED_FREQ_LOW GPIO_SPEED_FREQ_MEDIUM GPIO_SPEED_FREQ_HIGH GPIO_SPEED_FREQ_VERY_HIGH

Please find below typical GPIO configuration examples:
· Configuring GPIOs as output push-pull to drive external LEDs:
GPIO_InitStruct.Pin = GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

UM3029 – Rev 1

page 21/1419

3.11.3 3.11.4 3.11.5

UM3029
HAL system peripheral handling

· Configuring PA0 as external interrupt with falling edge sensitivity:
GPIO_InitStructure.Mode = GPIO_MODE_IT_FALLING; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Pin = GPIO_PIN_0; HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);

Cortex® NVIC and SysTick timer The Cortex® HAL driver, stm32c0xx_hal_cortex.c, provides APIs to handle NVIC and SysTick. The supported APIs include: · HAL_NVIC_SetPriority()/ HAL_NVIC_SetPriorityGrouping() · HAL_NVIC_GetPriority() / HAL_NVIC_GetPriorityGrouping() · HAL_NVIC_EnableIRQ()/HAL_NVIC_DisableIRQ() · HAL_NVIC_SystemReset() · HAL_SYSTICK_IRQHandler() · HAL_NVIC_GetPendingIRQ() / HAL_NVIC_SetPendingIRQ () / HAL_NVIC_ClearPendingIRQ() · HAL_NVIC_GetActive(IRQn) · HAL_SYSTICK_Config() · HAL_SYSTICK_CLKSourceConfig() · HAL_SYSTICK_Callback()
PWR The PWR HAL driver handles power management. The features shared between all STM32 Series are listed below: · Wakeup pin configuration
­ HAL_PWR_EnableWakeUpPin() / HAL_PWR_DisableWakeUpPin() · Low-power mode entry
­ HAL_PWR_EnterSLEEPMode() ­ HAL_PWR_EnterSTANDBYMode() · STM32C0 low-power management features: ­ HAL_PWREx_EnterSHUTDOWNMode()
EXTI The EXTI is not considered as a standalone peripheral but rather as a service used by other peripheral, that are handled through EXTI HAL APIs. In addition, each peripheral HAL driver implements the associated EXTI configuration and function as macros in its header file. The first 16 EXTI lines connected to the GPIOs, are managed within the GPIO driver. The GPIO_InitTypeDef structure allows configuring an I/O as external interrupt or external event. The EXTI lines connected internally to the RTC, I2C1, and USART1, are configured within the HAL drivers of these peripheral through the macros given in the table below. The EXTI internal connections depend on the targeted STM32 microcontroller (refer to the product datasheet for more details):

Table 13. Description of EXTI configuration macros

Macros HALPPP{SUBLOCK}EXTI_ENABLE_IT()
HALPPP{SUBLOCK}EXTI_DISABLE_IT() HAL PPP{SUBLOCK}EXTI_GET_FLAG()

Description Enables a given EXTI line interrupt Example: __HAL_PWR_PVD_EXTI_ENABLE_IT() Disables a given EXTI line. Example: __HAL_PWR_PVD_EXTI_DISABLE_IT() Gets a given EXTI line interrupt flag pending bit status.

UM3029 – Rev 1

page 22/1419

3.11.6

UM3029
HAL system peripheral handling

Macros
HAL PPP{SUBLOCK}_EXTI_CLEAR_FLAG()
_HAL PPP_{SUBLOCK}_EXTI_GENERATE_SWIT()
HAL_PPP_SUBBLOCK_EXTI_ENABLE_EVENT()
HAL_PPP_SUBBLOCK_EXTI_DISABLE_EVENT() HAL_ PPP_SUBBLOCK_EXTI_ENABLE_RISING_EDGE() HAL_ PPP_SUBBLOCK_EXTI_ENABLE_FALLING_EDGE() HAL_ PPP_SUBBLOCK_EXTI_DISABLE_RISING_EDGE() HAL_ PPP_SUBBLOCK_EXTI_DISABLE_FALLING_EDGE() _HAL PPP_SUBBLOCK_EXTI_ENABLE_RISING_FALLING_EDGE() HAL_ PPP_SUBBLOCK_EXTI_DISABLE_RISING_FALLING_EDGE()

Example:

Description

__HAL_PWR_PVD_EXTI_GET_FLAG()

Clears a given EXTI line interrupt flag pending bit. Example; __HAL_PWR_PVD_EXTI_CLEAR_FLAG()

Generates a software interrupt for a given EXTI line. Example: __HAL_PWR_PVDEXTI GENERATE_SWIT ()

Enable a given EXTI line event Example: __HAL_RTC_WAKEUP_EXTI_ENABLE_EVENT()

Disable a given EXTI line event Example: __HAL_RTC_WAKEUP_EXTI_DISABLE_EVENT()

Configure an EXTI Interrupt or Event on rising edge

Enable an EXTI Interrupt or Event on Falling edge

Disable an EXTI Interrupt or Event on rising edge

Disable an EXTI Interrupt or Event on Falling edge

Enable an EXTI Interrupt or Event on Rising/Falling edge

Disable an EXTI Interrupt or Event on Rising/Falling edge

If the EXTI interrupt mode is selected, the user application must call HAL_PPP_FUNCTION_IRQHandler() (for example HAL_PWR_PVD_IRQHandler()), from stm32c0xx_it.c file, and implement HAL_PPP_FUNCTIONCallback() callback function (for example HAL_PWR_PVDCallback().
DMA The DMA HAL driver allows enabling and configuring the peripheral to be connected to the DMA Channels (except for internal SRAM/FLASH memory which do not require any initialization). Refer to the product reference manual for details on the DMA request corresponding to each peripheral. For a given channel, HAL_DMA_Init() API allows programming the required configuration through the following parameters: · Transfer direction · Source and destination data formats · Circular, Normal control mode · Channel priority level · Source and destination Increment mode · Hardware request connected to the peripheral
Two operating modes are available: · Polling mode I/O operation
1. Use HAL_DMA_Start() to start DMA transfer when the source and destination addresses and the Length of data to be transferred have been configured.
2. Use HAL_DMA_PollForTransfer() to poll for the end of current transfer. In this case a fixed timeout can be configured depending on the user application.

UM3029 – Rev 1

page 23/1419

Note: Note:
3.12
3.12.1

UM3029
How to use HAL drivers
· Interrupt mode I/O operation 1. Configure the DMA interrupt priority using HAL_NVIC_SetPriority(). 2. Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ(). 3. Use HAL_DMA_Start_IT() to start DMA transfer when the source and destination addresses and the length of data to be transferred have been configured. In this case the DMA interrupt is configured. 4. Use HAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine. 5. When data transfer is complete, HAL_DMA_IRQHandler() function is executed and a user function can be called by customizing XferCpltCallback and XferErrorCallback function pointer (that is a member of DMA handle structure).
Additional functions and macros are available to ensure efficient DMA management: · Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error
detection. · Use HAL_DMA_Abort() function to abort the current transfer. The most used DMA HAL driver macros are the following: · HAL_DMA_ENABLE: enables the specified DMA channel · HAL_DMA_DISABLE: disables the specified DMA channel · HAL_DMA_GET_FLAG: gets the DMA channel pending flags · __HAL_DMA_CLEAR_FLAG: clears the DMA channel pending flags · HAL_DMA_ENABLE_IT: enables the specified DMA channel interrupts · __HAL_DMA_DISABLE_IT: disables the specified DMA channel interrupts · __HAL_DMA_GET_IT_SOURCE: checks whether the specified DMA channel interrupt has been enabled or
not When a peripheral is used in DMA mode, the DMA initialization must be done in the HAL_PPP_MspInit() callback. In addition, the user application must associate the DMA handle to the PPP handle (refer to section “HAL IO operation functions”). DMA channel callbacks need to be initialized by the user application only in case of memory-to-memory transfer. However when peripheral-to-memory transfers are used, these callbacks are automatically initialized by calling a process API function that uses the DMA.
How to use HAL drivers
HAL usage models The following figure shows the typical use of the HAL driver and the interaction between the application user, the HAL driver and the interrupts.

UM3029 – Rev 1

page 24/1419

stm32c0xxx_it.c
DMAx_IRQHandler or
PPP_IRQHandler

UM3029
How to use HAL drivers

Figure 7. HAL driver model

hal_msp.c app.c/main.c
1. Declare PPP handle 2. Init handle Params 3. Call HAL_PPP_init()
HAL_PPP_Mspinit()

stm32c0xxx_hal_ppp.c

Services

stm32c0xx_hal_gpio.c/h

HAL_PPP_Init()

stm32c0xx_hal_rcc.c/h stm32c0xx_hal_nvic.c/h

Calll HAL_PPP_Process()

HAL_PPP_Process()

stm32c0xx_hal_dma.c/h

Interrupt model

DMA model

Hal_PPP_ProcessCpltCallBack() Hal_PPP_ErrorCallBack()

Calll HAL_PPP_DeInit() HAL_PPP_MspDeinit()

HAL_PPP_DeInit()

Note:
3.12.2 3.12.2.1

The functions implemented in the HAL driver are shown in green, the functions called from interrupt handlers in dotted lines, and the msp functions implemented in the user application in red. Non-dotted lines represent the interactions between the user application functions. Basically, the HAL driver APIs are called from user files and optionally from interrupt handlers file when the APIs based on the DMA or the PPP peripheral dedicated interrupts are used. When DMA or PPP peripheral interrupts are used, the PPP process complete callbacks are called to inform the user about the process completion in real- time event mode (interrupts). Note that the same process completion callbacks are used for DMA in interrupt mode.
HAL initialization
HAL global initialization In addition to the peripheral initialization and de- initialization functions, a set of APIs are provided to initialize the HAL core implemented in file stm32c0xx_hal.c. · HAL_Init(): this function must be called at application startup to
­ initialize data/instruction cache and pre-fetch queue ­ set SysTick timer to generate an interrupt each 1ms (based on HSI clock) with the lowest priority ­ call HAL_MspInit() user callback function to perform system level initializations (Clock, GPIOs, DMA,
interrupts). HAL_MspInit() is defined as “weak” empty function in the HAL drivers. · HAL_DeInit()
­ resets all peripherals ­ calls function HAL_MspDeInit() which is a user callback function to do system level De-Initalizations.

UM3029 – Rev 1

page 25/1419

UM3029
How to use HAL drivers

3.12.2.2 3.12.2.3

· HAL_GetTick(): this function gets current SysTick counter value (incremented in SysTick interrupt) used by peripherals drivers to handle timeouts.
· HAL_Delay(). this function implements a delay (expressed in milliseconds) using the SysTick timer.
Care must be taken when using HAL_Delay() since this function provides an accurate delay (expressed in milliseconds) based on a variable incremented in SysTick ISR. This means that if HAL_Delay() is called from a peripheral ISR, then the SysTick interrupt must have highest priority (numerically lower) than the peripheral interrupt, otherwise the caller ISR is blocked.
System clock initialization The clock configuration is done at the beginning of the user code. However the user can change the configuration of the clock in his own code.
Below the typical clock configuration sequence to reach the maximum clock frequency of 48 MHz based on the HSE clock.
/* @brief System Clock Configuration @retval None /
void SystemClock_Config(void) {
RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/ Initializes the RCC Oscillators according to the specified parameters in the RCC_OscInitTypeDef structure. / RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler(); } /
Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI; RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) {
Error_Handler(); } }
HAL MSP initialization process The peripheral initialization is done through HAL_PPP_Init() while the hardware resources initialization used by a peripheral (PPP) is performed during this initialization by calling MSP callback function HAL_PPP_MspInit().
The MspInit callback performs the low level initialization related to the different additional hardware resources: RCC, GPIO, NVIC and DMA.
All the HAL drivers with handles include two MSP callbacks for initialization and de-initialization:

UM3029 – Rev 1

page 26/1419

UM3029
How to use HAL drivers

3.12.3 3.12.3.1

/* @brief Initializes the PPP MSP. @param hppp: PPP handle @retval None / void __weak HAL_PPP_MspInit(PPP_HandleTypeDef hppp) { / NOTE : This function Should not be modified, when the callback is needed, the HAL_PPP_MspInit could be implemented in the user file / } /* @brief DeInitializes PPP MSP. @param hppp: PPP handle @retval None / void __weak HAL_PPP_MspDeInit(PPP_HandleTypeDef hppp) { / NOTE : This function Should not be modified, when the callback is needed, the HAL_PPP_MspDeInit could be implemented in the user file / }
The MSP callbacks are declared empty as weak functions in each peripheral driver. The user can use them to set the low level initialization code or omit them and use his own initialization routine. The HAL MSP callback is implemented inside the stm32c0xx_hal_msp.c file in the user folders. An stm32c0xx_hal_msp.c file template is located in the HAL folder and should be copied to the user folder. It can be generated automatically by STM32CubeMX tool and further modified. Note that all the routines are declared as weak functions and could be overwritten or removed to use user low level initialization code. stm32c0xx_hal_msp.c file contains the following functions:

Routine void HAL_MspInit() void HAL_MspDeInit() void HAL_PPP_MspInit() void HAL_PPP_MspDeInit()

Table 14. MSP functions Description
Global MSP initialization routine Global MSP de-initialization routine
PPP MSP initialization routine PPP MSP de-initialization routine

By default, if no peripheral needs to be de-initialized during the program execution, the whole MSP initialization is done in Hal_MspInit() and MSP De- Initialization in the Hal_MspDeInit(). In this case the HAL_PPP_MspInit() and HAL_PPP_MspDeInit() are not implemented. When one or more peripherals needs to be de-initialized in run time and the low level resources of a given peripheral need to be released and used by another peripheral, HAL_PPP_MspDeInit() and HAL_PPP_MspInit() are implemented for the concerned peripheral and other peripherals initialization and de-Initialization are kept in the global HAL_MspInit() and the HAL_MspDeInit(). If there is nothing to be initialized by the global HAL_MspInit() and HAL_MspDeInit(), the two routines can simply be omitted.
HAL I/O operation process The HAL functions with internal data processing like transmit, receive, write and read are generally provided with three data processing modes as follows: · Polling mode · Interrupt mode · DMA mode
Polling mode In Polling mode, the HAL functions return the process status when the data processing in blocking mode is complete. The operation is considered complete when the function returns the HAL_OK status, otherwise an error status is returned. The user can get more information through the HAL_PPP_GetState() function. The data processing is handled internally in a loop. A timeout (expressed in ms) is used to prevent process hanging. The example below shows the typical Polling mode processing sequence :

UM3029 – Rev 1

page 27/1419

UM3029
How to use HAL drivers

3.12.3.2

HAL_StatusTypeDef HAL_PPP_Transmit ( PPP_HandleTypeDef phandle, uint8_t pData, int16_tSize,uint32_tTimeout) { if((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } (…) while (data processing is running) { if( timeout reached ) { return HAL_TIMEOUT; } } (…) return HAL_OK; }
Interrupt mode
In Interrupt mode, the HAL function returns the process status after starting the data processing and enabling the appropriate interruption. The end of the operation is indicated by a callback declared as a weak function. It can be customized by the user to be informed in real-time about the process completion. The user can also get the process status through the HAL_PPP_GetState() function.
In Interrupt mode, four functions are declared in the driver: · HAL_PPP_Process_IT(): launches the process · HAL_PPP_IRQHandler(): global PPP peripheral interruption · weak HAL_PPP_ProcessCpltCallback (): callback relative to the process completion. · weak HAL_PPP_ProcessErrorCallback(): callback relative to the process Error. To use a process in Interrupt mode, HAL_PPP_Process_IT() is called in the user file and HAL_PPP_IRQHandler in stm32c0xx_it.c. The HAL_PPP_ProcessCpltCallback() function is declared as weak function in the driver. This means that the user can declare it again in the application. The function in the driver is not modified.
An example of use is illustrated below: main.c file:
UART_HandleTypeDef UartHandle; int main(void) { /
Set User Parameters / UartHandle.Init.BaudRate = 9600; UartHandle.Init.WordLength = UART_DATABITS_8; UartHandle.Init.StopBits = UART_STOPBITS_1; UartHandle.Init.Parity = UART_PARITY_NONE; UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE; UartHandle.Init.Mode = UART_MODE_TX_RX; UartHandle.Init.Instance = USART1; HAL_UART_Init(&UartHandle); HAL_UART_SendIT(&UartHandle, TxBuffer, sizeof(TxBuffer)); while (1); } void HAL_UART_TxCpltCallback(UART_HandleTypeDef huart) { } void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) { }

UM3029 – Rev 1

page 28/1419

3.12.3.3

UM3029
How to use HAL drivers
stm32c0xx_it.cfile:
extern UART_HandleTypeDef UartHandle; void USART1_IRQHandler(void) { HAL_UART_IRQHandler(&UartHandle); }
DMA mode In DMA mode, the HAL function returns the process status after starting the data processing through the DMA and after enabling the appropriate DMA interruption. The end of the operation is indicated by a callback declared as a weak function and can be customized by the user to be informed in real-time about the process completion. The user can also get the process status through the HAL_PPP_GetState() function. For the DMA mode, three functions are declared in the driver: · HAL_PPP_Process_DMA(): launch the process · HAL_PPP_DMA_IRQHandler(): the DMA interruption used by the PPP peripheral · weak HAL_PPP_ProcessCpltCallback(): the callback relative to the process completion. · weak HAL_PPP_ErrorCpltCallback(): the callback relative to the process Error. To use a process in DMA mode, HAL_PPP_Process_DMA() is called in the user file and the HAL_PPP_DMA_IRQHandler() is placed in the stm32c0xx_it.c. When DMA mode is used, the DMA initialization is done in the HAL_PPP_MspInit() callback. The user should also associate the DMA handle to the PPP handle. For this purpose, the handles of all the peripheral drivers that use the DMA must be declared as follows:
typedef struct { PPP_TypeDef Instance; / Register base address / PPP_InitTypeDef Init; / PPP communication parameters / HAL_StateTypeDef State; / PPP communication state / (…) DMA_HandleTypeDef hdma; / associated DMA handle / } PPP_HandleTypeDef;
The initialization is done as follows (UART example):
int main(void) { / Set User Parameters / UartHandle.Init.BaudRate = 9600; UartHandle.Init.WordLength = UART_DATABITS_8; UartHandle.Init.StopBits = UART_STOPBITS_1; UartHandle.Init.Parity = UART_PARITY_NONE; UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE; UartHandle.Init.Mode = UART_MODE_TX_RX; UartHandle.Init.Instance = UART1; HAL_UART_Init(&UartHandle); (..) } void HAL_USART_MspInit (UART_HandleTypeDef * huart) { static DMA_HandleTypeDef hdma_tx; static DMA_HandleTypeDef hdma_rx; (…) HAL_LINKDMA(UartHandle, DMA_Handle_tx, hdma_tx); HAL_LINKDMA(UartHandle, DMA_Handle_rx, hdma_rx); (…) }
The HAL_PPP_ProcessCpltCallback() function is declared as weak function in the driver that means, the user can declare it again in the application code. The function in the driver should not be modified. An example of use is illustrated below:

UM3029 – Rev 1

page 29/1419

3.12.4 3.12.4.1

UM3029
How to use HAL drivers

main.c file:
UART_HandleTypeDef UartHandle; int main(void) { / Set User Paramaters / UartHandle.Init.BaudRate = 9600; UartHandle.Init.WordLength = UART_DATABITS_8; UartHandle.Init.StopBits = UART_STOPBITS_1; UartHandle.Init.Parity = UART_PARITY_NONE; UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE; UartHandle.Init.Mode = UART_MODE_TX_RX; UartHandle.Init.Instance = USART1; HAL_UART_Init(&UartHandle); HAL_UART_Send_DMA(&UartHandle, TxBuffer, sizeof(TxBuffer)); while (1); } void HAL_UART_TxCpltCallback(UART_HandleTypeDef phuart) { } void HAL_UART_TxErrorCallback(UART_HandleTypeDef phuart) { }
stm32c0xx_it.c file:
extern UART_HandleTypeDef UartHandle; void DMAx_IRQHandler(void) { HAL_DMA_IRQHandler(&UartHandle.DMA_Handle_tx); }
HAL_USART_TxCpltCallback() and HAL_USART_ErrorCallback() should be linked in the HAL_PPP_Process_DMA() function to the DMA transfer complete callback and the DMA transfer Error callback by using the following statement:
HAL_PPP_Process_DMA (PPP_HandleTypeDef *hppp, Params….) { (…) hppp->DMA_Handle->XferCpltCallback = HAL_UART_TxCpltCallback ; hppp->DMA_Handle->XferErrorCallback = HAL_UART_ErrorCallback ; (…) }

Timeout and error management
Timeout management The timeout is often used for the APIs that operate in Polling mode. It defines the delay during which a blocking process should wait till an error is returned. An example is provided below: HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout)
The timeout possible values are the following:

Table 15. Timeout values

Timeout value

Description

0

No poll : Immediate process check and exit

1 … (HAL_MAX_DELAY -1) (1)

Timeout in ms

HAL_MAX_DELAY

Infinite poll till process is successful

1. HAL_MAX_DELAY is defined in the stm32c0xx_hal_def.h as 0xFFFFFFFF

However, in some cases, a fixed timeout is used for system peripherals or internal HAL driver processes. In these cases, the timeout has the same meaning and is used in the same way, except when it is defined locally in the drivers and cannot be modified or introduced as an argument in the user application.

UM3029 – Rev 1

page 30/1419

UM3029
How to use HAL drivers

3.12.4.2

Example of fixed timeout:

define LOCAL_PROCESS_TIMEOUT 100 HAL_StatusTypeDef

HAL_PPP_Process(PPP_HandleTypeDef) { (…) timeout = HAL_GetTick() + LOCAL_PROCESS_TIMEOUT; (…) while(ProcessOngoing) { (…) if(HAL_GetTick() timeout) { / Process unlocked / __HAL_UNLOCK(hppp); hppp->State= HAL_PPP_STATE_TIMEOUT; return HAL_PPP_STATE_TIMEOUT; } } (…) }
The following example shows how to use the timeout inside the polling functions:
HAL_PPP_StateTypeDef HAL_PPP_Poll (PPP_HandleTypeDef hppp, uint32_t Timeout) { (…) timeout = HAL_GetTick() + Timeout; (…) while(ProcessOngoing) { (…) if(Timeout != HAL_MAX_DELAY) { if(HAL_GetTick() timeout) { / Process unlocked / __HAL_UNLOCK(hppp); hppp->State= HAL_PPP_STATE_TIMEOUT; return hppp->State; } } (…) }
Error management
The HAL drivers implement a check on the following items:
· Valid parameters: for some process the used parameters should be valid and already defined, otherwise the system may crash or go into an undefined state. These critical parameters are checked before being used (see example below).
HAL_StatusTypeDef HAL_PPP_Process(PPP_HandleTypeDef
hppp, uint32_t *pdata, uint32 Size) { if ((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } }

UM3029 – Rev 1

page 31/1419

UM3029
How to use HAL drivers

3.12.4.3

· Valid handle: the PPP peripheral handle is the most important argument since it keeps the PPP driver vital parameters. It is always checked in the beginning of the HAL_PPP_Init() function.
HAL_StatusTypeDef HAL_PPP_Init(PPP_HandleTypeDef hppp) { if (hppp == NULL) //the handle should be already allocated { return HAL_ERROR; } }
· Timeout error: the following statement is used when a timeout error occurs:
while (Process ongoing) { timeout = HAL_GetTick() + Timeout; while (data processing is running) { if(timeout) { return HAL_TIMEOUT; } }
When an error occurs during a peripheral process, HAL_PPP_Process () returns with a HAL_ERROR status. The HAL PPP driver implements the HAL_PPP_GetError () to allow retrieving the origin of the error.
HAL_PPP_ErrorTypeDef HAL_PPP_GetError (PPP_HandleTypeDef
hppp);
In all peripheral handles, a HAL_PPP_ErrorTypeDef is defined and used to store the last error code.
typedef struct { PPP_TypeDef Instance; / PPP registers base address / PPP_InitTypeDef Init; / PPP initialization parameters / HAL_LockTypeDef Lock; / PPP locking object / __IO HAL_PPP_StateTypeDef State; / PPP state / __IO HAL_PPP_ErrorTypeDef ErrorCode; / PPP Error code / (…) / PPP specific parameters / } PPP_HandleTypeDef;
The error state and the peripheral global state are always updated before returning an error: PPP->State = HAL_PPP_READY; /
Set the peripheral ready / PP->ErrorCode = HAL_ERRORCODE ; / Set the error code / _HAL_UNLOCK(PPP) ; / Unlock the PPP resources / return HAL_ERROR; /return with HAL error /
HAL_PPP_GetError () must be used in interrupt mode in the error callback:
void HAL_PPP_ProcessCpltCallback(PPP_HandleTypeDef
hspi) { ErrorCode = HAL_PPP_GetError (hppp); / retreive error code / }
Run-time checking The HAL implements run-time failure detection by checking the input values of all HAL driver functions. The run-time checking is achieved by using an assert_param macro. This macro is used in all the HAL driver functions which have an input parameter. It allows verifying that the input value lies within the parameter allowed values. To enable the run-time checking, use the assert_param macro, and leave the define USE_FULL_ASSERT uncommented in stm32c0xx_hal_conf.h file.

UM3029 – Rev 1

page 32/1419

UM3029
How to use HAL drivers

void HAL_UART_Init(UART_HandleTypeDef huart) { (..) / Check the parameters */ assert_param(IS_UART_INSTANCE(huart->Instance)); assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); assert_param(IS_UART_STOPBITS(huart->Init.StopBits)); assert_param(IS_UART_PARITY(huart->Init.Parity)); assert_param(IS_UART_MODE(huart->Init.Mode)); assert_param(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl)); (..)

Attention:

/* @defgroup UART_Word_Length @{ */ #define UART_WORDLENGTH_8B ((uint32_t)0x00000000) #define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M)

define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) ||

((LENGTH) == UART_WORDLENGTH_9B))
If the expression passed to the assert_param macro is false, theassert_failed function is called and returns the name of the source file and the source line number of the call that failed. If the expression is true, no value is returned. The assert_param macro is implemented in stm32c0xx_hal_conf.h:
/ Exported macro ————————————————————/ #ifdef USE_FULL_ASSERT /* @brief The assert_param macro is used for function’s parameters check. @param expr: If expr is false, it calls assert_failed function which reports the name of the source file and the source line number of the call that failed. If expr is true, it returns no value. @retval None / #define assert_param(expr) ((expr)?(void)0:assert_failed((uint8_t )FILE, LINE)) / Exported functions ————————————–/ void assert_failed(uint8_t file, uint32_t line); #else #define assert_param(expr)((void)0) #endif / USE_FULL_ASSERT /
The assert_failed function is implemented in the main.c file or in any other user C file:

ifdef USE_FULL_ASSERT /* @brief Reports the name of the source file and

the source line number where the assert_param error has occurred. @param file: pointer to the source file name @param line: assert_param error line source number @retval None / void assert_failed(uint8_t file, uint32_t line) { / User can add his own implementation to report the file name and line number, ex: printf(“Wrong parameters value: file %s on line %drn”, file, line) / / Infinite loop / while (1) { } }
Because of the overhead run-time checking introduces, it is recommended to use it during application code development and debugging, and to remove it from the final application to improve code size and speed.

UM3029 – Rev 1

page 33/1419

4
4.1
Note:

UM3029
Overview of low-layer drivers

Overview of low-layer drivers

The low-layer (LL) drivers are designed to offer a fast light-weight expert- oriented layer which is closer to the hardware than the HAL. Contrary to the HAL, LL APIs are not provided for peripherals where optimized access is not a key feature, or those requiring heavy software configuration and/or complex upper-level stack (such as USB). The LL drivers feature:
· A set of functions to initialize peripheral main features according to the parameters specified in data structures
· A set of functions used to fill initialization data structures with the reset values of each field · Functions to perform peripheral de-initialization (peripheral registers restored to their default values) · A set of inline functions for direct and atomic register access · Full independence from HAL since LL drivers can be used either in standalone mode (without HAL drivers)
or in mixed mode (with HAL drivers) · Full coverage of the supported peripheral features
The low-layer drivers provide hardware services based on the available features of the STM32 peripherals. These services reflect exactly the hardware capabilities and provide one-shot operations that must be called following the programming model described in the microcontroller line reference manual. As a result, the LL services do not implement any processing and do not require any additional memory resources to save their states, counter or data pointers: all the operations are performed by changing the associated peripheral registers content.
Low-layer files
The low-layer drivers are built around header/C files (one per each supported peripheral) plus five header files for some System and Cortex related features.

Table 16. LL driver files

File

Description

stm32c0xx_ll_bus.h

This is the h-source file for core bus control and peripheral clock activation and deactivation Example: LL_AHB1_GRP1_EnableClock

stm32c0xx_ll_ppp.h/.c

stm32c0xx_ll_ppp.c provides peripheral initialization functions such as LL_PPP_Init(), LL_PPP_StructInit(), LL_PPP_DeInit(). All the other APIs are definined within stm32c0xx_ll_ppp.h file.
The low-layer PPP driver is a standalone module. To use it, the application must include it in the stm32c0xx_ll_ppp.h file.

stm32c0xx_ll_cortex.h

Cortex-M related register operation APIs including the Systick, Low power (such as LL_SYSTICK_xxxxx and LL_LPM_xxxxx “Low Power Mode”)

stm32c0xx_ll_utils.h/.c

This file covers the generic APIs: · Read of device unique ID and electronic signature · Timebase and delay management · System clock configuration.

System related operations. stm32c0xx_ll_system.h
Example: LL_SYSCFG_xxx, LL_DBGMCU_xxx and LL_FLASH_xxx

Template file allowing to define the assert_param macro, that is used when run-time checking is enabled. stm32_assert_template.h This file is required only when the LL drivers are used in standalone mode (without calling the HAL APIs). It should be copied to the application folder and renamed to stm32_assert.h.

There is no configuration file for the LL drivers. The low-layer files are located in the same HAL driver folder.

UM3029 – Rev 1

page 34/1419

Figure 8. Low-layer driver folders

UM3029
Low-layer files

In general, low-layer drivers include only the STM32 CMSIS device file.

include “stm32yyxx.h”

UM3029 – Rev 1

page 35/1419

UM3029
Overview of low-layer APIs and naming rules
Figure 9. Low-layer driver CMSIS files

4.2
4.2.1

Application files have to include only the used low-layer driver header files.
Overview of low-layer APIs and naming rules
Peripheral initialization functions The LL drivers offer three sets of initialization functions. They are defined in stm32c0xx_ll_ppp.c file: · Functions to initialize peripheral main features according to the parameters specified in data structures · A set of functions used to fill initialization data structures with the reset values of each field · Function for peripheral de-initialization (peripheral registers restored to their default values) The definition of these LL initialization functions and associated resources (structure, literals and prototypes) is conditioned by a compilation switch: USE_FULL_LL_DRIVER. To use these functions, this switch must be added in the toolchain compiler preprocessor or to any generic header file which is processed before the LL drivers. The below table shows the list of the common functions provided for all the supported peripherals:

UM3029 – Rev 1

page 36/1419

UM3029
Overview of low-layer APIs and naming rules

Table 17. Common peripheral initialization functions

Functions LL_PPP_Init

Return Type
· ErrorStatus ·

LL_PPP_StructInit

void

·

LL_PPP_DeInit ErrorStatus ·

Parameters

Description

PPP_TypeDef PPPx LL_PPP_InitTypeDef PPP_InitStruct LL_PPP_InitTypeDef PPP_InitStruct
PPP_TypeDef
PPPx

Initializes the peripheral main features according to the parameters specified in PPP_InitStruct.
Example: LL_USART_Init(USART_TypeDef USARTx, LL_USART_InitTypeDef USART_InitStruct)
Fills each PPP_InitStruct member with its default value.
Example. LL_USART_StructInit(LL_USART_InitTypeDef USART_InitStruct)
De-initializes the peripheral registers, that is restore them to their default reset values.
Example. LL_USART_DeInit(USART_TypeDef
USARTx)

Additional functions are available for some peripherals (refer to Table 18. Optional peripheral initialization functions ).

Table 18. Optional peripheral initialization functions

Functions

Return Type

Parameters

Examples
Initializes peripheral features according to the parameters specified in PPP_InitStruct.

LL_PPP{_CATEGORY}_Init

· ErrorStatus ·

Example:
LL_ADC_INJ_Init(ADC_TypeDef ADCx, LL_ADC_INJ_InitTypeDef ADC_INJ_InitStruct)

PPP_TypeDef PPPx LL_PPP{_CATEGORY}_InitTypeDef PPP{_CATEGORY}_InitStruct

LL_RTC_TIME_Init(RTC_TypeDef RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef RTC_TimeStruct)
LL_RTC_DATE_Init(RTC_TypeDef RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef RTC_DateStruct)

LL_TIM_IC_Init(TIM_TypeDef TIMx, uint32_t Channel, LL_TIM_IC_InitTypeDef TIM_IC_InitStruct)

LL_PPP{_CATEGORY}_StructInit

void

LL_PPP{_CATEGORY}_InitTypeDef* PPP{_CATEGORY}_InitStruct

LL_PPP_CommonInit

· ErrorStatus ·

PPP_TypeDef PPPx LL_PPP_CommonInitTypeDef PPP_CommonInitStruct

LL_PPP_CommonStructInit

void

LL_PPP_CommonInitTypeDef* PPP_CommonInitStruct

LL_PPP_ClockInit

· ErrorStatus ·

PPP_TypeDef PPPx LL_PPP_ClockInitTypeDef PPP_ClockInitStruct

LL_TIM_ENCODER_Init(TIM_TypeDef TIMx, LL_TIM_ENCODER_InitTypeDef TIM_EncoderInitStruct)
Fills each PPP{_CATEGORY}_InitStruct member with its default value.
Example: LL_ADC_INJ_StructInit(LL_ADC_INJ_InitTypeDef ADC_INJ_InitStruct)
Initializes the common features shared between different instances of the same peripheral.
Example: LL_ADC_CommonInit(ADC_Common_TypeDef
ADCxy_COMMON, LL_ADC_CommonInitTypeDef ADC_CommonInitStruct)
Fills each PPP_CommonInitStruct member with its default value
Example: LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef
ADC_CommonInitStruct)
Initializes the peripheral clock configuration in synchronous mode.

UM3029 – Rev 1

page 37/1419

UM3029
Overview of low-layer APIs and naming rules

Functions

Return Type

LL_PPP_ClockStructInit

void

Parameters LL_PPP_ClockInitTypeDef*
PPP_ClockInitStruct

Examples
Example: LL_USART_ClockInit(USART_TypeDef USARTx, LL_USART_ClockInitTypeDef USART_ClockInitStruct)
Fills each PPP_ClockInitStruct member with its default value
Example: LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct)

4.2.1.1
Note: 4.2.2

Run-time checking Like HAL drivers, LL initialization functions implement run- time failure detection by checking the input values of all LL driver functions. For more details, refer to Section 3.12.4.3 Run-time checking. When using the LL drivers in standalone mode (without calling HAL functions), the following actions are required to use run-time checking: 1. Copy stm32_assert_template.h to the application folder and rename it to stm32_assert.h. This file defines
the assert_param macro which is used when run-time checking is enabled. 2. Include stm32_assert.h file within the application main header file. 3. Add the USE_FULL_ASSERT compilation switch in the toolchain compiler preprocessor or in any generic
header file which is processed before the stm32_assert.h driver. Run-time checking is not available for LL inline functions.
Peripheral register-level configuration functions On top of the peripheral initialization functions, the LL drivers offer a set of inline functions for direct atomic register access. Their format is as follows:
__STATIC_INLINE return_type LL_PPP_Function (PPPx_TypeDef *PPPx, args)
The “Function” naming is defined depending to the action category: · Specific Interrupt, DMA request and status flags management: Set/Get/Clear/Enable/Disable flags on
interrupt and status registers

Table 19. Specific Interrupt, DMA request and status flags management

Name
LLPPP{_CATEGORY}_ActionItem_BITNAME LL_PPP{_CATEGORY}_IsItem_BITNAME_Action

Examples
· LL_RCC_IsActiveFlag_LSIRDY · LL_RCC_IsActiveFlag_FWRST() · LL_ADC_ClearFlag_EOC(ADC1) · LL_DMA_ClearFlag_TCx(DMA_TypeDef* DMAx)

Note:

Item Flag Interrupts
DMA

Action Get Clear
Enable Disable
Get Enable Disable
Get

Table 20. Available function formats
Format LL_PPP_IsActiveFlag_BITNAME
LL_PPP_ClearFlag_BITNAME LL_PPP_EnableIT_BITNAME LL_PPP_DisableIT_BITNAME LL_PPP_IsEnabledIT_BITNAME LL_PPP_EnableDMAReq_BITNAME LL_PPP_DisableDMAReq_BITNAME LL_PPP_IsEnabledDMAReq_BITNAME

BITNAME refers to the peripheral register bit name as described in the product line reference manual.

UM3029 – Rev 1

page 38/1419

Note: Note:

UM3029
Overview of low-layer APIs and naming rules

· Peripheral clock activation/deactivation management: Enable/Disable/Reset a peripheral clock

Table 21. Peripheral clock activation/deactivation management

Name LL_BUS_GRPx_ActionClock{Mode} ·
·

Examples
LL_AHB1_GRP1_EnableClock (LL_AHB1_GRP1_PERIPH_DMA1) LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_RTC)

‘x’ corresponds to the group index and refers to the index of the modified register on a given bus. ‘bus’ corresponds to the bus name.
· Peripheral activation/deactivation management : Enable/disable a peripheral or activate/deactivate specific peripheral features

Table 22. Peripheral activation/deactivation management

Name
· LL_PPP{_CATEGORY}_Action{Item} · LL_PPP{_CATEGORY}_IsItemAction ·
· ·

Examples
LL_ADC_Enable () LL_ADC_StartCalibration(); LL_ADC_IsCalibrationOnGoing; LL_RCC_HSI_Enable () LL_RCC_HSI_IsReady()

· Peripheral configuration management : Set/get a peripheral configuration settings

Table 23. Peripheral configuration management

Name LL_PPP{_CATEGORY}_Set{ or
Get}ConfigItem

Examples LL_USART_SetBaudRate (USART2, Clock, LL_USART_BAUDRATE_9600)

· Peripheral register management : Write/read the content of a register/retrun DMA relative register address
Table 24. Peripheral register management
Name LL_PPP_WriteReg(INSTANCE, REG, VALUE)
LL_PPP_ReadReg(INSTANCE, REG) LL_PPP_DMA_GetRegAddr (PPP_TypeDef *PPPx,{Sub Instance if any ex: Channel} , {uint32_t Propriety})
The Propriety is a variable used to identify the DMA transfer direction or the data register type.

UM3029 – Rev 1

page 39/1419

5
5.1
Note:
5.2
Note:

UM3029
Cohabiting of HAL and LL
Cohabiting of HAL and LL
The low-ayer APIs are designed to be used in standalone mode or combined with the HAL. They cannot be automatically used with the HAL for the same peripheral instance. If you use the LL APIs for a specific instance, you can still use the HAL APIs for other instances. Be careful that the low-layer APIs might overwrite some registers which content is mirrored in the HAL handles.
Low-layer driver used in Standalone mode
The low-layer APIs can be used without calling the HAL driver services. This is done by simply including stm32c0xx_ll_ppp.h in the application files. The LL APIs for a given peripheral are called by executing the same sequence as the one recommended by the programming model in the corresponding product line reference manual. In this case the HAL drivers associated to the used peripheral can be removed from the workspace. However the STM32CubeC0 framework should be used in the same way as in the HAL drivers case which means that System file, startup file and CMSIS should always be used. When the BSP drivers are included, the used HAL drivers associated with the BSP functions drivers should be included in the workspace, even if they are not used by the application layer.
Mixed use of low-layer APIs and HAL drivers
In this case the low-layer APIs are used in conjunction with the HAL drivers to achieve direct and register level based operations. Mixed use is allowed, however some consideration should be taken into account: · It is recommended to avoid using simultaneously the HAL APIs and the combination of low-layer APIs for
a given peripheral instance. If this is the case, one or more private fields in the HAL PPP handle structure should be updated accordingly. · For operations and processes that do not alter the handle fields including the initialization structure, the HAL driver APIs and the low-layer services can be used together for the same peripheral instance. · The low-layer drivers can be used without any restriction with all the HAL drivers that are not based on handle objects (RCC, common HAL, Flash and GPIO). Several examples showing how to use HAL and LL in the same application are provided within stm32c0 firmware package (refer to Examples_MIX projects). 1. When the HAL Init/DeInit APIs are not used and are replaced by the low-layer macros, the InitMsp() functions are not called and the MSP initialization should be done in the user application. 2. When process APIs are not used and the corresponding function is performed through the low-layer APIs, the callbacks are not called and post processing or error management should be done by the user application. 3. When the LL APIs is used for process operations, the IRQ handler HAL APIs cannot be called and the IRQ should be implemented by the user application. Each LL driver implements the macros needed to read and clear the associated interrupt flags.

UM3029 – Rev 1

page 40/1419

6

HAL System Driver

UM3029
HAL System Driver

6.1
6.1.1 6.1.2
6.1.3

HAL Firmware driver API description
The following section lists the various functions of the HAL library.
How to use this driver
The common HAL driver contains a set of generic and common APIs that can be used by the PPP peripheral drivers and the user to start using the HAL. The HAL contains two APIs’ categories: · Common HAL APIs · Services HAL APIs
HAL Initialization and Configuration functions
This section provides functions allowing to: · Initialize the Flash interface the NVIC allocation and initial time base clock configuration. · De-initialize common part of the HAL. · Configure the time base source to have 1ms time base with a dedicated Tick interrupt priority.
­ SysTick timer is used by default as source of time base, but user can eventually implement his proper time base source (a general purpose timer for example or other time source), keeping in mind that Time base duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and handled in milliseconds basis.
­ Time base configuration function (HAL_InitTick ()) is called automatically at the beginning of the program after reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig().
­ Source of time base is configured to generate interrupts at regular time intervals. Care must be taken if HAL_Delay() is called from a peripheral ISR process, the Tick interrupt line must have higher priority (numerically lower) than the peripheral interrupt. Otherwise the caller ISR process will be blocked.
­ functions affecting time base configurations are declared as __weak to make override possible in case of other implementations in user file.
This section contains the following APIs: · HAL_Init() · HAL_DeInit() · HAL_MspInit() · HAL_MspDeInit() · HAL_InitTick()
HAL Control functions
This section provides functions allowing to: · Provide a tick value in millisecond · Provide a blocking delay in millisecond · Suspend the time base source interrupt · Resume the time base source interrupt · Get the HAL API driver version · Get the device identifier · Get the device revision identifier This section contains the following APIs: · HAL_IncTick() · HAL_GetTick() · HAL_GetTickPrio() · HAL_SetTickFreq()

UM3029 – Rev 1

page 41/1419

UM3029
HAL Firmware driver API description

· HAL_GetTickFreq() · HAL_Delay() · HAL_SuspendTick() · HAL_ResumeTick() · HAL_GetHalVersion() · HAL_GetREVID() · HAL_GetDEVID() · HAL_GetUIDw0() · HAL_GetUIDw1() · HAL_GetUIDw2()

6.1.4

HAL Debug functions
This section provides functions allowing to: · Enable/Disable Debug module during STOP mode · Enable/Disable Debug module during STANDBY mode This section contains the following APIs: · HAL_DBGMCU_EnableDBGStopMode() · HAL_DBGMCU_DisableDBGStopMode() · HAL_DBGMCU_EnableDBGStandbyMode() · HAL_DBGMCU_DisableDBGStandbyMode()

6.1.5

HAL SYSCFG configuration functions
This section provides functions allowing to: · Enable/Disable Pin remap · Enable/Disable the I/O analog switch voltage booster This section contains the following APIs: · HAL_SYSCFG_EnableIOAnalogSwitchBooster() · HAL_SYSCFG_DisableIOAnalogSwitchBooster() · HAL_SYSCFG_EnableRemap() · HAL_SYSCFG_DisableRemap() · HAL_SYSCFG_SetPinBinding() · HAL_SYSCFG_GetPinBinding()

6.1.6

Detailed description of functions

HAL_Init

Function name HAL_StatusTypeDef HAL_Init (void )

Function description
Configure the Flash prefetch and the Instruction cache, the time base source, NVIC and any required global low level hardware by calling the HAL_MspInit() callback function to be optionally defined in user file stm32c0xx_hal_msp.c.

Return values ·

HAL: status

UM3029 – Rev 1

page 42/1419

UM3029
HAL Firmware driver API description

Notes

· HAL_Init() function is called at the beginning of program after reset and before the clock configuration.
· In the default implementation the System Timer (Systick) is used as source of time base. The Systick configuration is based on HSI clock, as HSI is the clock used after a system Reset. Once done, time base tick starts incrementing: the tick variable counter is incremented each 1ms in the SysTick_Handler() interrupt handler.

HAL_DeInit

Function name HAL_StatusTypeDef HAL_DeInit (void )

Function description This function de-Initializes common part of the HAL and stops the source of time base.

Return values ·

HAL: status

Notes

· This function is optional.

HAL_MspInit

Function name void HAL_MspInit (void )

Function description Initialize the MSP.

Return values ·

None:

HAL_MspDeInit

Function name void HAL_MspDeInit (void )

Function description DeInitializes the MSP.

Return values ·

None:

HAL_InitTick

Function name HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority)

Function description
This function configures the source of the time base: The time source is configured to have 1ms time base with a dedicated Tick interrupt priority.

Parameters ·

TickPriority: Tick interrupt priority.

Return values ·

HAL: status

UM3029 – Rev 1

page 43/1419

UM3029
HAL Firmware driver API description

Notes

· This function is called automatically at the beginning of program after reset by HAL_Init() or at any time when clock is reconfigured by HAL_RCC_ClockConfig().
· In the default implementation, SysTick timer is the source of time base. It is used to generate interrupts at regular time intervals. Care must be taken if HAL_Delay() is called from a peripheral ISR process, The SysTick interrupt must have higher priority (numerically lower) than the peripheral interrupt. Otherwise the caller ISR process will be blocked. The function is declared as __weak to be overwritten in case of other implementation in user file.

HAL_IncTick

Function name void HAL_IncTick (void )

Function description This function is called to increment a global variable “uwTick” used as application time base.

Return values ·

None:

Notes

· In the default implementation, this variable is incremented each 1ms in SysTick ISR. · This function is declared as __weak to be overwritten in case of other implementations in user file.

HAL_Delay

Function name void HAL_Delay (uint32_t Delay)

Function description This function provides minimum delay (in milliseconds) based on variable incremented.

Parameters ·

Delay: specifies the delay time length, in milliseconds.

Return values ·

None:

Notes

· In the default implementation , SysTick timer is the source of time base. It is used to generate interrupts at regular time intervals where uwTick is incremented.
· This function is declared as __weak to be overwritten in case of other implementations in user file.

HAL_GetTick

Function name uint32_t HAL_GetTick (void )

Function description Provides a tick value in millisecond.

Return values ·

tick: value

Notes

· This function is declared as __weak to be overwritten in case of other implementations in user file.

UM3029 – Rev 1

page 44/1419

UM3029
HAL Firmware driver API description

HAL_GetTickPrio

Function name uint32_t HAL_GetTickPrio (void )

Function description This function returns a tick priority.

Return values ·

tick: priority

HAL_SetTickFreq

Function name HAL_StatusTypeDef HAL_SetTickFreq (uint32_t Freq)

Function description Set new tick Freq.

Return values ·

status:

HAL_GetTickFreq

Function name uint32_t HAL_GetTickFreq (void )

Function description return tick frequency.

Return values ·

tick: period in Hz

HAL_SuspendTick

Function name void HAL_SuspendTick (void )

Function description Suspend Tick increment.

Return values ·

None:

Notes

· In the default implementation , SysTick timer is the source of time base. It is used to generate interrupts at regular time intervals. Once HAL_SuspendTick() is called, the SysTick interrupt will be disabled and so Tick increment is suspended.
· This function is declared as __weak to be overwritten in case of other implementations in user file.

HAL_ResumeTick Function name
void HAL_ResumeTick (void ) Function description
Resume Tick increment.

UM3029 – Rev 1

page 45/1419

UM3029
HAL Firmware driver API description

Return values ·
Notes ·
·

None:
In the default implementation , SysTick timer is the source of time base. It is used to generate interrupts at regular time intervals. Once HAL_ResumeTick() is called, the SysTick interrupt will be enabled and so Tick increment is resumed. This function is declared as __weak to be overwritten in case of other implementations in user file.

HAL_GetHalVersion

Function name uint32_t HAL_GetHalVersion (void )

Function description Returns the HAL revision.

Return values ·

version: : 0xXYZR (8bits for each decimal, R for RC)

HAL_GetREVID

Function name uint32_t HAL_GetREVID (void )

Function description Returns the device revision identifier.

Return values ·

Device: revision identifier

HAL_GetDEVID

Function name uint32_t HAL_GetDEVID (void )

Function description Returns the device identifier.

Return values ·

Device: identifier

HAL_GetUIDw0

Function name uint32_t HAL_GetUIDw0 (void )

Function description Returns first word of the unique device identifier (UID based on 96 bits)

Return values ·

Device: identifier

HAL_GetUIDw1 Function name
uint32_t HAL_GetUIDw1 (void )

UM3029 – Rev 1

page 46/1419

UM3029
HAL Firmware driver API description

Function description Returns second word of the unique device identifier (UID based on 96 bits)

Return values ·

Device: identifier

HAL_GetUIDw2

Function name uint32_t HAL_GetUIDw2 (void )

Function description Returns third word of the unique device identifier (UID based on 96 bits)

Return values ·

Device: identifier

HAL_DBGMCU_EnableDBGStopMode

Function name void HAL_DBGMCU_EnableDBGStopMode (void )

Function description Enable the Debug Module during STOP mode.

Return values ·

None:

HAL_DBGMCU_DisableDBGStopMode

Function name void HAL_DBGMCU_DisableDBGStopMode (void )

Function description Disable the Debug Module during STOP mode.

Return values ·

None:

HAL_DBGMCU_EnableDBGStandbyMode

Function name void HAL_DBGMCU_EnableDBGStandbyMode (void )

Function description Enable the Debug Module during STANDBY mode.

Return values ·

None:

HAL_DBGMCU_DisableDBGStandbyMode Function name
void HAL_DBGMCU_DisableDBGStandbyMode (void ) Function description
Disable the Debug Module during STANDBY mode.

UM3029 – Rev 1

page 47/1419

UM3029
HAL Firmware driver API description

Return values ·

None:

HAL_SYSCFG_EnableIOAnalogSwitchBooster

Function name void HAL_SYSCFG_EnableIOAnalogSwitchBooster (void )

Function description Enable the I/O analog switch voltage booster.

Return values ·

None:

HAL_SYSCFG_DisableIOAnalogSwitchBooster

Function name void HAL_SYSCFG_DisableIOAnalogSwitchBooster (void )

Function description Disable the I/O analog switch voltage booster.

Return values ·

None:

HAL_SYSCFG_EnableRemap

Function name void HAL_SYSCFG_EnableRemap (uint32_t PinRemap)

Function description Enable the remap on PA11_PA12.

Parameters ·

PinRemap: specifies which pins have to be remapped This parameter can be any combination of the following values:
­ SYSCFG_REMAP_PA11
­ SYSCFG_REMAP_PA12

Return values ·

None:

HAL_SYSCFG_DisableRemap

Function name void HAL_SYSCFG_DisableRemap (uint32_t PinRemap)

Function description Disable the remap on PA11_PA12.

Parameters ·

PinRemap: specifies which pins will behave normally This parameter can be any combination of the following values:
­ SYSCFG_REMAP_PA11
­ SYSCFG_REMAP_PA12

UM3029 – Rev 1

page 48/1419

UM3029
HAL Firmware driver defines

Return values ·

None:

HAL_SYSCFG_SetPinBinding

Function name void HAL_SYSCFG_SetPinBinding (uint32_t pin_binding)

Function description Set Pin Binding.

Parameters ·

pin_binding: specifies which pin will bind a specific GPIO for each die package This parameter can be any combination of HAL_BIND_xx defines

Return values ·

None:

HAL_SYSCFG_GetPinBinding

Function name uint32_t HAL_SYSCFG_GetPinBinding (void )

Function description return Pin Binding configuration

Return values ·

PinMux: configuration

6.2

HAL Firmware driver defines

The following section lists the various define and macros of the module.

6.2.1

HAL HAL Bind Pin config

HAL_BIND_WLCSP14_PINF2_PA1 STM32C031 WLCSP14 package, PinF2 assigned to GPIO PA1

HAL_BIND_WLCSP14_PINF2_PA2 STM32C031 WLCSP14 package, PinF2 assigned to GPIO PA2

HAL_BIND_WLCSP14_PING3_PF2 STM32C031 WLCSP14 package, PinG3 assigned to GPIO PF2

HAL_BIND_WLCSP14_PING3_PA0 STM32C031 WLCSP14 package, PinG3 assigned to GPIO PA0

HAL_BIND_WLCSP14_PINJ1_PA8 STM32C031 WLCSP14 package, PinJ1 assigned to GPIO PA8

HAL_BIND_WLCSP14_PINJ1_PA11 STM32C031 WLCSP14 package, PinJ1 assigned to GPIO PA11

HAL_BIND_WLCSP14_PINH2_PA5 STM32C031 WLCSP14 package, PinH2 assigned to GPIO PA5

UM3029 – Rev 1

page 49/1419

HAL_BIND_WLCSP14_PINH2_PA6 STM32C031 WLCSP14 package, PinH2 assigned to GPIO PA6
HAL_BIND_WLCSP14_PING1_PA7 STM32C031 WLCSP14 package, PinG1 assigned to GPIO PA7
HAL_BIND_WLCSP14_PING1_PA12 STM32C031 WLCSP14 package, PinG1 assigned to GPIO PA12
HAL_BIND_WLCSP14_PINJ3_PA3 STM32C031 WLCSP14 package, PinJ3 assigned to GPIO PA3
HAL_BIND_WLCSP14_PINJ3_PA4 STM32C031 WLCSP14 package, PinJ3 assigned to GPIO PA4
IR Modulation Envelope signal selection HAL_SYSCFG_IRDA_ENV_SEL_TIM16
00: Timer16 is selected as IR Modulation envelope source HAL_SYSCFG_IRDA_ENV_SEL_USART1
01: USART1 is selected as IR Modulation envelope source HAL_SYSCFG_IRDA_ENV_SEL_USART2
10: USART2 is selected as IR Modulation envelope source
IR output polarity selection HAL_SYSCFG_IRDA_POLARITY_NOT_INVERTED
00: IR output polarity not inverted HAL_SYSCFG_IRDA_POLARITY_INVERTED
01: IR output polarity inverted
HAL ISR Wrapper HAL_SYSCFG_ITLINE0
Internal define for macro handling HAL_SYSCFG_ITLINE2
Internal define for macro handling HAL_SYSCFG_ITLINE3
Internal define for macro handling HAL_SYSCFG_ITLINE4
Internal define for macro handling HAL_SYSCFG_ITLINE5
Internal define for macro handling HAL_SYSCFG_ITLINE6
Internal define for macro handling HAL_SYSCFG_ITLINE7
Internal define for macro handling
UM3029 – Rev 1

UM3029
HAL Firmware driver defines
page 50/1419

HAL_SYSCFG_ITLINE9 Internal define for macro handling
HAL_SYSCFG_ITLINE10 Internal define for macro handling
HAL_SYSCFG_ITLINE11 Internal define for macro handling
HAL_SYSCFG_ITLINE12 Internal define for macro handling
HAL_SYSCFG_ITLINE13 Internal define for macro handling
HAL_SYSCFG_ITLINE14 Internal define for macro handling
HAL_SYSCFG_ITLINE16 Internal define for macro handling
HAL_SYSCFG_ITLINE19 Internal define for macro handling
HAL_SYSCFG_ITLINE21 Internal define for macro handling
HAL_SYSCFG_ITLINE22 Internal define for macro handling
HAL_SYSCFG_ITLINE23 Internal define for macro handling
HAL_SYSCFG_ITLINE25 Internal define for macro handling
HAL_SYSCFG_ITLINE27 Internal define for macro handling
HAL_SYSCFG_ITLINE28 Internal define for macro handling
HAL_ITLINE_WWDG WWDG Interrupt
HAL_ITLINE_RTC RTC Interrupt
HAL_ITLINE_FLASH_ITF Flash ITF Interrupt
HAL_ITLINE_CLK_CTRL CLK Control Interrupt
HAL_ITLINE_EXTI0 External Interrupt 0
UM3029 – Rev 1

UM3029
HAL Firmware driver defines
page 51/1419

HAL_ITLINE_EXTI1 External Interrupt 1
HAL_ITLINE_EXTI2 External Interrupt 2
HAL_ITLINE_EXTI3 External Interrupt 3
HAL_ITLINE_EXTI4 EXTI4 Interrupt
HAL_ITLINE_EXTI5 EXTI5 Interrupt
HAL_ITLINE_EXTI6 EXTI6 Interrupt
HAL_ITLINE_EXTI7 EXTI7 Interrupt
HAL_ITLINE_EXTI8 EXTI8 Interrupt
HAL_ITLINE_EXTI9 EXTI9 Interrupt
HAL_ITLINE_EXTI10 EXTI10 Interrupt
HAL_ITLINE_EXTI11 EXTI11 Interrupt
HAL_ITLINE_EXTI12 EXTI12 Interrupt
HAL_ITLINE_EXTI13 EXTI13 Interrupt
HAL_ITLINE_EXTI14 EXTI14 Interrupt
HAL_ITLINE_EXTI15 EXTI15 Interrupt
HAL_ITLINE_DMA1_CH1 DMA1 Channel 1 Interrupt
HAL_ITLINE_DMA1_CH2 DMA1 Channel 2 Interrupt
HAL_ITLINE_DMA1_CH3 DMA1 Channel 3 Interrupt
HAL_ITLINE_DMAMUX DMAMUX Interrupt
UM3029 – Rev 1

UM3029
HAL Firmware driver defines
page 52/1419

HAL_ITLINE_ADC ADC Interrupt
HAL_ITLINE_TIM1_BRK TIM1 BRK Interrupt
HAL_ITLINE_TIM1_UPD TIM1 UPD Interrupt
HAL_ITLINE_TIM1_TRG TIM1 TRG Interrupt
HAL_ITLINE_TIM1_CCU TIM1 CCU Interrupt
HAL_ITLINE_TIM3 TIM3 Interrupt
HAL_ITLINE_TIM14 TIM14 Interrupt
HAL_ITLINE_TIM16 TIM16 Interrupt
HAL_ITLINE_TIM17 TIM17 Interrupt
HAL_ITLINE_I2C1 I2C1 Interrupt
HAL_ITLINE_SPI1 SPI1 Interrupt
HAL_ITLINE_USART1 USART1 GLB Interrupt
HAL_ITLINE_USART2 USART2 GLB Interrupt
Pin remapping SYSCFG_REMAP_PA11
PA11 pad behaves digitally as PA9 GPIO pin SYSCFG_REMAP_PA12
PA12 pad behaves digitally as PA10 GPIO pin
HAL state definition HAL_SMBUS_STATE_RESET
SMBUS not yet initialized or disabled HAL_SMBUS_STATE_READY
SMBUS initialized and ready for use HAL_SMBUS_STATE_BUSY
SMBUS internal process is ongoing
UM3029 – Rev 1

UM3029
HAL Firmware driver defines
page 53/1419

UM3029
HAL Firmware driver defines
HAL_SMBUS_STATE_MASTER_BUSY_TX Master Data Transmission process is ongoing
HAL_SMBUS_STATE_MASTER_BUSY_RX Master Data Reception process is ongoing
HAL_SMBUS_STATE_SLAVE_BUSY_TX Slave Data Transmission process is ongoing
HAL_SMBUS_STATE_SLAVE_BUSY_RX Slave Data Reception process is ongoing
HAL_SMBUS_STATE_TIMEOUT Timeout state
HAL_SMBUS_STATE_ERROR Reception process is ongoing
HAL_SMBUS_STATE_LISTEN Address Listen Mode is ongoing
Tick Frequency HAL_TICK_FREQ_10HZ
HAL_TICK_FREQ_100HZ
HAL_TICK_FREQ_1KHZ
HAL_TICK_FREQ_DEFAULT
Boot Mode SYSCFG_BOOT_MAINFLASH
Main Flash memory mapped at 0x0000 0000 SYSCFG_BOOT_SYSTEMFLASH
System Flash memory mapped at 0x0000 0000 SYSCFG_BOOT_SRAM
Embedded SRAM mapped at 0x0000 0000
Break SYSCFG_BREAK_LOCKUP
Enables and locks the LOCKUP output of CortexM0+ with Break Input of TIM1/16/17
SYSCFG Exported Macros HAL_GET_PENDING_IT
Notes: · Allow to determine interrupt source per line.
__HAL_SYSCFG_REMAPMEMORY_FLASH
HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH

UM3029 – Rev 1

page 54/1419

UM3029
HAL Firmware driver defines
HAL_SYSCFG_REMAPMEMORY_SRAM
HAL_SYSCFG_GET_BOOT_MODE Description: · Return the boot mode as configured by user. Return value: · The: boot mode as configured by user. The returned value can be one of the following values
HAL_SYSCFG_BREAK_LOCKUP_LOCK Notes: · The selected configuration is locked and can be unlocked only by system reset. Enables and locks the connection of Cortex-M0+ LOCKUP (Hardfault) output to TIM1/16/17 Break input
__HAL_SYSCFG_FASTMODEPLUS_ENABLE Description: · Fast-mode Plus driving capability enable/disable macros. Parameters: ·
FASTMODEPLUS: This parameter can be a value of
HAL_SYSCFG_FASTMODEPLUS_DISABLE
HAL_SYSCFG_IRDA_ENV_SELECTION Description: · selection of the modulation envelope signal macro, using bits [7:6] of SYSCFG_CFGR1 register Parameters: · SOURCE: This parameter can be a value of
__HAL_SYSCFG_GET_IRDA_ENV_SELECTION
HAL_SYSCFG_IRDA_OUT_POLARITY_SELECTION Description: · IROut Polarity Selection, using bit[5] of SYSCFG_CFGR1 register. Parameters: · SEL: This parameter can be a value of
HAL_SYSCFG_GET_POLARITY Description: · Return the IROut Polarity mode as configured by user. Return value: · The: IROut polarity as configured by user. The returned value can be one of
__HAL_SYSCFG_BREAK_ENABLE Description: · Break input to TIM1/16/17 capability enable/disable macros. Parameters: ·
BREAK: This parameter can be a value of
HAL_SYSCFG_BREAK_DISABLE
Fast mode Plus on GPIO
SYSCFG_FASTMODEPLUS_PB6 Enable Fast mode Plus on PB6

UM3029 – Rev 1

page 55/1419

SYSCFG_FASTMODEPLUS_PB7 Enable Fast mode Plus on PB7
SYSCFG_FASTMODEPLUS_PB8 Enable Fast mode Plus on PB8
SYSCFG_FASTMODEPLUS_PB9 Enable Fast mode Plus on PB9
SYSCFG_FASTMODEPLUS_PA9 Enable Fast mode Plus on PA9
SYSCFG_FASTMODEPLUS_PA10 Enable Fast mode Plus on PA10
SYSCFG_FASTMODEPLUS_PC14 Enable Fast mode Plus on PC14
Fast mode Plus driving capability activation for I2Cx SYSCFG_FASTMODEPLUS_I2C1
Enable Fast mode Plus on I2C1

UM3029
HAL Firmware driver defines

UM3029 – Rev 1

page 56/1419

7

HAL ADC Generic Driver

UM3029
HAL ADC Generic Driver

7.1
7.1.1
7.1.2

ADC Firmware driver registers structures
ADC_OversamplingTypeDef ADC_OversamplingTypeDef is defined in the stm32c0xx_hal_adc.h Data Fields · uint32_t Ratio · uint32_t RightBitShift · uint32_t TriggeredMode Field Documentation · uint32_t ADC_OversamplingTypeDef::Ratio
Configures the oversampling ratio. This parameter can be a value of ADC_HAL_EC_OVS_RATIO · uint32_t ADC_OversamplingTypeDef::RightBitShift
Configures the division coefficient for the Oversampler. This parameter can be a value of ADC_HAL_EC_OVS_SHIFT · uint32_t ADC_OversamplingTypeDef::TriggeredMode Selects the regular triggered oversampling mode. This parameter can be a value of ADC_HAL_EC_OVS_DISCONT_MODE
ADC_InitTypeDef ADC_InitTypeDef is defined in the stm32c0xx_hal_adc.h Data Fields · uint32_t ClockPrescaler · uint32_t Resolution · uint32_t DataAlign · uint32_t ScanConvMode · uint32_t EOCSelection · FunctionalState LowPowerAutoWait · FunctionalState LowPowerAutoPowerOff · FunctionalState ContinuousConvMode · uint32_t NbrOfConversion · FunctionalState DiscontinuousConvMode · uint32_t ExternalTrigConv · uint32_t ExternalTrigConvEdge · FunctionalState DMAContinuousRequests · uint32_t Overrun · uint32_t SamplingTimeCommon1 · uint32_t SamplingTimeCommon2 · FunctionalState OversamplingMode · ADC_OversamplingTypeDef Oversampling · uint32_t TriggerFrequencyMode Field Documentation

UM3029 – Rev 1

page 57/1419

UM3029
ADC Firmware driver registers structures
· uint32_t ADC_InitTypeDef::ClockPrescaler
Select ADC clock source (synchronous clock derived from APB clock or asynchronous clock derived from system clock or PLL (Refer to reference manual for list of clocks available)) and clock prescaler. This parameter can be a value of ADC_HAL_EC_COMMON_CLOCK_SOURCE. Note: The ADC clock configuration is common to all ADC instances. Note: In case of synchronous clock mode based on HCLK/1, the configuration must be enabled only if the system clock has a 50% duty clock cycle (APB prescaler configured inside RCC must be bypassed and PCLK clock must have 50% duty cycle). Refer to reference manual for details. Note: In case of usage of asynchronous clock, the selected clock must be preliminarily enabled at RCC top level. Note: This parameter can be modified only if all ADC instances are disabled.
· uint32_t ADC_InitTypeDef::Resolution
Configure the ADC resolution. This parameter can be a value of ADC_HAL_EC_RESOLUTION
· uint32_t ADC_InitTypeDef::DataAlign
Specify ADC data alignment in conversion data register (right or left). Refer to reference manual for alignments formats versus resolutions. This parameter can be a value of ADC_HAL_EC_DATA_ALIGN
· uint32_t ADC_InitTypeDef::ScanConvMode
Configure the sequencer of ADC group regular. On this STM32 series, ADC group regular sequencer both modes “fully configurable” or “not fully configurable” are available:
­ sequencer configured to fully configurable: sequencer length and each rank affectation to a channel are configurable.
Sequence length: Set number of ranks in the scan sequence.
Sequence direction: Unless specified in parameters, sequencer scan direction is forward (from rank 1 to rank n).
­ sequencer configured to not fully configurable: sequencer length and each rank affectation to a channel are fixed by channel HW number.
Sequence length: Number of ranks in the scan sequence is defined by number of channels set in the sequence, rank of each channel is fixed by channel HW number. (channel 0 fixed on rank 0, channel 1 fixed on rank1, …).
Sequence direction: Unless specified in parameters, sequencer scan direction is forward (from lowest channel number to highest channel number). This parameter can be associated to parameter ‘DiscontinuousConvMode’ to have main sequence subdivided in successive parts. Sequencer is automatically enabled if several channels are set (sequencer cannot be disabled, as it can be the case on other STM32 devices): If only 1 channel is set: Conversion is performed in single mode. If several channels are set: Conversions are performed in sequence mode. This parameter can be a value of ADC_Scan_mode
· uint32_t ADC_InitTypeDef::EOCSelection
Specify which EOC (End Of Conversion) flag is used for conversion by polling and interruption: end of unitary conversion or end of sequence conversions. This parameter can be a value of ADC_EOCSelection.
· FunctionalState ADC_InitTypeDef::LowPowerAutoWait
Select the dynamic low power Auto Delay: new conversion start only when the previous conversion (for ADC group regular) has been retrieved by user software, using function HAL_ADC_GetValue(). This feature automatically adapts the frequency of ADC conversions triggers to the speed of the system that reads the data. Moreover, this avoids risk of overrun for low frequency applications. This parameter can be set to ENABLE or DISABLE. Note: It is not recommended to use with interruption or DMA (HAL_ADC_Start_IT(), HAL_ADC_Start_DMA()) since these modes have to clear immediately the EOC flag (by CPU to free the IRQ pending event or by DMA). Auto wait will work but fort a very short time, discarding its intended benefit (except specific case of high load of CPU or DMA transfers which can justify usage of auto wait). Do use with polling: 1. Start conversion with HAL_ADC_Start(), 2. Later on, when ADC conversion data is needed: use HAL_ADC_PollForConversion() to ensure that conversion is completed and HAL_ADC_GetValue() to retrieve conversion result and trig another conversion start.
· FunctionalState ADC_InitTypeDef::LowPowerAutoPowerOff
Select the auto-off mode: the ADC automatically powers-off after a conversion and automatically wakes-up when a new conversion is triggered (with startup time between trigger and start of sampling). This feature can be combined with automatic wait mode (parameter ‘LowPowerAutoWait’). This parameter can be set to ENABLE or DISABLE. Note: If enabled, this feature also turns off the ADC dedicated 14 MHz RC oscillator (HSI14)

UM3029 – Rev 1

page 58/1419

UM3029
ADC Firmware driver registers structures
· FunctionalState ADC_InitTypeDef::ContinuousConvMode
Specify whether the conversion is performed in single mode (one conversion) or continuous mode for ADC group regular, after the first ADC conversion start trigger occurred (software start or external trigger). This parameter can be set to ENABLE or DISABLE.
· uint32_t ADC_InitTypeDef::NbrOfConversion
Specify the number of ranks that will be converted within the regular group sequencer. This parameter is dependent on ScanConvMode:
­ sequencer configured to fully configurable: Number of ranks in the scan sequence is configurable using this parameter. Note: After the first call of ‘HAL_ADC_Init()’, each rank corresponding to parameter “NbrOfConversion” must be set using ‘HAL_ADC_ConfigChannel()’. Afterwards, when all needed sequencer ranks are set, parameter ‘NbrOfConversion’ can be updated without modifying configuration of sequencer ranks (sequencer ranks above ‘NbrOfConversion’ are discarded).
­ sequencer configured to not fully configurable: Number of ranks in the scan sequence is defined by number of channels set in the sequence. This parameter is discarded. This parameter must be a number between Min_Data = 1 and Max_Data = 8. Note: This parameter must be modified when no conversion is on going on regular group (ADC disabled, or ADC enabled without continuous mode or external trigger that could launch a conversion).
· FunctionalState ADC_InitTypeDef::DiscontinuousConvMode
Specify whether the conversions sequence of ADC group regular is performed in Complete-sequence/ Discontinuous-sequence (main sequence subdivided in successive parts). Discontinuous mode is used only if sequencer is enabled (parameter ‘ScanConvMode’). If sequencer is disabled, this parameter is discarded. Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. This parameter can be set to ENABLE or DISABLE. Note: On this STM32 series, ADC group regular number of discontinuous ranks increment is fixed to one-by- one.
· uint32_t ADC_InitTypeDef::ExternalTrigConv
Select the external event source used to trigger ADC group regular conversion start. If set to ADC_SOFTWARE_START, external triggers are disabled and software trigger is used instead. This parameter can be a value of ADC_regular_external_trigger_source. Caution: external trigger source is common to all ADC instances.
· uint32_t ADC_InitTypeDef::ExternalTrigConvEdge
Select the external event edge used to trigger ADC group regular conversion start. If trigger source is set to ADC_SOFTWARE_START, this parameter is discarded. This parameter can be a value of ADC_regular_external_trigger_edge
· FunctionalState ADC_InitTypeDef::DMAContinuousRequests
Specify whether the DMA requests are performed in one shot mode (DMA transfer stops when number of conversions is reached) or in continuous mode (DMA transfer unlimited, whatever number of conversions). This parameter can be set to ENABLE or DISABLE. Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer maximum pointer is reached.
· uint32_t ADC_InitTypeDef::Overrun
Select the behavior in case of overrun: data overwritten or preserved (default). This parameter can be a value of ADC_HAL_EC_REG_OVR_DATA_BEHAVIOR. Note: In case of overrun set to data preserved and usage with programming model with interruption (HAL_Start_IT()): ADC IRQ handler has to clear end of conversion flags, this induces the release of the preserved data. If needed, this data can be saved in function HAL_ADC_ConvCpltCallback(), placed in user program code (called before end of conversion flags clear). Note: Error reporting with respect to the conversion mode:
­ Usage with ADC conversion by polling for event or interruption: Error is reported only if overrun is set to data preserved. If overrun is set to data overwritten, user can willingly not read all the converted data, this is not considered as an erroneous case.
­ Usage with ADC conversion by DMA: Error is reported whatever overrun setting (DMA is expected to process all data from data register).

UM3029 – Rev 1

page 59/1419

7.1.3

UM3029
ADC Firmware driver registers structures
· uint32_t ADC_InitTypeDef::SamplingTimeCommon1 Set sampling time common to a group of channels. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). Note: On this STM32 family, two different sampling time settings are available, each channel can use one of these two settings. On some other STM32 devices, this parameter in channel wise and is located into ADC channel initialization structure. This parameter can be a value of ADC_HAL_EC_CHANNEL_SAMPLINGTIME Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values, parameters TS_vrefint, TS_vbat, TS_temp (values rough order: few tens of microseconds).
· uint32_t ADC_InitTypeDef::SamplingTimeCommon2 Set sampling time common to a group of channels, second common setting possible. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). Note: On this STM32 family, two different sampling time settings are available, each channel can use one of these two settings. On some other STM32 devices, this parameter in channel wise and is located into ADC channel initialization structure. This parameter can be a value of ADC_HAL_EC_CHANNEL_SAMPLINGTIME Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values, parameters TS_vrefint, TS_vbat, TS_temp (values rough order: few tens of microseconds).
· FunctionalState ADC_InitTypeDef::OversamplingMode Specify whether the oversampling feature is enabled or disabled. This parameter can be set to ENABLE or DISABLE. Note: This parameter can be modified only if there is no conversion is ongoing on ADC group regular.
· ADC_OversamplingTypeDef ADC_InitTypeDef::Oversampling Specify the Oversampling parameters. Caution: this setting overwrites the previous oversampling configuration if oversampling is already enabled.
· uint32_t ADC_InitTypeDef::TriggerFrequencyMode Set ADC trigger frequency mode. This parameter can be a value of ADC_HAL_EC_REG_TRIGGER_FREQ. Note: ADC trigger frequency mode must be set to low frequency when a duration is exceeded before ADC conversion start trigger event (between ADC enable and ADC conversion start trigger event or between two ADC conversion start trigger event). Duration value: Refer to device datasheet, parameter “tIdle”. Note: When ADC trigger frequency mode is set to low frequency, some rearm cycles are inserted before performing ADC conversion start, inducing a delay of 2 ADC clock cycles.
ADC_ChannelConfTypeDef ADC_ChannelConfTypeDef is defined in the stm32c0xx_hal_adc.h Data Fields
· uint32_t Channel · uint32_t Rank · uint32_t SamplingTime
Field Documentation
· uint32_t ADC_ChannelConfTypeDef::Channel Specify the channel to configure into ADC regular group. This parameter can be a value of ADC_HAL_EC_CHANNEL Note: Depending on devices and ADC instances, some channels may not be available on device package pins. Refer to device datasheet for channels availability.
· uint32_t ADC_ChannelConfTypeDef::Rank Add or remove the channel from ADC regular group sequencer and specify its conversion rank. This parameter is dependent on ScanConvMode:
­ sequencer configured to fully configurable: Channels ordering into each rank of scan sequence: whatever channel can be placed into whatever rank.
­ sequencer configured to not fully configurable: rank of each channel is fixed by channel HW number. (channel 0 fixed on rank 0, channel 1 fixed on rank1, …). Despite the channel rank is fixed, this parameter allow an additional possibility: to remove the selected rank (selected channel) from sequencer. This parameter can be a value of ADC_HAL_EC_REG_SEQ_RANKS

UM3029 – Rev 1

page 60/1419

7.1.4

UM3029
ADC Firmware driver registers structures
· uint32_t ADC_ChannelConfTypeDef::SamplingTime
Sampling time value to be set for the selected channel. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). This parameter can be a value of ADC_HAL_EC_SAMPLINGTIME_COMMON Note: On this STM32 family, two different sampling time settings are available (refer to parameters “SamplingTimeCommon1” and “SamplingTimeCommon2”), each channel can use one of these two settings.Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) Refer to device datasheet for timings values.
ADC_AnalogWDGConfTypeDef ADC_AnalogWDGConfTypeDef is defined in the stm32c0xx_hal_adc.h
Data Fields
· uint32_t WatchdogNumber
· uint32_t WatchdogMode
· uint32_t Channel
· FunctionalState ITMode
· uint32_t HighThreshold
· uint32_t LowThreshold
Field Documentation
· uint32_t ADC_AnalogWDGConfTypeDef::WatchdogNumber
Select which ADC analog watchdog is monitoring the selected channel. For Analog Watchdog 1: Only 1 channel can be monitored (or overall group of channels by setting parameter ‘WatchdogMode’) For Analog Watchdog 2 and 3: Several channels can be monitored (by successive calls of ‘HAL_ADC_AnalogWDGConfig()’ for each channel) This parameter can be a value of ADC_HAL_EC_AWD_NUMBER.
· uint32_t ADC_AnalogWDGConfTypeDef::WatchdogMode
Configure the ADC analog watchdog mode: single/all/none channels. For Analog Watchdog 1: Configure the ADC analog watchdog mode: single channel or all channels, ADC group regular. For Analog Watchdog 2 and 3: Several channels can be monitored by applying successively the AWD init structure. This parameter can be a value of ADC_analog_watchdog_mode.
· uint32_t ADC_AnalogWDGConfTypeDef::Channel
Select which ADC channel to monitor by analog watchdog. For Analog Watchdog 1: this parameter has an effect only if parameter ‘WatchdogMode’ is configured on single channel (only 1 channel can be monitored). For Analog Watchdog 2 and 3: Several channels can be monitored. To use this feature, call successively the function HAL_ADC_AnalogWDGConfig() for each channel to be added (or removed with value ‘ADC_ANALOGWATCHDOG_NONE’). This parameter can be a value of ADC_HAL_EC_CHANNEL.
· FunctionalState ADC_AnalogWDGConfTypeDef::ITMode
Specify whether the analog watchdog is configured in interrupt or polling mode. This parameter can be set to ENABLE or DISABLE
· uint32_t ADC_AnalogWDGConfTypeDef::HighThreshold
Configure the ADC analog watchdog High threshold value. Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. Note: Analog watchdog 2 and 3 are limited to a resolution of 8 bits: if ADC resolution is 12 bits the 4 LSB are ignored, if ADC resolution is 10 bits the 2 LSB are ignored. Note: If ADC oversampling is enabled, ADC analog watchdog thresholds are impacted: the comparison of analog watchdog thresholds is done on oversampling final computation (after ratio and shift application): ADC data register bitfield [15:4] (12 most significant bits).
· uint32_t ADC_AnalogWDGConfTypeDef::LowThreshold
Configures the ADC analog watchdog Low threshold value. Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. Note: Analog watchdog 2 and 3 are limited to a resolution of 8 bits: if ADC resolution is 12 bits the 4 LSB are ignored, if ADC resolution is 10 bits the 2 LSB are ignored. Note: If ADC oversampling is enabled, ADC analog watchdog thresholds are impacted: the comparison of analog watchdog thresholds is done on oversampling final computation (after ratio and shift application): ADC data register bitfield [15:4] (12 most significant bits).

UM3029 – Rev 1

page 61/1419

7.1.5

UM3029
ADC Firmware driver registers structures
ADC_HandleTypeDef ADC_HandleTypeDef is defined in the stm32c0xx_hal_adc.h Data Fields · ADC_TypeDef Instance · ADC_InitTypeDef Init · DMA_HandleTypeDef DMA_Handle · HAL_LockTypeDef Lock · IO uint32_t State · IO uint32_t ErrorCode · uint32_t ADCGroupRegularSequencerRanks · void( ConvCpltCallback · void( ConvHalfCpltCallback · void( LevelOutOfWindowCallback · void( ErrorCallback · void( LevelOutOfWindow2Callback · void( LevelOutOfWindow3Callback · void( EndOfSamplingCallback · void( MspInitCallback · void( MspDeInitCallback Field Documentation · ADC_TypeDef ADC_HandleTypeDef::Instance
Register base address · ADC_InitTypeDef
ADC_HandleTypeDef::Init
ADC initialization parameters and regular conversions setting · DMA_HandleTypeDef ADC_HandleTypeDef::DMA_Handle
Pointer DMA Handler · HAL_LockTypeDef __ADC_HandleTypeDef::Lock
ADC locking object ·
IO uint32_t ADC_HandleTypeDef::State
ADC communication state (bitmap of ADC states) · __IO uint32_t
ADC_HandleTypeDef::ErrorCode
ADC Error code · uint32_t __ADC_HandleTypeDef::ADCGroupRegularSequencerRanks
ADC group regular sequencer memorization of ranks setting, used in mode “fully configurable” (refer to parameter ‘ScanConvMode’) · void(
ADC_HandleTypeDef::ConvCpltCallback)(struct __ADC_HandleTypeDef hadc) ADC conversion complete callback · void( ADC_HandleTypeDef::ConvHalfCpltCallback)(struct ADC_HandleTypeDef hadc) ADC conversion DMA half-transfer callback · void( __ADC_HandleTypeDef::LevelOutOfWindowCallback)(struct ADC_HandleTypeDef hadc) ADC analog watchdog 1 callback · void( ADC_HandleTypeDef::ErrorCallback)(struct __ADC_HandleTypeDef hadc) ADC error callback · void( ADC_HandleTypeDef::LevelOutOfWindow2Callback)(struct ADC_HandleTypeDef hadc) ADC analog watchdog 2 callback · void( __ADC_HandleTypeDef::LevelOutOfWindow3Callback)(struct ADC_HandleTypeDef hadc) ADC analog watchdog 3 callback · void( __ADC_HandleTypeDef::EndOfSamplingCallback)(struct __ADC_HandleTypeDef *hadc) ADC end of sampling callback

UM3029 – Rev 1

page 62/1419

7.2
7.2.1
7.2.2

UM3029
ADC Firmware driver API description
· void( __ADC_HandleTypeDef::MspInitCallback)(struct __ADC_HandleTypeDef hadc) ADC Msp Init callback
· void( __ADC_HandleTypeDef::MspDeInitCallback)(struct __ADC_HandleTypeDef hadc) ADC Msp DeInit callback
ADC Firmware driver API description
The following section lists the various functions of the ADC library.
ADC peripheral features
· 12-bit, 10-bit, 8-bit or 6-bit configurable resolution. · Interrupt generation at the end of regular conversion and in case of analog watchdog or overrun events. · Single and continuous conversion modes. · Scan mode for conversion of several channels sequentially. · Data alignment with in-built data coherency. · Programmable sampling time (common to group of channels) · External trigger (timer or EXTI) with configurable polarity · DMA request generation for transfer of conversions data of regular group. · ADC calibration · ADC conversion of regular group. · ADC supply requirements: 1.62 V to 3.6 V. · ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to Vdda or to an external voltage
reference).
How to use this driver
Configuration of top level parameters related to ADC
1. Enable the ADC interface ­ As prerequisite, ADC clock must be configured at RCC top level. Caution: On STM32C0, ADC clock frequency max is 35MHz (refer to device datasheet). Therefore, ADC clock source from RCC and ADC clock prescaler must be configured to remain below this maximum frequency. ­ Two clock settings are mandatory: ADC clock (core clock, also possibly conversion clock). ADC clock (conversions clock). Four possible clock sources: synchronous clock from APB clock (same as ADC core clock) or asynchronous clock from RCC level: SYSCLK, HSI48. Example: Into HAL_ADC_MspInit() (recommended code location) or with other device clock parameters configuration: HAL_RCC_ADC_CLK_ENABLE(); (mandatory: core clock) ­ ADC clock source and clock prescaler are configured at ADC level with parameter “ClockPrescaler” using function HAL_ADC_Init().
2. ADC pins configuration ­ Enable the clock for the ADC GPIOs using macro
HAL_RCC_GPIOx_CLK_ENABLE() ­ Configure these ADC pins in analog mode using function HAL_GPIO_Init()
3. Optionally, in case of usage of ADC with interruptions: ­ Configure the NVIC for ADC using function HAL_NVIC_EnableIRQ(ADCx_IRQn) ­ Insert the ADC interruption handler function HAL_ADC_IRQHandler() into the function of corresponding ADC interruption vector ADCx_IRQHandler().
4. Optionally, in case of usage of DMA: ­ Configure the DMA (DMA channel, mode normal or circular, …) using function HAL_DMA_Init(). ­ Configure the NVIC for DMA using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn) ­ Insert the ADC interruption handler function HAL_ADC_IRQHandler() into the function of corresponding DMA interruption vector DMAx_Channelx_IRQHandler().

UM3029 – Rev 1

page 63/1419

UM3029
ADC Firmware driver API description

Note:

Configuration of ADC, group regular, channels parameters
1. Configure the ADC parameters (resolution, data alignment, …) and regular group parameters (conversion trigger, sequencer, …) using function HAL_ADC_Init().
2. Configure the channels for regular group parameters (channel number, channel rank into sequencer, …, into regular group) using function HAL_ADC_ConfigChannel().
3. Optionally, configure the analog watchdog parameters (channels monitored, thresholds, …) using function HAL_ADC_AnalogWDGConfig().
Execution of ADC conversions
1. Optionally, perform an automatic ADC calibration to improve the conversion accuracy using function HAL_ADCEx_Calibration_Start().
2. ADC driver can be used among three modes: polling, interruption, transfer by DMA. ­ ADC conversion by polling: Activate the ADC peripheral and start conversions using function HAL_ADC_Start() Wait for ADC conversion completion using function HAL_ADC_PollForConversion() Retrieve conversion results using function HAL_ADC_GetValue() Stop conversion and disable the ADC peripheral using function HAL_ADC_Stop() ­ ADC conversion by interruption: Activate the ADC peripheral and start conversions using function HAL_ADC_Start_IT() Wait for ADC conversion completion by call of function HAL_ADC_ConvCpltCallback() (this function must be implemented in user program) Retrieve conversion results using function HAL_ADC_GetValue() Stop conversion and disable the ADC peripheral using function HAL_ADC_Stop_IT() ­ ADC conversion with transfer by DMA: Activate the ADC peripheral and start conversions using function HAL_ADC_Start_DMA() Wait for ADC conversion completion by call of function HAL_ADC_ConvCpltCallback() or HAL_ADC_ConvHalfCpltCallback() (these functions must be implemented in user program) Conversion results are automatically transferred by DMA into destination variable address. Stop conversion and disable the ADC peripheral using function HAL_ADC_Stop_DMA()
Callback functions must be implemented in user program: · HAL_ADC_ErrorCallback() · HAL_ADC_LevelOutOfWindowCallback() (callback of analog watchdog) · HAL_ADC_ConvCpltCallback() · HAL_ADC_ConvHalfCpltCallback
Deinitialization of ADC
1. Disable the ADC interface ­ ADC clock can be hard reset and disabled at RCC top level. ­ Hard reset of ADC peripherals using macro ADCx_FORCE_RESET(), ADCx_RELEASE_RESET(). ­ ADC clock disable using the equivalent macro/functions as configuration step. Example: Into HAL_ADC_MspDeInit() (recommended code location) or with other device clock parameters configuration: RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI14; RCC_OscInitStructure.HSI14State = RCC_HSI14_OFF; (if not used for system clock) HAL_RCC_OscConfig(&RCC_OscInitStructure);
2. ADC pins configuration ­ Disable the clock for the ADC GPIOs using macro __HAL_RCC_GPIOx_CLK_DISABLE()
3. Optionally, in case of usage of ADC with interruptions: ­ Disable the NVIC for ADC using function HAL_NVIC_EnableIRQ(ADCx_IRQn)

UM3029 – Rev 1

page 64/1419

7.2.3

UM3029
ADC Firmware driver API description
4. Optionally, in case of usage of DMA: ­ Deinitialize the DMA using function HAL_DMA_Init(). ­ Disable the NVIC for DMA using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
Callback registration
The compilation flag USE_HAL_ADC_REGISTER_CALLBACKS, when set to 1, allows the user to configure dynamically the driver callbacks. Use Functions @ref HAL_ADC_RegisterCallback() to register an interrupt callback. Function @ref H

References

Read User Manual Online (PDF format)

Read User Manual Online (PDF format)  >>

Download This Manual (PDF format)

Download this manual  >>

Related Manuals