最近在琢磨用RP2040开发灯丝控制电路,买回来一块RP2040的开发板,在琢磨需要的功能的时候,发现一些问题,问题的起源是想用电脑控制RP2040,设想是通过usb通讯,查了一下,找到Adafruit TinyUSB这个库可以做CDC(通讯),Arduino 的库内可以找到Adafruit TinyUSB这个库,也可以下载,但是无法使用,因为编译会出现大量的报错。这让我非常费解。因为我是基于Adafruit 提供的例子来编译的。按道理能提供例程,至少不应该有这种bug。
后来我仔细看了Adafruit TinyUsb的官网,发现这么一段话:
Cores without built-in support
Following is cores without built-in support
- mbed_rp2040
It is still possible to use TinyUSB but with some limits such as:
TinyUSB_Device_Init()
need to be manually called in setup()TinyUSB_Device_Task()
and/orTinyUSB_Device_FlushCDC()
may (or not) need to be manually called in loop()- Use
SerialTinyUSB
name instead of Serial for serial monitor- And there could be more other issues, using on these cores should be considered as experimental
其大意就是指 mbed_rp2040 这个 Core 是没有被 Adafruit 所支持的。因为Arduino的板库内,搜索RP2040,只会得到 mbed 的 RP2040 开发包。所以,我折腾一下午,全是因为用错了开发包。
官网中还有这么一段话:
Following core has TinyUSB as either the primary usb stack or selectable via menu
Tools->USB Stack
. You only need to include<Adafruit_TinyUSB.h>
in your sketch to use.
其大意就是指,这些 Core 是 Adafruit TinyUsb 所支持的。其中就有对 RP2040 提供支持的 earlephilhower/arduino-pico 这个开发包。
但是搜索 Arduino 的 Board 库内,是找不到 earlephilhower 写的开发包的。如果要安装这个开发包,需要接下来这么做:
打开 Arduino,通过 File -> Preferences 打开设置面板。
找到 Additional boards manager URLs,将
https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json
添加到输入行中。点击确定,这个时候 Arduino 会开始下载新的库列表。
完成之后,转到 Boards Manager,搜索 pico 或则 RP2040,这个时候应该出现新的板子,作者是:Earle Philhower,然后选中点击下载即可。
然后打开 File -> Examples -> Adafruit TinyUsb Library, 找到 CDC 中的 cdc multi 这个例子,打开这个例子。
此时已经可以编译了。但是还有两个地方需要做一个调整。
第一个地方,打开菜单,Tools 找到 Usb Stack 这个菜单项,在里面选择使用 Adafruit TinyUsb。
第二个地方,在给的例子文件中找到
#include <Adafruit_TinyUSB.h>
在这个包含文件之前,加一个宏定义:
#define CFG_TUD_CDC 2
#include <Adafruit_TinyUSB.h>
虽然网上有文章,让修改这个库的源代码中的 CFG_TUD_CDC 定义,但这种侵入式的修改源代码库,并不是最好的方法。我暂时没有找到在 Arduino 里面如何设置gcc的编译参数,最理想的解决方案是直接在 gcc 的编译参数中,添加这个宏定义。
做完这两步之后,就可以编译了。编译好上传到开发板,打开 Arduino 的串口监视器,此时已经能看到 RP2040 开始向串口监视器返回字符串信息。如果需要测试两个com口之间的通讯,还是得暂时修改库的源代码中的 CFG_TUD_CDC 定义。不过真心不推荐这种办法。