STM32F103C8T6 开发板 PB3 引脚作为普通 GPIO 引脚
· 阅读需 2 分钟
STM32F1xx 系列的部分引脚默认作为 JTAG/SWD 调试接口引脚。官方文档对这些引脚的功能定义如下:
| SWJ_CFG [2:0] | JTAG-DP | SW-DP | PA13 / JTMS / SWDIO | PA14 / JTCK/SWCLK | PA15 / JTDI | PB3 / JTDO/TRACE SWO | PB4 / NJTRST |
|---|---|---|---|---|---|---|---|
| 000 | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| 001 | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ✔️ |
| 010 | 🚫 | ✅ | ❌ | ❌ | ✔️ | ✔️ | ✔️ |
| 100 | 🚫 | 🚫 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
备注
- 每次 Reset 后,默认模式为 000,即 JTAG-DP 和 SW-DP 都被启用。
- 激活 SWD 时,仅当调试器没有激活 SWO 时,PB3 引脚才可以作为普通 GPIO 引脚使用。
HAL 库提供了如下宏来设置使用的 JTAG/SWD 模式:
stm32f1xx_hal_gpio_ex.h
/**
* @brief Enable the Serial wire JTAG configuration
* @note ENABLE: Full SWJ (JTAG-DP + SW-DP): Reset State
* @retval None
*/
#define __HAL_AFIO_REMAP_SWJ_ENABLE() AFIO_DBGAFR_CONFIG(AFIO_MAPR_SWJ_CFG_RESET)
/**
* @brief Enable the Serial wire JTAG configuration
* @note NONJTRST: Full SWJ (JTAG-DP + SW-DP) but without NJTRST
* @retval None
*/
#define __HAL_AFIO_REMAP_SWJ_NONJTRST() AFIO_DBGAFR_CONFIG(AFIO_MAPR_SWJ_CFG_NOJNTRST)
/**
* @brief Enable the Serial wire JTAG configuration
* @note NOJTAG: **JTAG-DP**Disabled and SW-DP Enabled
* @retval None
*/
#define __HAL_AFIO_REMAP_SWJ_NOJTAG() AFIO_DBGAFR_CONFIG(AFIO_MAPR_SWJ_CFG_JTAGDISABLE)
/**
* @brief Disable the Serial wire JTAG configuration
* @note DISABLE: **JTAG-DP**Disabled and SW-DP Disabled
* @retval None
*/
#define __HAL_AFIO_REMAP_SWJ_DISABLE() AFIO_DBGAFR_CONFIG(AFIO_MAPR_SWJ_CFG_DISABLE)
如果使用 CubeMX 生成的项目模板,则会在HAL_MspInit()中设置 JTAG/SWD 模式,例如:
stm32f1xx_hal_msp.c
void HAL_MspInit(void)
{
__HAL_RCC_AFIO_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
// **JTAG-DP**Disabled and SW-DP Enabled
__HAL_AFIO_REMAP_SWJ_NOJTAG();
}
使用 SWD 调试,在关闭 SWO 功能时 PB3 引脚就可以作为普通 GPIO 引脚使用。使用 VSCode 调试时,修改启动配置文件launch.json,删除或关闭 swoConfig 配置项即可关闭 SWO 功能 :
launch.json
{
"showDevDebugOutput": "raw",
"showDevDebugTimestamps": true,
"cwd": "${workspaceRoot}",
"executable": "build/Debug/${workspaceRootFolderName}.elf",
"name": "Launch STM32",
"request": "launch",
"type": "cortex-debug",
"servertype": "openocd",
"preLaunchTask": "CMake: build",
"device": "STM32F103C8",
"svdFile": "./STM32F103.svd",
"runToEntryPoint": "main",
"configFiles": ["openocd.cfg"],
"swoConfig": {
"enabled": false,
"source": "probe",
"swoFrequency": 115200,
"cpuFrequency": 72000000,
"decoders": [
{
"port": 0,
"type": "console",
"label": "SWO output",
"encoding": "ascii"
}
]
}
}
问题排查
如果按照上述配置后 PB3 仍无法作为普通 GPIO 引脚 使用,请进行以下检查:
- 确认在调试器终端选项中 SWO 功能已确实关闭,如 VSCode 终端下确实没有 SWO 终端了
- 断开电源并重新上电,确保配置生效
- 检查代码中是否正确调用了相应的 GPIO 初始化函数