STMF4DISCOVERY Board: init mode failed (unable to connect to the target)


I set up VSCode, PIO, and ST-Link as required by this official tutorial for my STM32F4DISCOVERY board. The first time the sample code compiled, uploaded to the board, and debugged successfully. However, the second time, I couldn’t connect to the board and got this error:

Error: init mode failed (unable to connect to the target)
in procedure 'program'
** OpenOCD init failed **
shutdown command invoked

*** [upload] Error 1

A potential reason might be that I had Eclipse running openOCD at the same time. After that, neither Eclipse nor openOCD can connect to the board, even though the USB connection is shown in the Device Manager.

Failed attempts

I tried a bunch of solutions but none worked:

  1. Disconnect the USB and try again
  2. Connect under reset and clear chip through ST-Utility
  3. Try different reset configurations as shown in this thread
  4. Reset the board didn’t work. Got this error:
Error: timed out while waiting for target halted
embedded:startup.tcl:530: Error: ** Unable to reset target **
in procedure 'program' 
in procedure 'program_error' called at file "embedded:startup.tcl", line 567
at file "embedded:startup.tcl", line 530
*** [upload] Error 1

Set up

I’m using Windows 10 with latest VSCode and PIO. The board is a STM32F407G-DISC1 with latest firmware.

This is my platformio.ini:

platform = ststm32
board = disco_f407vg
framework = stm32cube

This is the debug message before the error occurs:

HARDWARE: STM32F407VGT6 168MHz, 128KB RAM, 1MB Flash
DEBUG: Current (stlink) On-board (stlink) External (blackmagic, cmsis-dap, jlink)
 - framework-stm32cubef4 1.25.2
 - tool-dfuutil 1.9.200310
 - tool-ldscripts-ststm32 0.1.0
 - tool-openocd 2.1100.0 (11.0)
 - tool-stm32duino 1.0.2
 - toolchain-gccarmnoneeabi 1.70201.0 (7.2.1)
LDF: Library Dependency Finder ->
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 48 compatible libraries
Scanning dependencies...
No dependencies
Building in release mode
Checking size .pio\build\disco_f407vg\firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [          ]   0.0% (used 44 bytes from 131072 bytes)
Flash: [          ]   0.1% (used 1228 bytes from 1048576 bytes)
Configuring upload protocol...
AVAILABLE: blackmagic, cmsis-dap, jlink, mbed, stlink
CURRENT: upload_protocol = stlink
Uploading .pio\build\disco_f407vg\firmware.elf

I managed to restore the connection by clearing the chip in ST-Utility, and then press on “Disconnect from the target” to disconnect the Utility. Now, I can connect to the board with no problem on both Eclipse and VSCode.