我们知道在GPIO初始化的时候需要配置结构体,如果配置多个GPIO的话就得多次配置结构体,那么为什么我们不直接封装一个函数来直接掉用函数直接对GPIO的某个引脚进行初始化呢,下面我就讲解怎么对GPIO初始化进行封装。
u8 GPIO_QuickInit(int instance, int GPIO_Pin_x, GPIOMode_TypeDef Mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
switch(instance)
{
case HW_GPIOA:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_x;
if( GPIO_Pin_x == GPIO_Pin_13 || GPIO_Pin_x == GPIO_Pin_14 || GPIO_Pin_x == GPIO_Pin_15 ){
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
}
GPIO_InitStructure.GPIO_Mode = Mode;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
break;
case HW_GPIOB:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_x;
if(GPIO_Pin_x == GPIO_Pin_4 || GPIO_Pin_x == GPIO_Pin_3 ){
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
}
GPIO_InitStructure.GPIO_Mode = Mode;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
break;
case HW_GPIOC:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_x;
GPIO_InitStructure.GPIO_Mode = Mode;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
break;
case HW_GPIOD:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_x;
GPIO_InitStructure.GPIO_Mode = Mode;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
break;
case HW_GPIOE:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_x;
GPIO_InitStructure.GPIO_Mode = Mode;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStructure);
break;
default:
return 0;
}
return 1;
}
上面就是GPIO快速初始化的函数封装,有人可能会对这两个函数疑惑 RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
这个是因为PA13-15是有特殊功能的需要我们用这个函数使能时钟
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
STM32F10x系列的MCU复位后,PA13/14/15 & PB3/4默认配置为JTAG功能。有时我们为了充分利用MCU I/O口的资源,会把这些端口设置为普通I/O口。上述函数就是禁用此功能。