TeenyUSB 开源项目教程
项目介绍
TeenyUSB 是一个开源的 USB 设备和主机库,旨在简化 USB 设备的开发。它支持多种 USB 设备类型,包括 HID、CDC、MSC 等,并且可以在多种微控制器平台上运行。TeenyUSB 的设计目标是提供一个易于使用的接口,使得开发者可以快速实现 USB 功能,而无需深入了解复杂的 USB 协议。
项目快速启动
环境准备
在开始之前,请确保你已经安装了以下工具和环境:
- 支持的微控制器开发环境(如 Keil, IAR, GCC 等)
- USB 调试工具(如 USB 分析仪)
下载代码
首先,从 GitHub 仓库下载 TeenyUSB 的源代码:
git clone https://github.com/xtoolbox/TeenyUSB.git
编译和烧录
进入项目目录,根据你的开发环境选择相应的编译工具链进行编译。以下是一个示例,假设你使用的是 GCC:
cd TeenyUSB
make
编译完成后,将生成的二进制文件烧录到你的微控制器中。
示例代码
以下是一个简单的示例代码,展示了如何使用 TeenyUSB 实现一个基本的 HID 设备:
#include "teeny_usb.h"
// 定义 USB 设备描述符
USB_DESC_STORAGE const uint8_t device_descriptor[] = {
// 设备描述符
0x12, // bLength
0x01, // bDescriptorType
0x00, 0x02, // bcdUSB
0x00, // bDeviceClass
0x00, // bDeviceSubClass
0x00, // bDeviceProtocol
0x40, // bMaxPacketSize0
0x83, 0x04, // idVendor
0x30, 0x00, // idProduct
0x00, 0x01, // bcdDevice
0x01, // iManufacturer
0x02, // iProduct
0x03, // iSerialNumber
0x01 // bNumConfigurations
};
// 定义配置描述符
USB_DESC_STORAGE const uint8_t config_descriptor[] = {
// 配置描述符
0x09, // bLength
0x02, // bDescriptorType
0x20, 0x00, // wTotalLength
0x01, // bNumInterfaces
0x01, // bConfigurationValue
0x00, // iConfiguration
0x80, // bmAttributes
0x32, // bMaxPower
// 接口描述符
0x09, // bLength
0x04, // bDescriptorType
0x00, // bInterfaceNumber
0x00, // bAlternateSetting
0x02, // bNumEndpoints
0x03, // bInterfaceClass
0x01, // bInterfaceSubClass
0x02, // bInterfaceProtocol
0x00, // iInterface
// 端点描述符
0x07, // bLength
0x05, // bDescriptorType
0x81, // bEndpointAddress
0x03, // bmAttributes
0x08, 0x00, // wMaxPacketSize
0x0A, // bInterval
0x07, // bLength
0x05, // bDescriptorType
0x01, // bEndpointAddress
0x03, // bmAttributes
0x08, 0x00, // wMaxPacketSize
0x0A // bInterval
};
// 字符串描述符
USB_DESC_STORAGE const uint8_t string_descriptor[] = {
0x04, 0x03, 'T', 'B'
};
// USB 设备对象
TeenyUSB usb;
// 初始化 USB 设备