USB_DEVICE — 复合设备: VCP + 键盘
固件库: AT32F403A_407_Firmware_Library V2.2.2
芯片: AT32
源文件: AT32/AT32F403A_407_Firmware_Library_V2.2.2/project/at_start_f403a/examples/usb_device/composite_vcp_keyboard/src/main.c
功能简介
本示例演示 USB 设备模式 — 复合设备: VCP + 键盘。MCU 作为 USB 设备连接到电脑,实现 HID 键盘/鼠标、虚拟串口(CDC)、大容量存储(MSC)等功能。
完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
#include "at32f403a_407_board.h"
#include "at32f403a_407_clock.h"
#include "usbd_core.h"
#include "cdc_keyboard_class.h"
#include "cdc_keyboard_desc.h"
#include "usbd_int.h"
int main(void)
{
uint16_t data_len;
uint32_t timeout;
uint8_t send_zero_packet = 0;
/* config nvic priority group */
nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
system_clock_config();
at32_board_init();
/* select usb 48m clcok source */
usb_clock48m_select(USB_CLK_HEXT);
/* enable usb clock */
crm_periph_clock_enable(CRM_USB_PERIPH_CLOCK, TRUE);
/* enable usb interrupt */
nvic_irq_enable(USBFS_L_CAN1_RX0_IRQn, 0, 0);
/* usb core init */
usbd_core_init(&usb_core_dev, USB, &cdc_keyboard_class_handler, &cdc_keyboard_desc_handler, 0);
/* enable usb pull-up */
usbd_connect(&usb_core_dev);
while(1)
{
/* get usb vcp receive data */
data_len = usb_vcpkybrd_vcp_get_rxdata(&usb_core_dev, usb_buffer);
if(data_len > 0 || send_zero_packet == 1)
{
/* bulk transfer is complete when the endpoint does one of the following
1 has transferred exactly the amount of data expected
2 transfers a packet with a payload size less than wMaxPacketSize or transfers a zero-length packet
*/
if(data_len > 0)
send_zero_packet = 1;
if(data_len == 0)
send_zero_packet = 0;
timeout = 5000000;
do
{
/* send data to host */
if(usb_vcpkybrd_vcp_send_data(&usb_core_dev, usb_buffer, data_len) == SUCCESS)
{
break;
}
}while(timeout --);
}
if(at32_button_press() == USER_BUTTON)
{
keyboard_send_string(&usb_core_dev, (uint8_t *)" Keyboard Demo\r\n", 16);
}
}
}
|
代码讲解
系统时钟初始化:配置 MCU 的主频和时钟树。不同芯片的时钟配置不同,一般由工具生成。
板级初始化:初始化开发板上的 LED、按键等基础外设。
中断优先级配置:NVIC 设置中断的抢占优先级和子优先级。数字越小优先级越高。