stm32操作GPIO
软件环境:环境搭建https://www.cnblogs.com/bliss-/p/15043021.html
硬件环境:
基于普中定通stm32ZGT6开发板
概述:
GPIO是STM32非常重要的功能,在大多数控制系统中都会使用到GPIO,GPIO【General-purpose input/output】,通用输入输出端口,可以用于输出高低电平,也可以作为输入采集外部电平。
在我这块开发板上可以看到控制LED引脚在PF9和PF10引脚上,同时LED二极管的一端为VCC3.3,我们只需要控制另一端将其拉低或者升高就可以控制其亮或者灭。
软件流程
基本流程比较简单
- 外设时钟需要根据具体的IO端口查看手册中的时钟树,也可以看库函数中的预设参数得知GPIO时钟都在AHB1时钟总线上挂着
/**
* @brief Enables or disables the AHB1 peripheral clock.
* @note After reset, the peripheral clock (used for registers read/write access)
* is disabled and the application software has to enable this clock before
* using it.
* @param RCC_AHBPeriph: specifies the AHB1 peripheral to gates its clock.
* This parameter can be any combination of the following values:
* @arg RCC_AHB1Periph_GPIOA: GPIOA clock
* @arg RCC_AHB1Periph_GPIOB: GPIOB clock
* @arg RCC_AHB1Periph_GPIOC: GPIOC clock
* @arg RCC_AHB1Periph_GPIOD: GPIOD clock
* @arg RCC_AHB1Periph_GPIOE: GPIOE clock
* @arg RCC_AHB1Periph_GPIOF: GPIOF clock
* @arg RCC_AHB1Periph_GPIOG: GPIOG clock
* @arg RCC_AHB1Periph_GPIOG: GPIOG clock
* @arg RCC_AHB1Periph_GPIOI: GPIOI clock
* @arg RCC_AHB1Periph_GPIOJ: GPIOJ clock (STM32F42xxx/43xxx devices)
* @arg RCC_AHB1Periph_GPIOK: GPIOK clock (STM32F42xxx/43xxx devices)
* @arg RCC_AHB1Periph_CRC: CRC clock
* @arg RCC_AHB1Periph_BKPSRAM: BKPSRAM interface clock
* @arg RCC_AHB1Periph_CCMDATARAMEN CCM data RAM interface clock
* @arg RCC_AHB1Periph_DMA1: DMA1 clock
* @arg RCC_AHB1Periph_DMA2: DMA2 clock
* @arg RCC_AHB1Periph_DMA2D: DMA2D clock (STM32F429xx/439xx devices)
* @arg RCC_AHB1Periph_ETH_MAC: Ethernet MAC clock
* @arg RCC_AHB1Periph_ETH_MAC_Tx: Ethernet Transmission clock
* @arg RCC_AHB1Periph_ETH_MAC_Rx: Ethernet Reception clock
* @arg RCC_AHB1Periph_ETH_MAC_PTP: Ethernet PTP clock
* @arg RCC_AHB1Periph_OTG_HS: USB OTG HS clock
* @arg RCC_AHB1Periph_OTG_HS_ULPI: USB OTG HS ULPI clock
* @param NewState: new state of the specified peripheral clock.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void RCC_AHB1PeriphClockCmd(uint32_t RCC_AHB1Periph, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_RCC_AHB1_CLOCK_PERIPH(RCC_AHB1Periph));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
RCC->AHB1ENR |= RCC_AHB1Periph;
}
else
{
RCC->AHB1ENR &= ~RCC_AHB1Periph;
}
}
- 我们这里作为GPIO输出使用,所以我们将GPIO初始化为以下模式
GPIO_InitTypeDef GPIO_LED;
/**GPIOF端口时钟使能**/
RCC_AHB1PeriphClockCmd(LED_GPIO_CLK,ENABLE);
GPIO_LED.GPIO_Mode = GPIO_Mode_OUT; //输出模式
GPIO_LED.GPIO_OType = GPIO_OType_PP; //推挽
GPIO_LED.GPIO_PuPd = GPIO_PuPd_DOWN; //内部上拉
GPIO_LED.GPIO_Speed = GPIO_Low_Speed; //设置为低速率模式
GPIO_LED.GPIO_Pin = GPIO_Pin_10|GPIO_Pin_9; //设置引脚9和10
GPIO_Init(GPIOF,&GPIO_LED); //绑定到GPIOF端口并将设置项生效
- 最后可以调用输出高低电平的库函数实现控制LED开关
GPIO_ResetBits(GPIO_F,GPIO_Pin_10);
/*拉高引脚 控制LED灭*/
GPIO_SetBits(GPIOF,GPIO_Pin_10);