I got an STM32F4-Discovery board a while ago, but have not had much time to play with it. So the other day I decided to check out the GPIO functions to get myself familiarized with the board.

STM32F4-Discovery breaks out most (more on this later) of its 16-bit GPIO pins (GPIOA through GPIOE) so it is easy enough to use these GPIO pins to interface external devices.

Using the GPIOs is also fairly straightforward. For instance, to toggle PB0 we can initialize port B (GPIOB) and configure PB0 as an output and use either BSRRL/BSRRH in GPIOB or GPIO_SetBits function to toggle the pin. Here is an example using Atollic TrueSTUDIO:

#include <stm32f4xx.h>
#include <stm32f4xx_gpio.h>

void main()
{
    GPIO_InitTypeDef GPIO_InitStruct;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
    
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT; 
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; 
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOB, &GPIO_InitStruct);

    while (1)
    {
        GPIOB->BSRRL = GPIO_Pin_0;
        GPIOB->BSRRH = GPIO_Pin_0;
    }
}

The code above generates a square wave of roughly 4 MHz at PB0 by rapidly toggling the pin, nothing fancy.

Curiously enough, the discovery board breaks out all the GPIO pins except PA11 and PA12. At first I did not pay enough attention to this and configured all port A pins as output in a test setup. After uploading the code I quickly realized that I had lost the ability to debug and upload programs through USB.

Realizing that I might have “bricked” the device somehow, I used the STM32 ST-Link utility to try loading a test HEX file just to be sure. But all I got was the dreaded “Cannot connect to ST-LINK!” error message. At this point, I started wondering whether by writing to PA11 and PA12 could have caused this problem.

The STM32F4-Discovery board uses either SWD (Serial Wire Debug) or JTAG for programming, and a bootloader is in place for serial communications via the USB. And by default, programming is done via USB using SWD. By checking the user’s manual, it became clear to me that the issue was caused by re-configuring PA11 and PA12 since these two pins are dedicated as DM DP pins for USB communications. By re-configuring these pins in code we essentially interfered with the USB communication mechanism. This may be the reason why these two pins were not broken out in the first place.

Solution

Fortunately, this problem can be corrected using the STM32 ST-Link UTILITY. When the USB cable is first plugged in, hold down the reset button and upon release immediately select Target->Erase Chip. You may need to try this a few times to get the timing correctly. Once the chip is erased, the bootloader will be able to utilize the USB connection correctly and you will be able to use USB port to program your STM32F4-Discovery board again.

Be Sociable, Share!