ST-LINK V2 使用与配置代码例程

知识库
知识库文档
/firmware/开发板/ST-LINK V2/ST-LINK V2 使用与配置代码例程.md

文档

ST-LINK V2 使用与配置代码例程

ST-LINK V2 本身是调试烧录硬件工具,不直接需要MCU端驱动代码。本文档涵盖 ST-LINK V2 在各大开发环境中的配置方法和命令行工具使用示例。


例程一:STM32CubeProgrammer CLI 命令行烧录

安装

从ST官网下载 STM32CubeProgrammer,支持 Windows/Linux/macOS。

命令行烧录脚本

#!/bin/bash
# ST-LINK V2 命令行烧录脚本 (Linux/macOS)
# 路径根据实际安装位置调整

STM32_Programmer_CLI="/opt/st/stm32cubeprogrammer/bin/STM32_Programmer_CLI"
FIRMWARE="build/firmware.hex"     # 或 .bin
INTERFACE="SWD"

echo "=== STM32 固件烧录 ==="

# 1. 检测ST-LINK连接
echo "[1/4] 检测ST-LINK V2..."
$STM32_Programmer_CLI -c port=SWD freq=4000

# 2. 擦除芯片
echo "[2/4] 擦除Flash..."
$STM32_Programmer_CLI -c port=SWD freq=4000 -e all

# 3. 烧录固件
echo "[3/4] 烧录中..."
$STM32_Programmer_CLI -c port=SWD freq=4000 -w $FIRMWARE -v

# 4. 复位并运行
echo "[4/4] 复位运行..."
$STM32_Programmer_CLI -c port=SWD freq=4000 -rst

echo "烧录完成!"

Windows 批处理脚本

@echo off
REM ST-LINK V2 烧录脚本 (Windows)
REM 假设 STM32_Programmer_CLI.exe 在 PATH 中

set FIRMWARE=build\firmware.bin
set ADDRESS=0x08000000

echo === STM32 固件烧录 ===

echo [1/3] 连接并擦除...
STM32_Programmer_CLI.exe -c port=SWD freq=4000 -e all
if %errorlevel% neq 0 (
    echo [ERROR] 连接失败!
    pause
    exit /b 1
)

echo [2/3] 烧录固件...
STM32_Programmer_CLI.exe -c port=SWD freq=4000 -w %FIRMWARE% %ADDRESS% -v

echo [3/3] 验证并运行...
STM32_Programmer_CLI.exe -c port=SWD freq=4000 -rst

echo 烧录成功!
pause

例程二:OpenOCD 配置与使用

OpenOCD ST-LINK 配置文件

# ======================================
# openocd_stlink.cfg
# ST-LINK V2 + STM32F103C8T6 配置
# 使用方法: openocd -f openocd_stlink.cfg
# ======================================

# 调试器配置
source [find interface/stlink-v2.cfg]

# 传输协议
transport select hla_swd

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

# 可选:调整SWD时钟
# adapter speed 4000

# 可选:复位配置
# reset_config srst_only srst_nogate

命令行烧录

# 终端1:启动OpenOCD服务器
openocd -f openocd_stlink.cfg

# 终端2:使用telnet或gdb连接

# ====== Telnet方式 ======
telnet localhost 4444
# 进入OpenOCD命令行后:
>; reset halt          # 复位并暂停CPU
>; flash erase_sector 0 0 63  # 擦除全部Flash (64KB)
>; flash write_image erase build/firmware.bin 0x08000000
>; verify_image build/firmware.bin 0x08000000
>; reset run           # 复位并运行

# ====== 一键命令 ======
openocd -f openocd_stlink.cfg \
        -c "program build/firmware.bin 0x08000000 verify reset exit"

GDB调试

# 启动OpenOCD
openocd -f openocd_stlink.cfg &;

# 连接GDB
arm-none-eabi-gdb build/firmware.elf

# GDB内执行:
(gdb) target remote localhost:3333
(gdb) monitor reset halt
(gdb) load
(gdb) monitor reset init
(gdb) continue

# 常用GDB调试命令
(gdb) break main           # 在main函数设断点
(gdb) info registers       # 查看寄存器
(gdb) print variable       # 打印变量
(gdb) step                 # 单步进入
(gdb) next                 # 单步跳过
(gdb) continue             # 继续运行
(gdb) bt                   # 查看调用栈

例程三:PlatformIO 配置

platformio.ini

; ==========================================
; PlatformIO 项目配置 (STM32 + ST-LINK V2)
; ==========================================

[env:bluepill_f103c8]
platform = ststm32
board = bluepill_f103c8
framework = arduino   ; 或 libopencm3, stm32cube

; 调试器配置
debug_tool = stlink
upload_protocol = stlink

; SWD接口
debug_init_break = tbreak main

; 监控串口(如果有USB转串口)
monitor_speed = 115200

; 编译选项
build_flags =
    -D DEBUG_ENABLED

; ST-LINK 特定选项(如需要)
; upload_flags =
;     -c port=SWD
;     -freq=4000

PlatformIO 命令行

# 编译
pio run

# 烧录
pio run -t upload

# 调试
pio debug

# 串口监控
pio device monitor

# 清理
pio run -t clean

例程四:STM32CubeIDE 一键调试配置

在 STM32CubeIDE 中无需手动写配置代码,但可参考以下 .launch 文件内容了解底层配置:

<?xml version="1.0" encoding="UTF-8"?>
<!-- STM32CubeIDE Debug Configuration (.launch) -->
<launchConfiguration type="com.st.stm32cube.ide.mcu.debug.launch.launchConfigurationType">
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.access_port_id" value="0"/>
    <booleanAttribute key="com.st.stm32cube.ide.mcu.debug.launch.enable_live_expr" value="true"/>
    <booleanAttribute key="com.st.stm32cube.ide.mcu.debug.launch.enable_swv" value="false"/>
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.fpu_error_handling" value="1"/>
    <intAttribute key="com.st.stm32cube.ide.mcu.debug.launch.interface_type" value="0"/> <!-- SWD=0 -->
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.ip_address_local" value="localhost"/>
    <booleanAttribute key="com.st.stm32cube.ide.mcu.debug.launch.jtag_devices" value="false"/>
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.probe_id" value="0"/>
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.script_file_name" value=""/>
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.stlink_clk_freq" value="4000"/>
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.swv_clock" value="72000000"/>
    <stringAttribute key="com.st.stm32cube.ide.mcu.debug.launch.swv_mode" value="0"/>
</launchConfiguration>

例程五:Python + pyOCD 自动化测试

#!/usr/bin/env python3
"""
ST-LINK V2 + pyOCD 自动化烧录与测试脚本
安装: pip install pyocd
"""

import os
import sys
import time
from pyocd.core.helpers import ConnectHelper
from pyocd.flash.file_programmer import FileProgrammer

FIRMWARE_PATH = "build/firmware.bin"
TARGET = "stm32f103c8"  # 目标芯片型号

def detect_stlink():
    """检测ST-LINK V2连接"""
    try:
        session = ConnectHelper.session_with_chosen_probe(
            target_override=TARGET,
            connect_mode="attach"
        )
        board = session.board
        print(f"[OK] ST-LINK V2 已连接")
        print(f"     目标芯片: {board.target_type}")
        print(f"     UID: {', '.join(f'0x{b:08X}' for b in board.unique_id)}")
        session.close()
        return True
    except Exception as e:
        print(f"[ERROR] 连接失败: {e}")
        return False

def flash_firmware(firmware_path, address=0x08000000):
    """烧录固件"""
    if not os.path.exists(firmware_path):
        print(f"[ERROR] 固件文件不存在: {firmware_path}")
        return False

    print(f"[INFO] 烧录: {firmware_path} -> 0x{address:08X}")

    try:
        session = ConnectHelper.session_with_chosen_probe(
            target_override=TARGET,
            connect_mode="attach"
        )

        # 擦除
        print("[1/3] 擦除Flash...")
        flash = session.target.memory_map.get_region_for_address(address)
        if flash:
            flash.flash.init(flash.flash.Operation.ERASE)
            flash.flash.erase_all()

        # 烧录
        print("[2/3] 烧录中...")
        programmer = FileProgrammer(session)
        programmer.program(firmware_path, base_address=address)

        # 验证
        print("[3/3] 复位运行...")
        session.target.reset_and_halt()
        session.target.resume()

        session.close()
        print("[OK] 烧录完成!")
        return True

    except Exception as e:
        print(f"[ERROR] 烧录失败: {e}")
        return False

def read_memory(address, length):
    """读取目标内存(调试用)"""
    try:
        session = ConnectHelper.session_with_chosen_probe(
            target_override=TARGET,
            connect_mode="attach"
        )
        data = session.target.read_memory_block8(address, length)
        session.close()
        return bytes(data)
    except Exception as e:
        print(f"[ERROR] 读取失败: {e}")
        return None

# ====== 使用示例 ======

if __name__ == "__main__":
    print("=== ST-LINK V2 自动化烧录工具 ===\n")

    if detect_stlink():
        flash_firmware(FIRMWARE_PATH)

        # 可选:回读验证
        # data = read_memory(0x08000000, 256)
        # if data:
        #     print(f"Flash首256字节: {data[:32].hex()}")
    else:
        print("请检查ST-LINK V2连接!")
        sys.exit(1)

例程六:Keil MDK 批处理自动编译+烧录

@echo off
REM ==========================================
REM Keil MDK 自动编译+ST-LINK烧录脚本
REM 使用方法:放在工程目录下运行
REM ==========================================

set UV4_PATH=C:\Keil_v5\UV4\UV4.exe
set PROJECT=stm32_template.uvprojx
set TARGET=STM32F103C8

echo === Keil + ST-LINK V2 自动构建 ===

REM 1. 编译
echo [1/2] 编译工程...
%UV4_PATH% -b %PROJECT% -t "%TARGET%" -j0
if %errorlevel% neq 0 (
    echo [ERROR] 编译失败!
    pause
    exit /b 1
)

REM 2. 烧录
echo [2/2] 烧录到目标板...
%UV4_PATH% -f %PROJECT% -t "%TARGET%" -j0
if %errorlevel% neq 0 (
    echo [ERROR] 烧录失败! 检查ST-LINK连接!
    pause
    exit /b 1
)

echo [OK] 编译+烧录完成!
pause

ST-LINK V2 常见问题排查

问题 可能原因 解决方案
无法识别USB设备 驱动未安装 Windows: 安装STSW-LINK009驱动
连接目标失败 SWD引脚被禁用 按住复位键,点击连接后松开
"Target DLL has been cancelled" 芯片类型不匹配 Keil中检查芯片型号设置
烧录校验失败 线缆过长/接触不良 缩短线缆≤20cm,检查焊点
克隆版升级后变砖 固件不兼容 使用旧版升级工具或重新烧录bootloader
"No target connected" 目标板未供电 检查目标板3.3V供电

信息

路径
/firmware/开发板/ST-LINK V2/ST-LINK V2 使用与配置代码例程.md
更新时间
2026/5/25