This time, I will use HAL’s assert_param().
The following is the development environment at the time of submission.
PC: Windows 10 OS
IDE: STM32CubeIDE Version1.3.0
Configurator: STM32CubeMX Version5.6.0
Board: STM32Nucleo-F401RE
What is an assert?
Assert is an English word that means to assert or assert.
An assertion is a mechanism for describing the conditions that should normally be met when a program is executed, and checking them at runtime.
Developers place assertions at arbitrary locations in the program, and describe the conditions that should be met when the program reaches those locations. At runtime, the program evaluates the conditions described in the assertions, and if they are not met, the program raises an error or exception, or displays a message.
How to use assertions in HAL?
HAL allows you to use the assert_param() macro, but it is disabled by default.
Try opening Core\Inc\stm32f4xx_hal_conf.h in your project.
You will find the following in line 422. (Comments are omitted)
#ifdef USE_FULL_ASSERT
#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__))
void assert_failed(uint8_t* file, uint32_t line);
#else.
#define assert_param(expr) ((void)0U)
#endif
So, for example.
#define USE_FULL_ASSERT 1
So, for example, if you define #define USE_FULL_ASSERT 1, you can make an assertion and run assert_failed() when the condition fails.
Assert_failed() is written in main.c, and the process is written in that file.
Assert_failed(), for example, can be written in the following code, and if printf() output is enabled, it will tell you in which file and on which line the assertion error occurred.
void assert_failed(uint8_t *file, uint32_t line)
{
printf("Assert failed: file %s on line %d\r\n", file, line);
}
Try coding
Now, let’s check the behavior of assert_failed() by making sure that it actually takes place.
First, we will prepare a function to output printf() in the View on the debugger by referring to the article Debugging with STM32 printf.
We will use the project created in Using STM32 HAL to access memory via I2C.
The assert_failed() function will use the one described above, so please code it.
Now let’s rewrite the fourth argument of the HAL_I2C_Mem_Write() function to 2, for example, so that an error occurs.
s = HAL_I2C_Mem_Write(&hi2c1, DEVICE_ADDR, 0, 2, sbuf, BYTES_PER_PAGE, 1000);
Build and Run – Debug.
HAL_Init() will stop the program, so click SWV ITM Data Console and press Start Trace button. (part 0 of the following image)
![]()
After Run – Resume, an error message was displayed in the SWV ITM Data Console.
How did you like it?
Were you able to get assert_failed() to work in your environment?
HAL API functions have assert_param() implemented in various places.
You can learn a lot by understanding its contents.
Please try to use arrset_param().





