STM32的GPIO操作
正点原子ppt:
1个初始化函数:
void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);
2个读取输入电平函数:
uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
uint16_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx);
2个读取输出电平函数:
uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
uint16_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx);
4个设置输出电平函数:
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);
硬件LED0-->PB.5 LED1-->PE.5
//初始化PB5和PE5为输出口.并使能这两个口的时钟
//LED IO初始化
void LED_Init(void)
{
/*
硬件: LED0-PB5与LED1-PE5 低电平亮灯 使用推免输出
初始化IO口是对GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);进行操作
1.设置的时钟
*/
GPIO_InitTypeDef GPIO_InitStructure;
//时钟设置
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOE,ENABLE);
//对IO口,IO模式配置
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //LED0-->PB.5 端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOB,&GPIO_InitStructure); //初始化GPIOB.5
//参数里的GPIOB是地址,&GPIO_InitStructure也是指针GPIO_InitStructure的地址
//#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE)
//#define GPIOB_BASE (APB2PERIPH_BASE + 0x0C00)
//#define APB2PERIPH_BASE (PERIPH_BASE + 0x10000)
//#define PERIPH_BASE ((uint32_t)0x40000000) /*!< Peripheral base address in the alias region */
GPIO_SetBits(GPIOB,GPIO_Pin_5); //PB.5 输出高
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //LED1-->PE.5 端口配置, 推挽输出
GPIO_Init(GPIOE, &GPIO_InitStructure); //推挽输出 ,IO口速度为50MHz
GPIO_SetBits(GPIOE,GPIO_Pin_5); //PE.5 输出高
}
//寄存器操作 /*- GPIOx_CRL :端口配置低寄存器 - GPIOx_CRH:端口配置高寄存器 - GPIOx_IDR:端口输入寄存器 - GPIOx_ODR:端口输出寄存器 - GPIOx_BSRR:端口位设置/清除寄存器 - GPIOx_BRR :端口位清除寄存器 - GPIOx_LCKR:端口配置锁存寄存器 */ /* 使能IO口时钟。配置寄存器RCC_APB2ENR。 初始化IO口模式。配置寄存器GPIOx_CRH/CRL 操作IO口,输出高低电平。配置寄存器GPIOX_ODR或者BSRR/BRR */ void LED_Init(void) { //PB PE时钟打开 APB2外设时钟使能寄存器(RCC_APB2ENR) 的BIT3开启PB时钟 BIT6开启PE时钟 //与0或运算不改变该位,与1或运算变为1 RCC->APB2ENR |= 1<<3; //打开PB时钟 RCC->APB2ENR |= 1<<6; //打开PE时钟 //PB.5 GPIOB->CRL &=0xff0fffff; //让PB.5端口的4位清0 GPIOB->CRL |=0X00300000; //CNF=00 MODE=11 GPIOB->ODR |=1<<5; //PB.5高电平 //PE.5 GPIOE->CRL &=0xff0fffff; //让PB.5端口的4位清0 GPIOE->CRL |=0X00300000; //CNF=00 MODE=11 GPIOE->ODR |=1<<5; //PE.5高电平 }
浙公网安备 33010602011771号