在STM32的固件庫和提供的例程中,到處都可以見到assert_param()的使用。如果打開任何一個例程中的stm32f10x_conf.h文件,就可以看到實際上assert_param是一個宏定義;
在固件庫中,它的作用就是檢測傳遞給函數的參數是否是有效的參數。
舉例說明:
assert_param(IS_USART_ALL_PERIPH(USARTx));
這句代碼用於檢查參數USARTx是否有效,其中IS_USART_ALL_PERIPH(USARTx)是一個宏定義,如下:
#define IS_USART_ALL_PERIPH(PERIPH) (((PERIPH) == USART1) || \ ((PERIPH) == USART2) || \ ((PERIPH) == USART3) || \ ((PERIPH) == USART4) || \ ((PERIPH) == USART5) || \ ((PERIPH) == USART6) || \ ((PERIPH) == USART7) || \ ((PERIPH) == USART8))
宏定義的功能是參數USARTx是USART1~USART8其中的一個,表示參數USARTx有效,返回true,否則返回false。
assert_param()也是一個宏,定義在stm32f0xx_conf.h中,具體如下:
/* #define USE_FULL_ASSERT 1 */ /* 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 */
如果USE_FULL_ASSERT宏定義了,則執行下面的代碼:
#define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) //表示參數expr為false,則執行后面的assert_failed()函數,__FILE__, __LINE__是標准庫函數中的宏定義,表示文件名和行號
void assert_failed(uint8_t* file, uint32_t line); //申明該函數
如果USE_FULL_ASSERT沒有宏定義,則執行((void)0),即什么都不做。
assert_failed()函數的具體實現在main.c中(在任何一個例程中的main.c中都有這個函數的模板),內容如下:
1 #ifdef USE_FULL_ASSERT 2 3 /** 4 * @brief Reports the name of the source file and the source line number 5 * where the assert_param error has occurred. 6 * @param file: pointer to the source file name 7 * @param line: assert_param error line source number 8 * @retval None 9 */ 10 void assert_failed(uint8_t* file, uint32_t line) 11 { 12 /* User can add his own implementation to report the file name and line number, 13 ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ 14 15 /* Infinite loop */ 16 while (1) 17 { 18 } 19 } 20 #endif
assert_failed()函數給了一個框架,內部具體實現需要開發者自己去寫,通常是用串口把文件名和行號打印出來。
要使assert_failed()函數生效,需要宏定義USE_FULL_ASSERT,並且包含頭文件stm32f0xx_conf.h;在stm32f0xx.h文件中,有如下代碼:
#ifdef USE_STDPERIPH_DRIVER #include "stm32f0xx_conf.h" #endif
只要宏定義USE_STDPERIPH_DRIVER,就能包含頭文件stm32f0xx_conf.h了。
宏定義可以在文件中寫,也可以直接在軟件中設置,如下圖:
注意:assert_failed()函數一般在代碼調試時使用,可以幫助開發者檢查輸入參數無效的錯誤,但由於assert_failed()函數會影響代碼執行效率,在程序release時,需要屏蔽掉,將宏定義USE_FULL_ASSERT注釋即可。