STM32固件庫(kù)中assert_param的作用
在學(xué)習(xí)stm32庫(kù)函數(shù)過(guò)程中,筆者遇到大量的assert_param語(yǔ)句。經(jīng)查明,assert_param的作用就是用來(lái)判斷傳遞給函數(shù)的參數(shù)是否是有效值。
以下是從固件庫(kù)中復(fù)制粘貼的:
void RCC_APB2PeriphClockCmd(uint32_t RCC_APB2Periph, FunctionalState NewState)
{
assert_param(IS_RCC_APB2_PERIPH(RCC_APB2Periph));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
RCC->APB2ENR |= RCC_APB2Periph;
}
else
{
RCC->APB2ENR &= ~RCC_APB2Periph;
}
}
筆者用keil中的鼠標(biāo)右鍵“go to definition xxxxxx""
查看assert_param(IS_RCC_APB2_PERIPH(RCC_APB2Periph));語(yǔ)句中IS_RCC_APB2_PERIPH的定義,得到如下結(jié)果:
#define RCC_APB2Periph_AFIO((uint32_t)0x00000001)
#define RCC_APB2Periph_GPIOA((uint32_t)0x00000004)
#define RCC_APB2Periph_GPIOB((uint32_t)0x00000008)
#define RCC_APB2Periph_GPIOC((uint32_t)0x00000010)
#define RCC_APB2Periph_GPIOD((uint32_t)0x00000020)
#define RCC_APB2Periph_GPIOE((uint32_t)0x00000040)
#define RCC_APB2Periph_GPIOF((uint32_t)0x00000080)
#define RCC_APB2Periph_GPIOG((uint32_t)0x00000100)
#define RCC_APB2Periph_ADC1((uint32_t)0x00000200)
#define RCC_APB2Periph_ADC2((uint32_t)0x00000400)
#define RCC_APB2Periph_TIM1((uint32_t)0x00000800)
#define RCC_APB2Periph_SPI1((uint32_t)0x00001000)
#define RCC_APB2Periph_TIM8((uint32_t)0x00002000)
#define RCC_APB2Periph_USART1((uint32_t)0x00004000)
#define RCC_APB2Periph_ADC3((uint32_t)0x00008000)
#define RCC_APB2Periph_TIM15((uint32_t)0x00010000)
#define RCC_APB2Periph_TIM16((uint32_t)0x00020000)
#define RCC_APB2Periph_TIM17((uint32_t)0x00040000)
#define RCC_APB2Periph_TIM9((uint32_t)0x00080000)
#define RCC_APB2Periph_TIM10((uint32_t)0x00100000)
#define RCC_APB2Periph_TIM11((uint32_t)0x00200000)
#define IS_RCC_APB2_PERIPH(PERIPH) ((((PERIPH) & 0xFFC00002) == 0x00) && ((PERIPH) != 0x00))
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
以這個(gè)函數(shù)為例:
void RCC_APB2PeriphClockCmd(uint32_t RCC_APB2Periph,
FunctionalState
NewState)的作用就是使能APB2外設(shè)時(shí)鐘,而當(dāng)我們調(diào)用這個(gè)函數(shù)的時(shí)候,所給它的參數(shù)必須是以上規(guī)定的幾個(gè)數(shù)值中的一個(gè),不可隨意填一個(gè)未定義的值進(jìn)去。assert_param()函數(shù)有效的解決了這個(gè)問(wèn)題,它在函數(shù)運(yùn)行之初,便判斷工程師所給的值是否為這個(gè)函數(shù)的有效值,以達(dá)到糾錯(cuò)報(bào)錯(cuò)的功能。同時(shí),當(dāng)我們不知道這個(gè)函數(shù)該填入什么樣的值的時(shí)候,就可以使用keil中提供的右鍵“go
to definition xxxx"查看assert_param()括號(hào)中的定義。