<返回更多

STM32CUBEIDE 配置USBHID自定义设备

2022-03-15    Runningwater
加入收藏

STM32CubeMX USB-HID

RCC的HSE选择BYPASS Clock Source, USB时钟为48MHz

STM32CUBEIDE 配置USBHID自定义设备

 


STM32CUBEIDE 配置USBHID自定义设备

 

修改usbd_custom_hid_if.c文件添加通讯代码:

__ALIGN_BEGIN static uint8_t CUSTOM_HID_ReportDesc_FS[USBD_CUSTOM_HID_REPORT_DESC_SIZE] __ALIGN_END =

{

0x06, 0xA0, 0xFF, //用法页(FFA0h, vendor defined)

0x09, 0x01,//用法(vendor defined)

0xA1, 0x01,//集合(Application)

0x09, 0x02, //用法(vendor defined)

0xA1, 0x00,//集合(Physical)

0x06, 0xA1, 0xFF, //用法页(vendor defined)

//输入报告

0x09, 0x03, //用法(vendor defined)

0x09, 0x04,//用法(vendor defined)

0x15, 0x80,//逻辑最小值(0x80 or -128)

0x25, 0x7F,//逻辑最大值(0x7F or 127)

0x35, 0x00,//物理最小值(0)

0x45, 0xFF,//物理最大值(255)

0x75, 0x08,//报告长度Report size (8位)

0x95, 0x40,//报告数值(64 fields)

0x81, 0x02,//输入(data, variable, absolute)

//输出报告

0x09, 0x05,//用法(vendor defined)

0x09, 0x06,//用法(vendor defined)

0x15, 0x80,//逻辑最小值(0x80 or -128)

0x25, 0x7F,//逻辑最大值(0x7F or 127)

0x35, 0x00,//物理最小值(0)

0x45, 0xFF,//物理最大值(255)

0x75, 0x08,//报告长度(8位)

0x95, 0x40,//报告数值(64 fields)

0x91, 0x02,//输出(data, variable, absolute)

0xC0,//集合结束(Physical)

0xC0//集合结束(Application)

};

USBD_CUSTOM_HID_REPORT_DESC_SIZE = 52

同时修改usbd_customhid.h文件中的发送与接收长度

#define CUSTOM_HID_EPIN_SIZE 0x40

#define CUSTOM_HID_EPOUT_SIZE 0x40

再次编译并写入,系统会枚举到USB,用
USBD_CUSTOM_HID_SendReport()函数就可以发送数据,第一步完成了。接收数据的函数也在usbd_customhid.c文件中,生成 的接收函数USBD_CUSTOM_HID_DataOut()需要进一步修改。定义个接收缓冲区和接收计数器。

unsigned char USB_Recive_Buffer[64];

volatile unsigned char USB_Received_Count = 0;

再修改接收函数成这个样子:

static uint8_t USBD_CUSTOM_HID_DataOut (USBD_HandleTypeDef *pdev, uint8_t epnum)

{

USB_Received_Count = USBD_GetRxCount( pdev,epnum );

USBD_LL_PrepareReceive( pdev, CUSTOM_HID_EPOUT_ADDR , USB_Recive_Buffer, sizeof( USB_Recive_Buffer ) );

return USBD_OK;

}

USB接收是在USB事件中处理的,只需要盯着USB_Received_Count变量就行了,有了数据就从USB_Recive_Buffer里直接拿。

在main.c中实现的数据回传,上位机发啥返啥:

#include "usbd_customhid.h"

extern volatile unsigned char USB_Received_Count;

extern unsigned char USB_Recive_Buffer[64];

while( 1 )

{

if (USB_Received_Count>0) //收到数据后返回数据

{

USBD_CUSTOM_HID_SendReport( &hUsbDeviceFS, USB_Recive_Buffer, sizeof(USB_Recive_Buffer) );

USB_Received_Count = 0;

}

}

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>