CDC SetLineCoding
2025-07-11
0
0
1. SetLineCoding 请求用途
SetLineCoding 用于设置异步线路字符格式化属性,适用于异步字节流数据类接口和端点。
主机通过此请求配置数据传输的格式参数,如波特率、数据位、停止位、奇偶校验等,影响主机到设备和设备到主机的双向数据传输。
2. USB 控制传输格式
字段 | 值/说明 |
---|---|
bmRequestType | 0x21 (00100001B) 方向:主机到设备,类型:类,接收者:接口 |
bRequest | 0x20 (SET_LINE_CODING) |
wValue | 0x0000 |
wIndex | 接口号 |
wLength | Line Coding Structure 的大小(通常为7字节) |
Data | Line Coding Structure(见下表) |
3. Line Coding Structure 格式
typedef struct _LINE_CODING {
uint32_t dwDTERate; // 波特率(如9600, 19200, 38400等)
uint8_t bCharFormat; // 停止位(0:1位, 1:1.5位, 2:2位)
uint8_t bParityType; // 奇偶校验(0:无, 1:奇, 2:偶, 3:标记, 4:空格)
uint8_t bDataBits; // 数据位(5,6,7,8,16)
} LINE_CODING;
字段说明:
- dwDTERate:数据传输速率(波特率)
- bCharFormat:字符格式(停止位数量)
- bParityType:奇偶校验类型
- bDataBits:数据位数量
4. 典型主机端请求示例
C 结构体示例:
LINE_CODING line_coding = {
.dwDTERate = 9600, // 9600波特率
.bCharFormat = 0, // 1个停止位
.bParityType = 0, // 无奇偶校验
.bDataBits = 8 // 8位数据
};
USB_SETUP_PACKET setup = {
.bmRequestType = 0x21, // 主机到设备,类,接口
.bRequest = 0x20, // SET_LINE_CODING
.wValue = 0x0000,
.wIndex = interface_number, // 通信接口号
.wLength = sizeof(LINE_CODING) // 7字节
};
// 发送setup包和line_coding数据
5. 设备端处理要点
- 接收并解析 Line Coding Structure。
- 配置UART/串口硬件参数。
- 应用新的线路编码设置到数据传输。
- 完成后通过状态阶段(Status Stage)ACK主机。
6. 常见配置示例
应用场景 | 波特率 | 数据位 | 奇偶校验 | 停止位 | bCharFormat | bParityType | bDataBits |
---|---|---|---|---|---|---|---|
标准串口 | 9600 | 8 | 无 | 1 | 0 | 0 | 8 |
调制解调器 | 115200 | 8 | 无 | 1 | 0 | 0 | 8 |
工业设备 | 19200 | 7 | 偶 | 1 | 0 | 2 | 7 |
7. 参考
- USB CDC 规范 6.2.12](https://www.usb.org/document-library/class-definitions-communication-devices-12)
- GetLineCoding 6.2.13](https://www.usb.org/document-library/class-definitions-communication-devices-12)