OpenOCD基础篇(二)——调试和烧录

前言:
  本篇文章介绍使用OpenOCD烧录和调试。

1 OpenOCD连接芯片

  OpenOCD需要配置cfg文件才能连接芯片,cfg需要根据使用环境进行配置,以stm32f103ZET6通过J-Link,按照SWD接线方式连接芯片,以下给出 jlink-swd-stm32f103.cfg 配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# jlink-swd-f103.cfg
# J-Link调试器配置
source [find interface/jlink.cfg]

# 选择SWD传输模式
transport select swd

# 适配器速度设置(可根据需要调整)
adapter speed 4000

# STM32F103ZET6目标芯片配置
source [find target/stm32f1x.cfg]

# 复位配置
reset_config srst_only
# 或者使用
# reset_config none

  执行以下指令让OpenOCD根据cfg的配置连接芯片。连接只需要通过USB连接J-Link,J-Link通过SWD接线方式连接芯片,linux环境只需要安装OpenOCD,不需要安装额外的驱动程序。

1
openocd -f jlink-swd-stm32f103.cfg

  连接成功后显示如下。

connect.png

2 烧录

  OpenOCD连接芯片成功后,保持该终端不要关闭,重新打开终端后执行以下指令烧录固件,可以烧录bin、hex、elf三种文件。以下默认固件文件和脚本在同一目录下。

  • 烧录elf文件
1
2
3
4
5
6
7
8
9
telnet localhost 4444
# 烧录前初始化
init
# 确保芯片暂停
halt 1000
# 烧录命令
program ord32.elf verify
reset # 复位芯片
shutdown # 断开连接
  • 烧录hex文件
1
2
3
4
5
6
7
8
9
telnet localhost 4444
# 烧录前初始化
init
# 确保芯片暂停
halt 1000
# 烧录命令
program ord32.hex verify
reset # 复位芯片
shutdown # 断开连接
  • 烧录bin文件
1
2
3
4
5
6
7
8
9
10
telnet localhost 4444
# 烧录前初始化
init
# 确保芯片暂停
halt 1000
# 烧录命令
# BIN文件必须指定烧录地址 (STM32 Flash起始地址为 0x08000000)
program ord32.bin 0x08000000 verify
reset # 复位芯片
shutdown # 断开连接

  bin文件不含地址信息,因此必须指定地址,STM32的Flash起始地址为0x08000000。
  打开两个终端手动操作比较麻烦,也可以一条指令实现烧录,指令中添加了halt超时和复位延迟动作,否则升级容易失败。

  • 烧录elf文件
1
openocd -f jlink-swd-stm32f103.cfg -c "reset_config srst_only; init; halt 3000; program ord32.elf verify reset exit"
  • 烧录hex文件
1
openocd -f jlink-swd-stm32f103.cfg -c "reset_config srst_only; init; halt 3000; program ord32.hex verify reset exit"
  • 烧录bin文件
1
openocd -f jlink-swd-stm32f103.cfg -c "reset_config srst_only; init; halt 3000; program ord32.bin 0x08000000 verify reset exit"

3 调试

  执行以下指令连接芯片。

1
openocd -f jlink-swd-stm32f103.cfg

  连接的终端不要关闭,另外再打开一个终端,执行以下指令使用GDB进入Debug。

1
arm-none-eabi-gdb ord32.elf # 注意必须用elf文件,其包含调试信息。

  设置断点并运行,查看变量值。

1
2
3
4
5
6
7
8
target remote localhost:3333
monitor reset halt # 复位并暂停芯片
load # 加载程序到Flash
break main # 在main函数设置断点
continue # 开始运行
next # 单步执行
print variable_name # 查看变量
continue # 继续运行

gdb.png