一、说明
在STM32的固件库和提供的例程中,到处都可以见到assert_param()的使用。如果打开任何一个例程中的stm32f10x_conf.h文件,就可以看到实际上assert_param是一个宏定义;
在固件库中,它的作用就是检测传递给函数的参数是否是有效的参数。
如果USE_FULL_ASSERT宏定义了,则执行下面的代码:
#define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) //表示参数expr为false,则执行后面的assert_failed()函数,__FILE__, __LINE__是标准库函数中的宏定义,表示文件名和行号
如果USE_FULL_ASSERT没有宏定义,则执行((void)0),即什么都不做。
二、使用
assert_failed()函数的具体实现在main.c中(在任何一个例程中的main.c中都有这个函数的模板),内容如下:
#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 %d\r\n", file, line) */
/* Infinite loop */
while (1)
{
}
}
#endif
assert_failed()函数给了一个框架,内部具体实现需要开发者自己去写,通常是用串口把文件名和行号打印出来。
要使assert_failed()函数生效,需要宏定义USE_FULL_ASSERT
注意:assert_failed()函数一般在代码调试时使用,可以帮助开发者检查输入参数无效的错误,但由于assert_failed()函数会影响代码执行效率,在程序release时,需要屏蔽掉,将宏定义USE_FULL_ASSERT注释即可。