Arduino stm32 USB CDC虚拟串口使用示例
- 相关篇《STM32F401RCT6基于Arduino框架点灯程序》
- 本开发环境基于VSCode + PIO
- 验证芯片:
STM32F401RC
- ⌛USB CDC引脚: PA11、 PA12
platformio.ini
配置信息:
[env:genericSTM32F401RC]
platform = ststm32
board = genericSTM32F401RC
framework = arduino
build_flags =
-D USBCON
-D USBD_USE_CDC
; -D USE_USB_HS
upload_protocol = stlink
;upload_protocol = serial
;upload_protocol = jlink
;upload_protocol = cmsis-dap
- STM32 USB CDC虚拟串口在Arduino IDE中好像可以在功能菜单上选择,
由于IDE环境支持包没有安装,没有进一步验证。 ✨个人还是推荐VSCode + PIO 方式来开发,比较灵活和便捷。✨
Arduino IDE 环境下配置USB CDC虚拟串口方法
- 这里以Arduino IDE
2.2.1
版本设置为例,进行USB CDC虚拟串口配置:
USBSerial API相关函数
void begin(void);
void begin(uint32_t);
void begin(uint32_t, uint8_t);
void end(void);
virtual int available(void);
virtual int availableForWrite(void);
virtual int peek(void);
virtual int read(void);
virtual size_t readBytes(char *buffer, size_t length);
virtual size_t readBytesUntil(char terminator, char *buffer, size_t length);
virtual void flush(void);
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buffer, size_t size);
- ✨ 为什么是使用
Serial
,因为在WSerial.h
文件中有如下定义:
#if defined (USBCON) && defined(USBD_USE_CDC)
#ifndef DISABLE_GENERIC_SERIALUSB
#define ENABLE_SERIALUSB
#if !defined(Serial)
#define Serial SerialUSB
#define serialEvent serialEventUSB
#endif
#endif
#if defined(ENABLE_SERIALUSB)
#define HAVE_SERIALUSB
#endif
示例代码
#include
#include
int myFunction(int, int);
#define led1 PC13
#define led2 PA_5
uint32_t TimerUART;
void setup()
{
Serial.begin();
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
TimerUART = HAL_GetTick();
}
void loop()
{
if ((HAL_GetTick() - TimerUART) > 1000)
{
digitalToggle(led1);
digitalToggle(led2);
Serial.println("USART2(PA2 PA3)Arduino STM32F401RC \n");
Serial.printf("USART1(PA9 PA10)STM32F401 SysClockFreq:%d \r\n", HAL_RCC_GetSysClockFreq());
Serial.print("from SerialUSB data\n");
TimerUART = HAL_GetTick();
}
}
int myFunction(int x, int y)
{
return x + y;
}
- 输出效果: