Here I will explain how to configure the general purpose input/output ports (GPIO) of the STM32F4xx micro controllers. Like most other micro controllers the GPIO pins can have multiple configurations and mappings.
In this small tutorial, I’ll show the high level functions provided by the GPIO peripheral provided by CooCox. In another post I will dig in the deeper, low level details by explaining the registers needed for configuring the GPIO ports on the STM32F4xx devices.
The CooCox GPIO peripheral is a great library for easy setup and understanding your micro controller. The GPIO_InitTypeDef is a structure defined in the ST’s library and it contains all the properties you can configure on the corresponding peripheral:
- Pull up/pull down resistors
The GPIO ports require a clock to operate, by default this clock is not connected to the peripheral and needs to be configured. On the STM32F4xx the GPIO ports are connected to the AHB1 bus (the first out of 3 advanced high-performance buses). Enabling the clock:
The GPIO’s clock can be anything of the following:
On the STM32F4 the GPIO can have up to 4 modes (check the datasheet for which modes are available for which pin):
- GPIO_Mode_OUT for digital output
- GPIO_Mode_IN for digital input
- GPIO_Mode_AN for analog input
- GPIO_Mode_AF for the alternate functions (like SPI, I²C, USART, …)
The type indicates the hardware configuration of the pin which can be:
- GPIO_OType_PP, a push-pull is driving the output
- GPIO_OType_OD, the output is open-drain
Next we can configure pull up, pull down resistors or nothing at all for each pin:
- GPIO_PuPd_NOPULL, no resistor connected
- GPIO_PuPd_UP, pin is connected to a pull up resistor
- GPIO_PuPd_DOWN, pin is connect to a pull down resistor
Let us assume that we would like to configure pins 11 and 12 of PortD as digital outputs at full speed, with a push-pull and no pull up or pull down:
GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOD, &GPIO_InitStructure);
I’ve written this post also for myself as a kind of a cheat sheet when I need to configure my general purpose I/O ports.