Embedded HandbookApps
All sections › I. Basics
STM32C5, STM32U5 · level intermediate · 23 min read
Open in the interactive handbook

5б. HAL2, the new generation of STM32 drivers: what changed from HAL1, architecture, error handling, callbacks, LL under the hood and porting a project

Sections 5 and 5а are about HAL as it has been known since 2014: the handle UART_HandleTypeDef with its Init field, HAL_UART_Init with MspInit inside, HAL_BUSY from a busy port, weak callbacks. Below, that HAL is called HAL1. ST now has a second generation, HAL2: the same idea of "one function, one action", but a different interface. It is not compatible with HAL1: code has to be rewritten. This section covers what exactly changed and why, how HAL2 is built inside (it stands entirely on LL), how it reports errors, what happened to callbacks, the RTOS support and the time base, how much it weighs next to HAL1 on the same program, and how to port a project.

Sources: the STM32CubeC5 package with the stm32c5xx_drivers 2.1.0 drivers (README and Release Notes, 12 June 2026), the templates/, os_port/ and timebases/ folders and the examples/hal/uart examples; the HAL2 preview for U5, the STM32CubeU5 HAL2 drivers Preview repository, V2.0.0-beta.1.1 of 4 July 2025, with its "Breaking changes in concepts" document (docs/breaking_concepts); HAL1 from the Keil packs STM32U5xx_DFP 2.2.1 (HAL driver V1.3.0) and STM32F4xx_DFP 2.17.1. The HAL2 drivers in both packages are licensed under BSD-3-Clause. What is said about HAL2 Migrator comes from ST documentation ("HAL1 to HAL2 — migration guide" 1.0.0, data brief DB5796 Rev 1) and is not verified: the tool is not on disk.

Terms used in the documentation

Term Meaning
HAL2 (STM32Cube HAL drivers v2.x) the second generation of HAL; the previous one is called HAL1 here
HAL-over-LL principle HAL touches registers only through LL functions
unitary configuration function a function that changes one setting (HAL_UART_SetBaudRate)
global state / process state the state of the block and the state of one process (tx_state, rx_state)
hal_status_t the HAL2 status code: five values far apart in bits
debug assertion (ASSERT_DBG_PARAM, ASSERT_DBG_STATE) a debug check of a parameter or a state, empty in release builds
run-time parameter check (USE_HAL_CHECK_PARAM) a parameter check that stays in release builds
acquire / release bus (HAL_PPP_AcquireBus) taking and releasing a block between RTOS tasks
time base pattern a ready-made HAL time base file on a timer or the RTC
HAL1 detection script, stubbing a script that finds HAL1 calls, and a stub mode to keep the build going
NRND (not recommended for new design) not recommended for new designs

5б.1 Why HAL2 and where it exists

The README of the STM32CubeC5 drivers lists the goals: less code, a clearer interface, finer-grained settings, better behaviour under an RTOS, HAL on top of LL, and code following MISRA C:2012 and checked with analysers. The price is stated plainly in the README of the U5 preview: incompatibility with the old HAL.

Where HAL2 exists. As the standard library on STM32C5: the STM32CubeC5 package carries drivers version 2.1.0, the second official release (the first, 2.0.0, came out on 13 March 2026). Supported are C531, C532, C542, C551, C552, C562, C591, C593 and C5A3, the boards NUCLEO-C562RE, NUCLEO-C542RC and NUCLEO-C5A3ZG; tested with IAR EWARM 9.60.3, Keil MDK 5.42, STM32CubeIDE for VS Code with GCC 13 and STM32CubeMX2 1.0.0. For U5 there is only a preview, V2.0.0-beta.1.1, and the repository itself is marked as archived: "no longer maintained", NRND. The other series live on HAL1: the Keil pack for F4 carries STM32F4xx_HAL_Driver with HAL_OK = 0x00U, the classic of sections 5 and 5а. So HAL2 is, for now, a choice that comes with the C5 series, not an update for F1 or F4.

What the driver package contains (the stm32c5xx_drivers folder):

Folder Contents
hal/ 47 .c files and headers; the application entry point is stm32_hal.h
ll/ 33 stm32c5xx_ll_*.h headers, only static inline functions, not a single .c
os_port/ no_os/ and freertos/: semaphores and mutexes for HAL
timebases/ the HAL time base on a timer, on the RTC alarm and on the RTC wakeup
utils/ timing calculation for I2C, I3C and FDCAN
templates/ stm32c5xx_hal_conf.h, stm32_assert.h, stm32_ll.h, RTOS and time base templates

For comparison: HAL1 for the same U5 (pack 2.2.1) has 117 .c files, of which 31 are LL init functions *_ll_*.c and 24 are extensions *_ex.c. HAL2 has neither: the extensions are merged into the main files, and LL-based initialisation is generated by CubeMX2 from inline functions. The series name has also left the entry header: the application includes stm32_hal.h, not stm32u5xx_hal.h, and the same program from 5б.6 builds for the U575 and for the C562 without changing a single line.

HAL2 layers in the STM32CubeC5 2.1.0 package: from top to bottom, application with the user code, generated with the files mx_usart2.c and mx_system.c that CubeMX2 overwrites entirely, hal with the Init, SetConfig, Transmit chain and the debug checks ASSERT_DBG_PARAM and ASSERT_DBG_STATE, ll with static inline functions and no .c files, the CMSIS registers; at the side, stm32c5xx_hal_conf.h with the keys USE_HAL_PPP_MODULE, USE_HAL_CHECK_PARAM and USE_HAL_CHECK_PROCESS_STATE, os_port with the no_os and freertos variants, timebases with SysTick by default and the TIM, RTC alarm, RTC wakeup templates, utils with I2C, I3C, FDCAN timings; on the right, the results of the section: on the U575 the HAL code is 7293 bytes in HAL1 against 3951 in HAL2, the UART handle is 148 bytes against 68, GCC 12.2.1 with -Os; HAL_OK on the C5 is 0xEAEAEAEA, in the U5 preview it is zero, HAL_BUSY = 0x55555555; a second Transmit_IT in a row returns HAL_OK by default, BYE goes out and HELLO is lost, with the state check it is HAL_BUSY


5б.2 The handle: Init, then SetConfig, with LL under the hood

In HAL1 a single function HAL_UART_Init did three jobs: it tied the handle to the block (the user filled in Instance), parsed the Init structure and wrote the registers, and in the middle it called HAL_UART_MspInit for clocks and pins. The Init structure stayed inside the handle. HAL2 cuts this into parts:

    if (HAL_UART_Init(&huart2, HAL_UART2) != HAL_OK) {   /* 1. дескриптор + экземпляр */
        for (;;) {
        }
    }
    HAL_RCC_USART2_EnableClock();                          /* 2. то, что было в MspInit */
    (void)HAL_RCC_USART2_SetKernelClkSource(HAL_RCC_USART2_CLK_SRC_PCLK1);
    g.mode = HAL_GPIO_MODE_ALTERNATE;
    g.alternate = HAL_GPIO_AF_7;
    (void)HAL_GPIO_Init(HAL_GPIOA, HAL_GPIO_PIN_2 | HAL_GPIO_PIN_3, &g);

    u.baud_rate = 115200;                                  /* 3. настройка */
    u.clock_prescaler = HAL_UART_PRESCALER_DIV1;

Three steps. HAL_UART_Init(&h, HAL_UART2) only fills in the handle: it sets the instance, clears the states and the DMA pointers and moves global_state to HAL_UART_STATE_INIT. It does not touch the registers: in the experiment of 5б.3 the "register" CR1 is preloaded with 0x12345678 and still holds it after Init. The second step, clocks, clock source and pins, is written by the user (or by CubeMX2 in mx_usart2.c): there is no MspInit or MspDeInit in HAL2. The third is HAL_UART_SetConfig(&h, &cfg): the settings structure is passed by pointer, applied to the registers and not stored in the handle. After it, global_state = HAL_UART_STATE_CONFIGURED. Individual parameters are then changed one by one: HAL_UART_SetBaudRate, HAL_UART_SetParity, HAL_UART_SetStopBits and four more such functions.

What this gained in bytes is visible with nm (5б.6): the global huart2 in HAL1 on the U575 takes 148 bytes, in HAL2 it takes 68, on the same U575 and on the C562. The fields of the HAL2 handle are documented as private: the application works with it only through functions.

HAL on top of LL. The second rule of HAL2: HAL functions do not write registers themselves, they call LL. Here is a pin toggle, the whole HAL2 function and what it calls:

void  HAL_GPIO_TogglePin(hal_gpio_t gpiox, uint32_t pins)
{
  ASSERT_DBG_PARAM(IS_GPIO_PORT((gpiox)));
  ASSERT_DBG_PARAM(IS_GPIO_PIN(pins));

  LL_GPIO_TogglePin(GPIO_GET_INSTANCE(gpiox), pins);
}
__STATIC_INLINE void LL_GPIO_TogglePin(GPIO_TypeDef *gpiox, uint32_t pin_mask)
{
  uint32_t odr = STM32_READ_REG(gpiox->ODR);
  STM32_WRITE_REG(gpiox->BSRR, ((odr & pin_mask) << 16U) | (~odr & pin_mask));
}

The HAL layer is responsible for checks, states and the order of steps, LL for the register write. The same goes for UART: at the end HAL_UART_Transmit_IT enables the interrupt by calling LL_USART_EnableIT_TXE_TXFNF, not __HAL_UART_ENABLE_IT. Three consequences follow. The __HAL_PPP_* macros that worked on registers are gone in HAL2: instead of __HAL_RCC_GPIOA_CLK_ENABLE() there is the inline HAL_RCC_GPIOA_EnableClock(), instead of __HAL_UART_ENABLE_IT there are LL functions. HAL constants became LL aliases: HAL_GPIO_PIN_5 is defined as LL_GPIO_PIN_5, the clock source HAL_RCC_USART2_CLK_SRC_PCLK1 as LL_RCC_USART2_CLKSOURCE_PCLK1. And any HAL function can be read as a ready-made sequence of LL calls, should HAL need to be thrown out of a hot path.


5б.3 Status codes, states and checks

Status codes. HAL1 has four of them, from 0 to 3 (5а.3). HAL2 has five, and they are not small numbers:

typedef enum
{
  HAL_OK            = 0xEAEAEAEAU, /* HAL operation completed successfully */
  HAL_ERROR         = 0xF5F5F5F5U, /* HAL operation completed with error   */
  HAL_BUSY          = 0x55555555U, /* HAL concurrent process ongoing       */
  HAL_INVALID_PARAM = 0xAAAAAAAAU, /* HAL invalid parameter                */
  HAL_TIMEOUT       = 0x5A5A5A5AU  /* HAL operation exceeds user timeout   */

} hal_status_t;

This is stm32c5xx_hal_def.h from release 2.1.0. The values are spread apart in bits on purpose: "Breaking changes in concepts" refers to a secure coding rule: the return values of sensitive functions must differ in at least eight bits, so that a single flipped bit cannot turn an error into success. In the U5 preview HAL_OK is still 0x00000000 and HAL_ERROR is 0xFFFFFFFF; on the C5 success has become non-zero. For porting this is the main point: a check if (status) or if (!HAL_..()) in the "zero means good" style reads success as an error on the C5. Compare only against HAL_OK by name.

HAL_INVALID_PARAM is a new code: an invalid parameter that could lead to a memory fault (a null pointer). HAL_TIMEOUT is returned only when a timeout set by the user expires; hardware failures and internal waits give HAL_ERROR.

States. For blocks where processes run in parallel, the state is split. For the UART on the C5: the common global_state is RESET (0), INIT (bit 31), CONFIGURED (bit 30); transmission and reception have tx_state and rx_state with RESET (bit 31), IDLE (bit 30), ACTIVE (bit 29), PAUSED and ABORT. Each value is one bit, so one check can accept several allowed states at once.

Checks: three independent groups of keys.

Key Where it is set What it does Default
USE_ASSERT_DBG_PARAM compiler option ASSERT_DBG_PARAM(...) in every function calls assert_dbg_param_failed(file, line) not set
USE_ASSERT_DBG_STATE compiler option ASSERT_DBG_STATE(state, allowed) calls assert_dbg_state_failed not set
USE_HAL_CHECK_PARAM stm32c5xx_hal_conf.h a check that stays in release: null pointer → HAL_INVALID_PARAM 0U
USE_HAL_SECURE_CHECK_PARAM stm32c5xx_hal_conf.h the same check for "sensitive" functions (AES and others) 0U
USE_HAL_CHECK_PROCESS_STATE stm32c5xx_hal_conf.h atomic state change; busy → HAL_BUSY 0U

In HAL1, assert_param was used only in the Init functions, while the busy port check was always there, with no keys. HAL2 is the other way round: parameter and state checks are in every function, but by default all of them are off. Here is the start of HAL_UART_Transmit_IT:

  ASSERT_DBG_PARAM(huart != NULL);
  ASSERT_DBG_PARAM(p_data != NULL);
  ASSERT_DBG_PARAM(size_byte != 0);

  ASSERT_DBG_STATE(huart->global_state, HAL_UART_STATE_CONFIGURED);
  ASSERT_DBG_STATE(huart->tx_state, HAL_UART_TX_STATE_IDLE);

#if defined(USE_HAL_CHECK_PARAM) && (USE_HAL_CHECK_PARAM == 1)
  if ((p_data == NULL) || (size_byte == 0U))
  {
    return HAL_INVALID_PARAM;
  }
#endif /* USE_HAL_CHECK_PARAM */

  HAL_CHECK_UPDATE_STATE(huart, tx_state, HAL_UART_TX_STATE_IDLE, HAL_UART_TX_STATE_ACTIVE);

and here is what the last line turns into when USE_HAL_CHECK_PROCESS_STATE is 0:

#define HAL_CHECK_UPDATE_STATE(handle, state_field, ppp_conditional_state, ppp_new_state) \
  (handle)->state_field = (ppp_new_state)

A plain assignment. With the key set to 1 the same macro reads the state with an LDREX instruction, compares it with the expected one, returns HAL_BUSY on a mismatch and otherwise writes the new state with STREX: check and update are atomic even between RTOS tasks and interrupts.

Experiment (QEMU mps2-an505, a Cortex-M33 core; the real stm32c5xx_hal_uart.c from the package is compiled, files in _verify/hal2_5b/). This machine has no USART block, so the instance is a USART_TypeDef structure in RAM: the program passes its address to HAL_UART_Init, sets the TXE and TC flags and calls HAL_UART_IRQHandler itself, collecting bytes from the TDR "register". The SetConfig step is replaced: its states are set by hand, because it needs the RCC clocks that QEMU does not have. The first transmission is "HELLO", right after it, before it has finished, comes the second, "BYE". Build with the configuration template as is:

tx1=0xeaeaeaea tx_state=0x20000000 txeie=0x00000001 
tx2=0xeaeaeaea buf_is_msg2=0x00000001 count=0x00000003 
sent=BYE bytes=0x00000003 callback=0x00000001 tx_state=0x40000000 
tx_null=0xeaeaeaea tx_state=0x20000000 

The second call returned HAL_OK and overwrote the buffer and the counter: BYE went out on the line and HELLO vanished without a trace; the callback came once. The call with a null pointer and zero length also returned HAL_OK and left tx_state in ACTIVE (0x20000000), a transmission that will never end. The same program with USE_HAL_CHECK_PARAM and USE_HAL_CHECK_PROCESS_STATE set to 1:

tx2=0x55555555 buf_is_msg2=0x00000000 count=0x00000005 
sent=HELLO bytes=0x00000005 callback=0x00000001 tx_state=0x40000000 
tx_null=0xaaaaaaaa tx_state=0x40000000 

HAL_BUSY, HELLO went out, the null pointer gives HAL_INVALID_PARAM, the state is IDLE. With the USE_ASSERT_DBG_PARAM and USE_ASSERT_DBG_STATE keys the debug checks fire: assert_dbg_param_failed already in HAL_UART_Init, at line 810, the instance check, since an address in RAM does not look like a USART; assert_dbg_state_failed on the second call, at line 4454, the tx_state check; two parameter checks at lines 4450 and 4451. But the handler from the template simply returns, and the function carries on: BYE still went out. A debug check reports, it does not protect; put a halt into your own assert_dbg_state_failed.

The conclusion for anyone coming from 5а: in HAL2 there is no "silent HAL_BUSY" by default; there is no refusal at all. The order of calls has become the application's job, and the protection is switched on by the USE_HAL_CHECK_PROCESS_STATE key, for 138 bytes of code in the program of 5б.6.

Process errors. The error flags (overrun, framing, noise, parity) are still collected in the handle, but only when USE_HAL_UART_GET_LAST_ERRORS = 1, and are read with HAL_UART_GetLastErrorCodes; by default it is 0, the field does not exist and the bytes are saved.


5б.4 Callbacks, RTOS, time base and the configuration file

Callbacks. Both mechanisms from 5а.8 remain. By default there are weak functions; with USE_HAL_UART_REGISTER_CALLBACKS = 1 there are pointers in the handle and one registration function per event: HAL_UART_RegisterTxCpltCallback, HAL_UART_RegisterRxCpltCallback and eleven more. In the experiment of 5б.3 the build with this key delivered the call to its own on_tx_done, not to the weak function. Registration is allowed in both INIT and CONFIGURED. The callbacks themselves have changed: MspInit is gone, and the end of reception is merged with "reception until idle":

__WEAK void HAL_UART_RxCpltCallback(hal_uart_handle_t *huart, uint32_t size_byte, hal_uart_rx_event_types_t rx_event)

Instead of the HAL1 pair HAL_UART_RxCpltCallback(huart) and HAL_UARTEx_RxEventCallback(huart, Size) there is one function: how much was received and on which event (HAL_UART_RX_EVENT_TC, _IDLE, _RTO, _CHAR_MATCH). Telling "who called" by huart->Instance is no longer possible: the fields are private, so you compare the handle address (huart == &huart2) or attach a pointer to your own data with HAL_UART_SetUserData when USE_HAL_UART_USER_DATA = 1.

RTOS: taking the block. With USE_HAL_MUTEX = 1, HAL_UART_Init creates a semaphore, and the block gets HAL_UART_AcquireBus and HAL_UART_ReleaseBus:

hal_status_t HAL_UART_AcquireBus(hal_uart_handle_t *huart, uint32_t timeout_ms)
{
  hal_status_t status;

  ASSERT_DBG_PARAM((huart != NULL));

  status = HAL_ERROR;

  if (HAL_OS_SemaphoreTake(&huart->semaphore, timeout_ms) == HAL_OS_OK)
  {
    status = HAL_OK;
  }

  return status;
}

HAL_OS_SemaphoreTake and its family come from os_port/: in freertos/ they are FreeRTOS semaphores (hal_os_semaphore_t = SemaphoreHandle_t), in no_os/ a volatile uint32_t variable. Taking the block is the task's job: two tasks writing to one UART first take the block, then transmit. This does not replace the atomic state change (5б.3), it complements it.

Time base. HAL_Init sets up SysTick at one of three rates: HAL_TICK_FREQ_1KHZ (the default), _100HZ, _10HZ; HAL_IncTick adds to uwTick not one but the period in milliseconds. The tick priority is HAL_TICK_INT_LOWEST_PRIORITY; on the C5, with four priority bits, that is 15, the lowest, so the HAL_Delay-in-an-interrupt trap from 5а.6 has not gone away. HAL_InitTick is weak; as replacements timebases/ has three ready-made files, on a timer, on the RTC alarm and on the RTC wakeup; they are bound to a specific timer by aliases in stm32_hal_timebase.h (timebase_gethandle → mx_tim6_gethandle and so on). New is HAL_Delay_NoISR: a delay that does not need the tick interrupt. The tick handler is generated by CubeMX2 in mx_system.c:

void SysTick_Handler(void)
{
  HAL_IncTick();
  HAL_CORTEX_SYSTICK_IRQHandler();
}

The timer callback in HAL2 is called HAL_TIM_UpdateCallback, not HAL_TIM_PeriodElapsedCallback.

Configuration file. stm32c5xx_hal_conf.h (687 lines in the template) holds only HAL keys: system ones (USE_HAL_TICK_INT_PRIORITY, USE_HAL_FLASH_PREFETCH), USE_HAL_MUTEX, the three check keys from 5б.3 and a block for each of 42 modules: USE_HAL_UART_MODULE, USE_HAL_UART_CLK_ENABLE_MODEL, USE_HAL_UART_REGISTER_CALLBACKS, USE_HAL_UART_USER_DATA, USE_HAL_UART_GET_LAST_ERRORS, USE_HAL_UART_DMA. The template enables all 42 modules, the generated echo example enables 8. Crystal frequencies (HSE_VALUE and others) have moved out of it into stm32_external_env.h from the DFP, internal oscillators into the CMSIS device header; they are pulled in by the USE_EXTERNAL_ENV key. Module names have changed: what was HAL_UART_MODULE_ENABLED is now USE_HAL_UART_MODULE.


5б.5 What to replace with what: the table and porting

Every row is checked against the headers of both versions: HAL1 from the STM32U5xx_DFP 2.2.1 pack, HAL2 from STM32CubeC5 2.1.0.

Task HAL1 HAL2
set up a UART HAL_UART_Init(&h) with h.Instance, h.Init HAL_UART_Init(&h, HAL_UART2) + HAL_UART_SetConfig(&h, &cfg)
block clock __HAL_RCC_USART2_CLK_ENABLE() in MspInit HAL_RCC_USART2_EnableClock() in your own code
blocking transmit HAL_UART_Transmit(h, const uint8_t *, uint16_t, Timeout) HAL_UART_Transmit(h, const void *, uint32_t size_byte, uint32_t timeout_ms)
blocking receive HAL_UART_Receive HAL_UART_Receive (length uint32_t)
interrupt transmit HAL_UART_Transmit_IT HAL_UART_Transmit_IT; without the key, no HAL_BUSY (5б.3)
DMA transmit HAL_UART_Transmit_DMA + __HAL_LINKDMA HAL_UART_SetTxDMA(&h, &hdma) + HAL_UART_Transmit_DMA
reception until idle with DMA HAL_UARTEx_ReceiveToIdle_DMA HAL_UART_ReceiveToIdle_DMA
end of reception HAL_UART_RxCpltCallback(h), HAL_UARTEx_RxEventCallback(h, Size) HAL_UART_RxCpltCallback(h, size_byte, rx_event)
block errors HAL_UART_GetError HAL_UART_GetLastErrorCodes (with USE_HAL_UART_GET_LAST_ERRORS)
configure a pin HAL_GPIO_Init(GPIOA, &init), pins in init.Pin, returns nothing HAL_GPIO_Init(HAL_GPIOA, HAL_GPIO_PIN_5, &cfg), returns hal_status_t
write, toggle HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET), HAL_GPIO_TogglePin HAL_GPIO_WritePin(HAL_GPIOA, HAL_GPIO_PIN_5, HAL_GPIO_PIN_SET), HAL_GPIO_TogglePin
I2C, memory read HAL_I2C_Mem_Read(h, DevAddress, MemAddress, MemAddSize, …) HAL_I2C_MASTER_MemRead(h, device_addr, memory_addr, memory_addr_size, …)
SPI, exchange HAL_SPI_TransmitReceive(h, pTxData, pRxData, Size, Timeout) HAL_SPI_TransmitReceive(h, p_tx_data, p_rx_data, count_packet, timeout_ms)
PWM: start, duty HAL_TIM_PWM_Start(&h, TIM_CHANNEL_1), __HAL_TIM_SET_COMPARE HAL_TIM_OC_StartChannel(&h, HAL_TIM_CHANNEL_1), HAL_TIM_OC_SetCompareUnitPulse
timer period HAL_TIM_PeriodElapsedCallback HAL_TIM_UpdateCallback
delay, ticks HAL_Delay(Delay), HAL_GetTick() HAL_Delay(delay_ms), HAL_GetTick()
NVIC HAL_NVIC_SetPriority(IRQn, 5, 0) HAL_CORTEX_NVIC_SetPriority(IRQn, HAL_CORTEX_NVIC_PREEMP_PRIORITY_5, HAL_CORTEX_NVIC_SUB_PRIORITY_0)

A small detail with consequences: timer channels in HAL2 are numbered from zero in a row, HAL_TIM_CHANNEL_1 = 0, HAL_TIM_CHANNEL_2 = 1, while in HAL1 TIM_CHANNEL_2 is 0x00000004U. A number kept "as is" from old code will point to a different channel.

Porting by ST's steps. The "HAL1 to HAL2 — migration guide" (1.0.0) and the HAL2 Migrator package (from ST documentation, not verified: neither is on disk) propose this order: copy the project, replace the HAL1 drivers with HAL2, use the stm32_hal.h entry point instead of stm32xxxx_hal.h, then run the detection script hal1_detection.py (Python 3.8 or later; there is also an executable for Windows 11). It walks the sources, finds HAL1 calls and writes an HTML report with the places found; it does not edit the code itself. A separate -d stub mode inserts stubs so that the project builds before the port is finished. Rewriting the calls is still done by hand.

What such a script looks for is shown by our very simple detect5b.py (not the ST tool: ten regular expressions for the types *_HandleTypeDef, *_InitTypeDef, MspInit, __HAL_*, the Instance and Init.* fields, constants without the HAL_ prefix). On mig_hal1.c, an interrupt-driven string transmission on HAL1, it found 28 places in 20 lines, on the ported mig_hal2.c none. Both files build. The most visible difference is in the callback:

void HAL_UART_TxCpltCallback(hal_uart_handle_t *huart)
{
    if (huart == &huart2)                    /* поля дескриптора закрыты: сравниваем адрес */
        tx_busy = 0;
}

MspInit is gone: clocks, pins and NVIC have moved into app_start between HAL_UART_Init and HAL_UART_SetConfig, and the eight huart2.Init.* lines into a local hal_uart_config_t that is no longer needed after SetConfig.


5б.6 Code size: one program on HAL1 and HAL2

There is one program: SysTick, pin PA5 as an output, USART2 on PA2/PA3 at 115200 baud; in the loop, Receive of one byte with a 500 ms timeout, if a byte came, Transmit it back, if not, toggle the LED. Built with arm-none-eabi-gcc 12.2.1 (Docker image stm-arm:1), -mcpu=cortex-m33 -Os, -ffunction-sections -fdata-sections, --gc-sections, newlib-nano. The bytes are counted from the linker map: by the input sections of each object file, without the heap and stack reserves, which differ between linker scripts.

Variant HAL, flash HAL, RAM UART handle Whole image, flash
U575, HAL1 (pack 2.2.1, HAL V1.3.0) 7293 9 148 10863
U575, HAL1 + USE_FULL_ASSERT 9145 9 148 12727
U575, HAL2 (preview beta.1.1) 3951 9 68 8211
C562, HAL2 (2.1.0) 3865 9 68 6615
C562, HAL2 + USE_HAL_CHECK_PARAM + USE_HAL_CHECK_PROCESS_STATE 4003 9 68 6753
C562, HAL2 + USE_ASSERT_DBG_PARAM + USE_ASSERT_DBG_STATE 5531 9 68 8309

The fair comparison is between the first and the third rows: one series, one compiler, the same options, the same application source. On the U575 the HAL code shrank from 7293 to 3951 bytes, by 46 %, and the handle from 148 to 68 bytes. The whole image went from 10863 to 8211, by 24 %: the rest is startup, system_*.c and the library, and each package brings its own. The image RAM is left out of the table on purpose: it is larger with HAL2 (353 bytes against 189), but that is not HAL: the C startup file of the DFP enters the C library through _start from newlib, which brings atexit and impure with it (244 bytes), while HAL holds 9 bytes in both cases. The C562 next to the U575 is a different chip and a different HAL2 version: rows 4 and 3 are close (3865 and 3951), but that is not a comparison of the same thing.

The price of the checks: the release keys (CHECK_PARAM and CHECK_PROCESS_STATE) cost 138 bytes, the HAL2 debug checks 1666, USE_FULL_ASSERT in HAL1 1852. Where the checks sit is visible in individual functions: HAL_UART_Transmit in HAL1 weighs 186 bytes with and without checks, since assert_param is only in Init; in HAL2 it grows from 184 to 252.

ST's own estimate in the README of the preview, on ST's "HAL versus HAL2" examples, in bytes and percent: pin toggle −1980 (32 %), I2C with interrupts −5104 (43 %), PWM −3187 (35 %), clock configuration −1970 (31 %). Our result is of the same order. Nothing was run on hardware: there is no board, and QEMU models neither U5 nor C5; what is checked is a warning-free build and the sizes.


5б.7 Pitfalls

if (status) after porting turns success into an error. On the C5 HAL_OK = 0xEAEAEAEA, on the U5 preview it is 0. Compare only against HAL_OK by name (5б.3).

A second start on a busy port silently corrupts the transfer. In the template USE_HAL_CHECK_PROCESS_STATE = 0: Transmit_IT on top of a running one returns HAL_OK and swaps the buffer, see the experiment in 5б.3. For multitasking code, enable the key (138 bytes) or enforce the order yourself.

A debug check fired, and the code went on. The assert_dbg_state_failed handler from the template returns. If you need a halt, write it in the handler.

HAL1 and HAL2 do not live together in one project. The same names have different meanings: HAL_OK exists in both enumerations. A file that includes the HAL2 stm32_hal.h and the HAL1 stm32u5xx_hal_def.h for the same U575 series does not build: five errors, four of them redeclaration of enumerator (HAL_OK, HAL_ERROR, HAL_BUSY, HAL_TIMEOUT). Files with the same name (stm32u5xx_hal_conf.h, stm32u5xx_hal_uart.h) also exist in both versions. Port the whole project.

Your own code in generated files. CubeMX2 overwrites generated/ entirely: of 20272 .c/.h files in the generated folders of the STM32CubeC5 examples, USER CODE BEGIN blocks exist in two. Your code goes into application/ or into the weak hooks pre_system_init_hook / post_system_init_hook.

Old macro and constant names. GPIO_PIN_5 → HAL_GPIO_PIN_5, HAL_UART_MODULE_ENABLED → USE_HAL_UART_MODULE, __HAL_RCC_*_CLK_ENABLE → HAL_RCC_*_EnableClock, timer channels from zero (5б.5).

huart->Instance in a callback. The fields are gone: compare the handle address or keep your data with HAL_UART_SetUserData (5б.4).

HAL2 for F1 or F4. It does not exist: of what is on disk, HAL2 is standard on C5 and a preview on U5, archived and NRND. F1, F4 and the rest use the HAL1 of sections 5 and 5а.


5б.8 Summary

Next: section 5в "One project twice on STM32F103: CMSIS and registers only versus HAL — 72 MHz clock, SysTick, GPIO and EXTI, UART with a ring, DMA, PWM, ADC, I2C and comparison" — the same F103 project twice: registers only and HAL, output, sizes and instructions side by side.

Open in the interactive handbook