操作stm32的gpio需要三个步骤
1:使用rcc开启GPIO时钟
2:使用GPIO_Init函数初始化GPIO
3:使用输出或输入的函数控制GPIO口
1.RCC相关库函数
最常用的三个函数:
RCC AHB外设时钟控制:void RCC_AHBPeriphClockCmd(uint32_t RCC_AHBPeriph, FunctionalState NewState);
RCC APB2外设时钟控制:void RCC_APB2PeriphClockCmd(uint32_t RCC_APB2Periph, FunctionalState NewState);
RCC APB1外设时钟控制:void RCC_APB1PeriphClockCmd(uint32_t RCC_APB1Periph, FunctionalState NewState);
其中,第一个参数位选择外设,第二个参数为enable和disable
2.GPIO 相关库函数
常用函数为:
void GPIO_DeInit(GPIO_TypeDef* GPIOx);
void GPIO_AFIODeInit(void);
void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);
void GPIO_StructInit(GPIO_InitTypeDef* GPIO_InitStruct);
uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
uint16_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx);
uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
uint16_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx);
void GPIO_SetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void GPIO_ResetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void GPIO_WriteBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, BitAction BitVal);
void GPIO_Write(GPIO_TypeDef* GPIOx, uint16_t PortVal);
其中GPIO_DeInit函数为复位函数
GPIO_Init函数的作用为用结构体的参数来初始化GPIO口
GPIO输出函数:
void GPIO_SetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
可以把指定端口设置为高电平
void GPIO_ResetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
可以把指定端口设置为低电平
void GPIO_WriteBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, BitAction BitVal);
根据第三个参数的值设置指定端口
void GPIO_Write(GPIO_TypeDef* GPIOx, uint16_t PortVal);
可同时对16个端口进行写入操作
3.代码(A0口)
#include "stm32f10x.h" // Device header
int main(void)
{
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIOInint;
GPIOInint.GPIO_Mode=GPIO_Mode_Out_PP;
GPIOInint.GPIO_Pin=GPIO_Pin_0;
GPIOInint.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIOInint);
GPIO_ResetBits(GPIOA,GPIO_Pin_0);
while(1)
{
}
}
现象: