以下代码简单演示了HID收发,可支持USB复合设备,通过唯一的路径打开设备,实现发送接收。源码可在资源下载中下载。
#include "stdafx.h"
#include "hidapi.h"
#include <stdio.h>
#include <Windows.h>
#define MAX_STR 255
#define READ_TIMEOUT_MS 500
#pragma comment(lib, "hidapi.lib")
void print_dev_info(hid_device_info *info)
{
printf("path:");printf(info->path);
printf("\r\nvendor_id:%04X",info->vendor_id);
printf("\r\nproduct_id:%04X",info->product_id);
printf("\r\nserial_number:");wprintf(info->serial_number);
printf("\r\nrelease_number:%04X",info->release_number);
printf("\r\nmanufacturer_string:");wprintf(info->manufacturer_string);
printf("\r\nproduct_string:");wprintf(info->product_string);
printf("\r\nusage_page:%d",info->usage_page);
printf("\r\nusage:%d",info->usage);
printf("\r\ninterface_number:%d\r\n",info->interface_number);
if (info->next != NULL)
{
print_dev_info(info->next);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int res;
unsigned char buf[65];
wchar_t wstr[MAX_STR];
hid_device *handle;
int i;
// Initialize the hidapi library
res = hid_init();
hid_device_info *p_device_info = hid_enumerate(0x2047, 0x0301);
if (p_device_info == NULL)
{
printf("get hid device info error!\r\n");
}
print_dev_info(p_device_info);
// Open the device using the VID, PID,
// and optionally the Serial number.
char* path = NULL;
if (p_device_info->usage == 1)// select path by usage
{
path = p_device_info->path;
}
else if (p_device_info->next != NULL && p_device_info->next->usage == 1)
{
path = p_device_info->next->path;
}
if (path == NULL)
{
printf("no valid path!\r\n");
goto END_MAIN;
}
//handle = hid_open(0x2047, 0x0301, NULL);
handle = hid_open_path(path);
if (handle == NULL)
{
printf("hid device open error!\r\n");
goto END_MAIN;
}
buf[0] = 0x00;//endpoint
buf[1] = 0xa5;
buf[2] = 0x5a;
buf[3] = 0x00;
buf[4] = 0x09;
buf[5] = 0xc9;
buf[6] = 0x01;
buf[7] = 0xc1;
buf[8] = 0x0d;
buf[9] = 0x0a;
res = hid_write(handle, buf, 65);
printf("");
// Read requested state
res = hid_read_timeout(handle, buf, 65, READ_TIMEOUT_MS);
printf("hid read size:%d\r\n",res);
// Print out the returned buffer.
for (i = 0; i < res; i++)
{
if (i > 0 && i%16 == 0)
{
printf("\r\n");
}
printf("%02X ", buf[i]);
}
printf("\r\n");
// Close the device
hid_close(handle);
// Finalize the hidapi library
res = hid_exit();
END_MAIN:
hid_free_enumeration(p_device_info);
system("pause");
return 0;
}

该博客展示了一段在Windows系统下的代码,用于简单演示HID收发,支持USB复合设备。代码通过唯一路径打开设备,实现数据的发送与接收,还包含设备信息打印等功能,源码可在资源下载中获取。
825

被折叠的 条评论
为什么被折叠?



