实现用STM32模拟一个USB键盘连接PC的功能
1 STM32CubeMX配置
1.1 USB接口配置
单片机做从机,所以Mode选择Device,其它设置保持默认即可
使能USB接口的中断:
设置IP,选择HID,注意不要选择自定义HID
参数页面不需要调整,设备描述符根据实际需要自行修改
1.2 时钟配置
USB接口使用的时钟频率为48MHz
至此,配置完成,生成代码
2 设备描述符
2.1 修改设备描述符大小
打开usbd_hid.h文件,修改HID_MOUSE_REPORT_DESC_SIZE的值为63,原来为74表示鼠标设备,HAL库默认的HID设备为鼠标,因此变量名、宏名中的MOUSE不必在意,不影响PC端识别到的设备名称和类型,如果要修改,请注意全部替换,不要遗漏
//#define HID_MOUSE_REPORT_DESC_SIZE 74U //鼠标描述符大小
#define HID_MOUSE_REPORT_DESC_SIZE 63U //键盘描述符大小
2.2 修改设备类型
打开usbd_hid.c文件,找到USBD_HID_CfgFSDesc数组的定义:
/* USB HID device FS Configuration Descriptor */
__ALIGN_BEGIN static uint8_t USBD_HID_CfgFSDesc[USB_HID_CONFIG_DESC_SIZ] __ALIGN_END =
{
0x09, /* bLength: Configuration Descriptor size */
USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
USB_HID_CONFIG_DESC_SIZ,
/* wTotalLength: Bytes returned */
0x00,
0x01, /*bNumInterfaces: 1 interface*/
0x01, /*bConfigurationValue: Configuration value*/
0x00, /*iConfiguration: Index of string descriptor describing
the configuration*/
0xE0, /*bmAttributes: bus powered and Support Remote Wake-up */
0x32, /*MaxPower 100 mA: this current is used for detecting Vbus*/
/************** Descriptor of Joystick Mouse interface ****************/
/* 09 */
0x09, /*bLength: Interface Descriptor size*/
USB_DESC_TYPE_INTERFACE,/*bDescriptorType: Interface descriptor type*/
0x00, /*bInterfaceNumber: Number of Interface*/
0x00, /*bAlternateSetting: Alternate setting*/
0x01,