Saturday, September 28, 2013

Programming Example : GPIO - Alternative Function Mode

#include "stm32f2xx.h"

void GPIO_Config_AFMode(void);

int main(void)

{
  GPIO_Config_AFMode(); // to be used as an USART Tx/Rx I/Os
}

void GPIO_Config_AFMode(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* Enable GPIOD Clock */

  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

  /* Connect PD5, PD6 to USART2_Tx/Rx */

  GPIO_PinAFConfig(GPIOD, GPIO_PinSource5, GPIO_AF_USART2);
  GPIO_PinAFConfig(GPIOD, GPIO_PinSource6, GPIO_AF_USART2);

  /* Configure PD5, PD6 as alternative function */

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
}

/*
<Alternative function mode>

1. Enable GPIOA's AHB interface clock

@reg   RCC->AHB1ENR
@fn    void RCC_AHB1PeriphClockCmd(uint32_t RCC_AHB1Periph, FunctionalState NewState)
@param RCC_AHB1Periph_GPIOA, ENABLE
@ref   stm32f2xx_rcc.h, stm32f2xx.h

2. Connect GPIO pin to USART_Tx/Rx

@reg   GPIOx->AFR
@fn    void GPIO_PinAFConfig(GPIO_TypeDef* GPIOx, uint16_t GPIO_PinSource, uint8_t GPIO_AF)
@param GPIOC, GPIO_PinSource5, GPIO_PinSource6, GPIO_AF_USART2
@ref   stm32f2xx_gpio.h

3. Configure GPIO pin in alternative function mode

@reg   GPIOx->MODER, GPIOx->OSPEEDR, GPIOx->OTYPER, GPIOx->PUPDR
@fn    void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct)
@param GPIOG, GPIO_Pin_5, GPIO_Pin_6, GPIO_Mode_AF, GPIO_Speed_50MHz, GPIO_OType_PP, GPIO_PuPd_UP
@ref   stm32f2xx.h, stm32f2xx_gpio.h
*/

No comments:

Post a Comment