HIDAPI是一个USB和蓝牙的hid类设备在Widows、Liux、FreeBSD和Mac的C语言通用库,使用HIDAPI可以在Widows、Liux、FreeBSD和Mac平台进行USB和蓝牙的hid类设备通信,非常简单实用。
示例代码:
#iclude <stdio.h>#iclude <stdlib.h>#iclude "hidapi.h"it mai(it argc, char* argv[]){it res;usiged char buf[65];#defie MAX_STR 255wchar_t wstr[MAX_STR];hid_device *hadle;it i;// Eumerate ad prit the HID devices o the systemstruct hid_device_ifo *devs, *cur_dev;devs = hid_eumerate(0x0, 0x0);cur_dev = devs;while (cur_dev) {pritf("Device Foud\ type: %04hx %04hx\ path: %s\ serial_umber: %ls",cur_dev->vedor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_umber);pritf("\");pritf(" Maufacturer: %ls\", cur_dev->maufacturer_strig);pritf(" Product: %ls\", cur_dev->product_strig);pritf("\");cur_dev = cur_dev->ext;}hid_free_eumeratio(devs);// Ope the device usig the VID, PID,// ad optioally the Serial umber.hadle = hid_ope(0x4d8, 0x3f, NULL);// Read the Maufacturer Strigres = hid_get_maufacturer_strig(hadle, wstr, MAX_STR);pritf("Maufacturer Strig: %ls\", wstr);// Read the Product Strigres = hid_get_product_strig(hadle, wstr, MAX_STR);pritf("Product Strig: %ls\", wstr);// Read the Serial Number Strigres = hid_get_serial_umber_strig(hadle, wstr, MAX_STR);pritf("Serial Number Strig: %ls", wstr);pritf("\");// Sed a Feature Report to the devicebuf[0] = 0x2; // First byte is report umberbuf[1] = 0xa0;buf[2] = 0x0a;res = hid_sed_feature_report(hadle, buf, 17);// Read a Feature Report from the devicebuf[0] = 0x2;res = hid_get_feature_report(hadle, buf, sizeof(buf));// Prit out the retured buffer.pritf("Feature Report\ ");for (i = 0; i < res; i++)pritf("%02hhx ", buf[i]);pritf("\");// Set the hid_read() fuctio to be o-blockig.hid_set_oblockig(hadle, 1);// Sed a Output report to toggle the LED (cmd 0x80)buf[0] = 1; // First byte is report umberbuf[1] = 0x80;res = hid_write(hadle, buf, 65);// Sed a Output report to request the state (cmd 0x81)buf[1] = 0x81;hid_write(hadle, buf, 65);// Read requested stateres = hid_read(hadle, buf, 65);if (res < 0)pritf("Uable to read()\");// Prit out the retured buffer.for (i = 0; i < res; i++)pritf("buf[%d]: %d\", i, buf[i]);retur 0;}HIDAPI有四个后端:
Widows(usighid.dll)
Liux/hidraw(usigtheKerel'shidrawdriver)
Liux/libusb(usiglibusb-1.0)
FreeBSD(usiglibusb-1.0)
Mac(usigIOHidMaager)
评论