You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

STM32黑药丸中USB Serial搭配FreeRTOS无法工作的问题求助

STM32FreeRTOS与USB CDC串口连接问题解决

问题场景

在PlatformIO的STM32Duino框架下,为项目添加STM32FreeRTOS 10.3.2库依赖后,Windows系统能识别到COM端口,但串口监视器无法连接;移除FreeRTOS依赖后,串口功能恢复正常。

测试代码:

#include <Arduino.h>
void setup() {
  Serial.begin(9600);
  Serial.println("Serial Started...");
}
void loop() {
  Serial.println("Hello world..");
  delay(1000);
}

PlatformIO配置:

[env:STM32]
platform = ststm32
board = blackpill_f411ce
framework = arduino
upload_protocol = dfu
monitor_speed = 115200
build_flags = 
    -D PIO_FRAMEWORK_ARDUINO_ENABLE_CDC
    -D USBCON
build_src_filter=+<*> -<.git/> -<.svn/> -<doc/>
lib_deps= https://github.com/stm32duino/STM32FreeRTOS/archive/refs/tags/10.3.2.zip

解决方案

1. 统一串口波特率

配置中monitor_speed为115200,但代码中Serial.begin(9600),两者波特率不匹配会导致连接异常。修改代码中的波特率与配置一致:

Serial.begin(115200);

2. 添加FreeRTOS启用宏定义

在build_flags中添加-D USE_FREERTOS,确保STM32FreeRTOS库正确集成到STM32Duino框架中,避免底层资源冲突:

build_flags = 
    -D PIO_FRAMEWORK_ARDUINO_ENABLE_CDC
    -D USBCON
    -D USE_FREERTOS

3. 调整FreeRTOS中断优先级(若上述步骤无效)

如果仍无法连接,需修改FreeRTOS配置文件(FreeRTOSConfig.h),降低SysTick中断优先级,确保USB CDC的中断能正常响应:

  • 找到configKERNEL_INTERRUPT_PRIORITY配置项,将其值改为较低的优先级(例如0xF0,数值越大优先级越低)
  • 确保configMAX_SYSCALL_INTERRUPT_PRIORITY的值不高于USB中断的优先级

4. 确保串口初始化优先于FreeRTOS调度器

若后续代码中使用FreeRTOS任务,需在setup()中先完成串口初始化,再启动调度器:

#include <Arduino.h>
#include <FreeRTOS.h>
#include <task.h>

void setup() {
  Serial.begin(115200);
  // 等待串口初始化完成
  while(!Serial);
  Serial.println("Serial Started...");
  
  // 启动FreeRTOS调度器
  xTaskCreate(loopTask, "LoopTask", 1024, NULL, 1, NULL);
  vTaskStartScheduler();
}

void loopTask(void *pvParameters) {
  while(1) {
    Serial.println("Hello world..");
    vTaskDelay(pdMS_TO_TICKS(1000));
  }
}

// 调度器启动失败时进入死循环
void loop() {
  while(1);
}

内容的提问来源于stack exchange,提问作者Arun K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 14:40:26