本节按步骤描述了如何初始化和设置任意外设。这里PPP代表任意外设。
1. 在主应用文件中,声明一个结构PPP_InitTypeDef,例如:
PPP_InitTypeDef PPP_InitStructure;
这里PPP_InitStructure是一个位于内存中的工作变量,用来初始化一个或者多个外设PPP。
2. 为变量PPP_InitStructure的各个结构成员填入允许的值。可以采用以下2种方式:
a)按照如下程序设置整个结构体
PPP_InitStructure.member1 = val1;
PPP_InitStructure.member2 = val2;
PPP_InitStructure.memberN = valN; /* where N is the number of the structure members */
以上步骤可以合并在同一行里,用以优化代码大小:
PPP_InitTypeDef PPP_InitStructure = { val1, val2,.., valN}
b)仅设置结构体中的部分成员:这种情况下,用户应当首先调用函数PPP_SturcInit(..)来初始化变量PPP_InitStructure,然后再修改其中需要修改的成员。这样可以保证其他成员的值(多为缺省值)被正确填入。
PPP_StructInit(&PPP_InitStructure);
PP_InitStructure.memberX = valX;
PPP_InitStructure.memberY = valY;/*where X and Y are the members the user wants to configure*/
3. 调用函数PPP_Init(..)来初始化外设PPP。
4. 在这一步,外设PPP已被初始化。可以调用函数PPP_Cmd(..)来使能之。PPP_Cmd(PPP, ENABLE); 可以通过调用一系列函数来使用外设。每个外设都拥有各自的功能函数。更多细节参阅 Section3 外设固件概述。
注:1. 在设置一个外设前,必须调用以下一个函数来使能它的时钟:
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_PPPx, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_PPPx, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PPPx, ENABLE);
2. 可以调用函数PPP_Deinit(..)来把外设PPP的所有寄存器复位为缺省值:
PPP_DeInit(PPP)
3. 在外设设置完成以后,继续修改它的一些参数,可以参照如下步骤:
PPP_InitStucture.memberX = valX;
PPP_InitStructure.memberY = valY; /* where X and Y are the only members that user wants to modify*/
PPP_Init(PPP, &PPP_InitStructure);
例如GPIO初始化
GPIO_InitTypeDef GPIO_InitStructure;
/* LED1 -> PB8 , LED4 -> PE1
*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 |GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 |GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOE, &GPIO_InitStructure);
注意,在固件库中,GPIO 没有GPIO_Cmd 的函数,因此这
个步骤省略。