VScode STM32串口调试
时间: 2025-07-07 17:11:01 浏览: 5
使用 VSCode 进行 STM32 的串口调试需要结合开发环境的配置、调试工具链以及串口通信工具。以下是完整的设置指南:
### 1. 安装必要的软件组件
- **VSCode**:安装 [Visual Studio Code](https://code.visualstudio.com/)。
- **C/C++ 插件**:用于代码补全、跳转定义等功能。
- **PlatformIO 插件(可选)**:简化嵌入式开发流程,支持 STM32。
- **STM32 开发工具链**:
- **ARM GCC 工具链**:如 `arm-none-eabi-gcc`。
- **OpenOCD 或 J-Link GDB Server**:用于连接调试器。
- **串口调试工具**:如 `PuTTY`、`Tera Term` 或 VSCode 内置终端。
### 2. 配置项目结构
确保你的 STM32 项目已经具备以下结构:
```plaintext
my_stm32_project/
├── src/
│ └── main.c
├── CMakeLists.txt (或 Makefile)
├── launch.json
├── tasks.json
└── settings.json
```
### 3. 编写 `tasks.json` 文件
该文件用于配置编译任务:
```json
{
"version": "2.0.0",
"tasks": [
{
"label": "Build Project",
"type": "shell",
"command": "make",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"]
}
]
}
```
### 4. 编写 `launch.json` 文件
该文件用于配置调试器,假设使用 OpenOCD 和 ST-Link 调试器:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Cortex Debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/your_project.elf",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/path/to/arm-none-eabi-gdb",
"debugServerPath": "/path/to/openocd",
"debugServerArgs": "-f interface/stlink-v2.cfg -f target/stm32f4x.cfg",
"serverStarted": "Info : \\*\\*\\*.*",
"filterStderr": true,
"targetArchitecture": "arm"
}
]
}
```
### 5. 使用串口工具进行调试输出
在 STM32 程序中启用 UART 输出日志,例如通过 `printf` 重定向到串口通道:
```c
#include <stdio.h>
#include <stm32f4xx_hal.h>
UART_HandleTypeDef huart2;
int __io_putchar(int ch) {
HAL_UART_Transmit(&huart2, (uint8_t*)&ch, 1, HAL_MAX_DELAY);
return ch;
}
int main(void) {
HAL_Init();
SystemClock_Config();
MX_USART2_UART_Init();
printf("Hello from STM32!\r\n");
while (1) {
// Your code here
}
}
```
### 6. 启动串口监视
可以使用如下方式查看串口输出:
- 在 VSCode 中使用 `Serial Monitor` 扩展。
- 使用外部工具如 `PuTTY`,设置正确的 COM 端口和波特率(如 115200)[^2]。
---
###
阅读全文
相关推荐


















