OpenOCD + ST-LinkでFirmware書き込み

OpenOCDを使ってSTM32F401 Nucleo-64にST-Link経由でFirmwareを書き込む。

OpenOCDとST-Linkドライバのインストール

Arch Linuxなら以下のコマンドでインストールする。

$ pacman -S openocd stlink

Firmwareを書き込む

OpenOCDで指定できるinterface, target, boardの設定ファイルは/usr/share/openocd/scriptsに配置されている。

OpenOCDで接続する

STM32F401 Nucleo-64 boardのUSB接続の場合

f:id:ryochack:20171103201550j:plain:w480

$ openocd -f board/st_nucleo_f4.cfg

もしくは、

$ openocd -f interface/stlink-v2-1.cfg -f target/stm32f4x.cfg

STM32F401 Chip + 中華ST-Linkの場合

f:id:ryochack:20171103201242j:plain:w480

Nucleoボードを使っているのなら中華ST-Linkを使う必要はないが、試した結果を書き残しておく。

$ openocd -f interface/stlink-v2.cfg -f target/stm32f4x.cfg

なお、Nucleoボード上のSWDコネクタ(CN4)は以下のピンアサインとなっている。

Pin CN4
1 VDD_TARGET
2 SWCLK
3 GND
4 SWDIO
5 NRST
6 SWO

※中華ST-Linkでは、一度ST-LinkのFirmwareをアップデートした後に書き込みに成功するようになった。 (書き込みに成功している中華ST-LinkのFW versionはV2J28S7)

telnetで書き込む

上記手順でOpenOCDで接続後、別のterminalからtelnetを起動する。

$ telnet localhost 4444

telnet上で以下のコマンドを実行することでFirmwareを書き込む。

> reset halt
> flash write_image erase ${elf_file_absolute_path}

telnet無しでFirmwareを書き込む

上記の方法だと、OpenOCDとは別にtelnetを起動する必要があり、若干煩わしい。 そこで、Firmwareを書き込む手順を記載したOpenOCDのconfigファイルを用意し、OpenOCDだけで書き込みを行えるようにする。

任意の名前で以下の内容のconfigファイルを作成する。 (今回はopenocd.cfgという名前にした)

telnet_port 4444
gdb_port 3333

source [find board/st_nucleo_f4.cfg]

init

proc flash_elf {elf_file} {
    reset
    halt
    flash write_image erase $elf_file
    verify_image $elf_file
    echo "flash write_image ($elf_file) complete"
    reset
    exit
}

configファイルを作成したら、以下のコマンドで書き込みを実行する。

$ openocd -f openocd.cfg -c "flash_elf ${elf_file_relative_path}"

※OpenOCDのprocの名前はOpenOCDの既存コマンド名にあるものを使うとエラーになるようだ。
(最初、proc flash {elf_file}としていたところ、以下のエラーが出て小一時間ほどハマってしまった)

Open On-Chip Debugger 0.10.0
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 2000 kHz
adapter_nsrst_delay: 100
none separate
srst_only separate srst_nogate srst_open_drain connect_deassert_srst
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
Info : clock speed 1800 kHz
Info : STLINK v2 JTAG v28 API v2 SWIM v18 VID 0x0483 PID 0x374B
Info : using stlink api v2
Info : Target voltage: 3.256353
Info : stm32f4x.cpu: hardware has 6 breakpoints, 4 watchpoints
flash
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
adapter speed: 1800 kHz
target halted due to debug-request, current mode: Thread
xPSR: 0x61000000 pc: 0x1fff1048 msp: 0x20002e40
openocd.cfg:13: Error: wrong # args: should be "flash elf_file"
in procedure 'flash'
at file "openocd.cfg", line 13

ST-LinkのFirmwareアップデート

こちらで公開されているツールを使ってアップデートする。

参考