前期准备
软件:bus hound,收费软件, 可以查看hid设备的vid和pid。
开源库:hidapi,直接包含h文件和c文件,不使动态链接库的形式。
开发环境:Qt,vs2015 64bit编译器
测试代码
pro文件:
SOURCES += \
main.cpp \
mainwindow.cpp \
hid.c
HEADERS += \
mainwindow.h \
hidapi.h
根据系统和vs版本的不同,还有加入SetupAPI.Lib,否则编译不通过
LIBS += $$quote(C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64\SetupAPI.Lib)
main函数
#define MAX_STR 256
void Wchar_tToString(std::string& szDst, wchar_t *wchar)
{
wchar_t * wText = wchar;
DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);// WideCharToMultiByte的运用
char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量
psText = new char[dwNum];
WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);// WideCharToMultiByte的再次运用
szDst = psText;// std::string赋值
delete []psText;// psText的清除
}
int main(int argc, char *argv[])
{
int res;
unsigned char buf[64];
wchar_t wstr[MAX_STR];
hid_device *handle;
int i;
qDebug() << "init start" << endl;
res = hid_init();
qDebug() << "init success" << endl;
//通过bus hound软件查看hid设备的vid和pid。
handle = hid_open(0x0483, 0xa005, NULL);
// Read the Manufacturer String
res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
string manufacture;
Wchar_tToString(manufacture,wstr);
qDebug() << "Manufacturer String:" << manufacture.c_str() << endl;
// Read the Product String
res = hid_get_product_string(handle, wstr, MAX_STR);
string product;
Wchar_tToString(product,wstr);
qDebug() << "Product String:" << product.c_str() << endl;
// Read the Serial Number String
res = hid_get_serial_number_string(handle, wstr, MAX_STR);
string serial_number;
Wchar_tToString(serial_number,wstr);
qDebug() << "Serial Number String:" << serial_number.c_str() << endl;
// Read Indexed String 1
res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
string indexed;
Wchar_tToString(indexed,wstr);
qDebug() << "Indexed String 1:" << indexed.c_str() << endl;
while(1)
{
//收到后判断第一字节,第一字节是多少,取后续多少字节进行处理
res = hid_read(handle, buf, 64);
qDebug() << buf[0] << " " << buf[1] << " " << buf[2] <<endl;
}
// Finalize the hidapi library
res = hid_exit();
return 0;
}
具体协议
一次发送64个字节,第一字节是将要发送的数据长度,大小不能超过63。下位机收到后判断收到的首字节是多少,从而决定从后面取多少字节进行处理。
接收同理,收到后判读首字节,然后从第二字节开始取出首字节个数的字节,就是有效信息。