基本過程如下
1.使用 GPIO_InitTypeDef 定義 GPIO 初始化結構體變量,以便下面用於存儲 GPIO 配置。
1.1在"stm32f10x_gpio.h"文件中可以找到gpio初始化結構體
typedef struct
{
uint16_t GPIO_Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
GPIOSpeed_TypeDef GPIO_Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIOSpeed_TypeDef */
GPIOMode_TypeDef GPIO_Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIOMode_TypeDef */
}GPIO_InitTypeDef;
1.2“實例化”
GPIO_InitTypeDef GPIO_InitStruct;
利用上面初始化的對象來配置“Pin”、“Speed”、“Mode”參數
GPIO_InitStruct.GPIO_Pin = LED_G_GPIO_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;//推輓輸出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
1.3.調用stm32f10x_gpio中的“GPIO_Init()” 來初始化
其函數原型爲:
GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct)
其中,各變量的含義爲
@param GPIOx: where x can be (A..G) to select the GPIO peripheral.
即配置GPIOA--GPIOG,根據不同的外設掛載在不同的GPIO上來配置
@param GPIO_InitStruct: pointer to a GPIO_InitTypeDef structure that contains the configuration information for the specified GPIO peripheral.
指向GPIO_InitTypeDef結構體的指針,該結構體包含指定GPIO外圍設備的配置信息。
所以在傳參時要加上取地址符“&”。
2.配置RCC時鐘
2.1配置相關的函數在“stm32f10x_rcc”裏面
void RCC_APB2PeriphClockCmd(uint32_t RCC_APB2Periph, FunctionalState NewState);
由rcc時鐘樹知道,因爲GPIO掛載在APB2上 ,所以調用RCC_APB2PeriphClockCmd()來配置時鐘,其函數原型爲
void RCC_APB2PeriphClockCmd(uint32_t RCC_APB2Periph, FunctionalState NewState);
各變量的含義爲:
@param RCC_APB2Periph: specifies the APB2 peripheral to gates its clock.
* This parameter can be any combination of the following values:
* @arg RCC_APB2Periph_AFIO, RCC_APB2Periph_GPIOA, RCC_APB2Periph_GPIOB,
* RCC_APB2Periph_GPIOC, RCC_APB2Periph_GPIOD, RCC_APB2Periph_GPIOE,
* RCC_APB2Periph_GPIOF, RCC_APB2Periph_GPIOG, RCC_APB2Periph_ADC1,
* RCC_APB2Periph_ADC2, RCC_APB2Periph_TIM1, RCC_APB2Periph_SPI1,
* RCC_APB2Periph_TIM8, RCC_APB2Periph_USART1, RCC_APB2Periph_ADC3,
* RCC_APB2Periph_TIM15, RCC_APB2Periph_TIM16, RCC_APB2Periph_TIM17,
* RCC_APB2Periph_TIM9, RCC_APB2Periph_TIM10, RCC_APB2Periph_TIM11
指定外圍設備來配置它的時鐘
* @param NewState: new state of the specified peripheral clock.
* This parameter can be: ENABLE or DISABLE.
選擇該時鐘的開或者關
3.將上述配置過程封裝成函數,便於下次使用
以配置LED_R爲例
void LED_R_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = LED_R_GPIO_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;//推輓輸出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_R_GPIO_PORT, &GPIO_InitStruct);
RCC_APB2PeriphClockCmd(LED_R_GPIO_CLK, ENABLE);
}
至此,初始化完畢,可以在main函數中調用,又因爲板子上的燈是低電平亮,所以一旦配置完成默認輸出低電平,燈亮
int main(void)
{
while(1)
{
LED_R_GPIO_Config();
}
}
若要控制GPIO向其發送高/低電平,可以使用stm32f10x_gpio中的
//至1
GPIO_ResetBits(LED_G_GPIO_PORT, LED_G_GPIO_PIN);
//至0
GPIO_SetBits(LED_G_GPIO_PORT, LED_G_GPIO_PIN);