用于自动化STM32闪烁的批处理文件

Batch file to automate STM32 flashing

为了使用 ST-Link 实用程序进行刷写,我编写了以下有效的命令:

"C:\Program Files\STMicroelectronics\STM32 ST-Link Utility\ST-Link_CLI.exe" -c SN=XXXXXXXXXXXXX SWD UR FREQ=400 -P "C:\flash STM32\test.hex" -V -HardRst

我想通过使用 ST-Link_CLI.exe 命令和批处理文件所在文件夹中的 .hex 文件获取序列号来自动执行此操作,这样我就可以单击此 .bat 文件使用连接的任何调试器 (SN) 进行闪存。

我可以用这个获取序列号:

@echo off
setlocal EnableDelayedExpansion
set "output_cnt=0"
for /F "delims=" %%f in ('"C:\Program Files\STMicroelectronics\STM32 ST-LINK Utility\ST-LINK Utility\ST-LINK_CLI.exe" -List') do (
    set /a output_cnt+=1
    set "output[!output_cnt!]=%%f"
)
for /L %%a in (1 1 !output_cnt!) do call echo !output[%%a]!
pause
set "str=SN"
for /L %%n in (1 1 !output_cnt!) do (
    echo !output[%%n]!|find "SN" >nul
    if errorlevel 1 (echo notfound) else (echo found at!output[%%n]!)
)
pause
output_cnt 中的行包含字符串 SN

时,

!output[%%a]!" SN:XXXXXXXXXXX"

在编写有效的批处理脚本方面,我完全是个新手,想知道是否有人可以帮助我自动完成这项任务。

更新代码:

set "STfilepath=C:\Program Files\STMicroelectronics\STM32 ST-LINK Utility\ST-LINK Utility\ST-LINK_CLI.exe"
set "output_cnt=0"
for /F "delims=" %%f in ('"!STfilepath!" -List') do (
    set /a output_cnt+=1
    set "output[!output_cnt!]=%%f"
)
::iterate thru output array to find SN and parse it to get the serial number
set "serial=NONE"
for /L %%n in (1 1 !output_cnt!) do (
    echo !output[%%n]!
    FOR /F "tokens=1,* delims=: " %%1 in ("!output[%%n]!") do (
        if "%%1" == "SN" (
            set "serial=%%2"
        )
    )
)
echo serial number is !serial!
set "hexfile=NONE"
for /r %%i in (*.hex) do (set "hexfile=%%i")
echo hexfile is !hexfile!
set "CMD="!STfilepath!" -c SN=!serial! SWD UR FREQ=400 -P "!hexfile!" -V -HardRst"
echo %CMD%
%CMD%
pause

您可以使用 FOR /F 循环拆分字符串。

...
set "serial=NONE"
for /L %%n in (1 1 !output_cnt!) do (
    echo !output[%%n]!
    FOR /F "tokens=1,* delims=: " %%1 in ("!output[%%n]!") do (
        if "%%1" == "SN" (
            set "serial=%%2"
        )
    )
)
echo Found serial: !serial!