用Qt写上位机时,需要用摇杆来控制伺服等设备,大部分使用虚拟摇杆在软件上控制,有时候也需要实体摇杆映射数据来控制伺服运动。
开发环境:Qt5.14.2+MSVC2017 Windows环境
开发准备:hidapi库,源码下载地址:https://github.com/signal11/hidapi
一、hidapi库编译(Windows下)
下载hidapi源码后,找到hidapi-master\windows\hidapi.sln 打开
编译后生成hidapi.dll和hidapi.lib
二、HID/USB设备数据收发
推荐先获取设备的vid和pid如上图所示,关键代码如下:
void MainWindow::on_btn_HIDInfo_clicked()
{
struct hid_device_info *devs, *cur_dev;
devs = hid_enumerate(0x0, 0x0);
cur_dev = devs;
QString deviceInfo;
while (cur_dev) {
// qDebug()<<"Device Found:"<< cur_dev->vendor_id<< cur_dev->product_id<< cur_dev->path<< cur_dev->serial_number << cur_dev;
deviceInfo = QString("vid:%1 pid:%2 %3 %4").arg(cur_dev->vendor_id).arg(cur_dev->product_id).arg(cur_dev->path).arg(cur_dev->serial_number);
ui->plainTextEdit->appendPlainText(deviceInfo);
cur_dev = cur_dev->next;
}
hid_free_enumeration(devs);
}
打开USB/HID设备进行数据收发,关键代码
void MainWindow::getHIDData()
{
hid_init();
m_Handle = hid_open(1046, 45057, NULL);//vid和pid绑定
unsigned char buf1[4] = {0xff};
hid_set_nonblocking(m_Handle, 0);
// 数据接收
hid_read(m_Handle, buf1, 4);
// while(hid_read(handle, buf1, 8))
{
for(int i = 0; i < 4; i++)
{
qDebug("%d %02X",i, buf1[i]);
ui->plainTextEdit->appendPlainText(QString("%1 %2").arg(i).arg(QString::number(buf1[i], 16), 2, QLatin1Char('0')).toUpper());
}
ui->plainTextEdit->appendPlainText("\n");
}
// 数据发送
// unsigned char buffer[9];
// memset(buffer, 0, sizeof(buffer));
// buffer[0] = 0x00;
// buffer[1] = 0x20;
// buffer[2] = 0x00;
// buffer[3] = 0x02;
// buffer[4] = 0x00;
// buffer[5] = 0x07;
// hid_write(handle, buffer, 9);
hid_close(m_Handle);
m_Handle = nullptr;
}
hid_open(vid, pid, NULL);vid 和pid在上面HID信息中打印出来。
开始获取摇杆数据,摇杆型号为ChenGong FJ9S,四个字节数据表示:按钮1,2,3、上下、左右、旋转 四种功能