linux - 需要 libusb 基本示例

标签 linux libusb

我正在编写旨在通过 USB 控制某些设备的用户空间程序,因此我决定使用 libusb (libusb-1.0) 向该设备发送控制消息并从该设备接收响应。

但是我的代码中不断收到以下一堆错误(即使它是使用“sudo”执行的):

USB error: could not set config 0: Device or resource busy
set configuration: failed
Check that you have permissions to write to 007/012 and, if you don't, that you set up hotplug (http://linux-hotplug.sourceforge.net/) correctly.
USB error: could not claim interface 0: Device or resource busy
claim interface: failed
USB error: error submitting URB: No such file or directory
bulk writing: failed
USB error: error submitting URB: No such file or directory
bulk reading: failed
response was: 

代码是:

usb_dev_handle* find_device ();

int 
main (int argc, char *argv[])
{
    usb_dev_handle* udev;
    int status;
    char request[] = "K1"; // 'ping' command used to check communication
    char response[256];

    udev = find_device ();
    // udev is successfully found here

    status = usb_set_configuration (udev, 0);
    printf ("set configuration: %s\n", status ? "failed" : "passed");

    status = usb_claim_interface (udev, 0);
    printf ("claim interface: %s\n", status ? "failed" : "passed");

    status = usb_bulk_write (udev, 3, request, sizeof (request), 500);
    printf ("bulk writing: %s\n", status ? "failed" : "passed");

    status = usb_bulk_read (udev, 2, response, sizeof (response), 500);
    printf ("bulk reading: %s\n", status ? "failed" : "passed");

    printf ("response was: %s\n", response);

    usb_close (udev);

    return 0;
}

代码有什么问题?以及如何解决?

操作系统:Ubuntu 10.10

最佳答案

回答这个问题,因为我在同一个操作系统上遇到过这个问题,并且能够通过以下方式解决:

下载并编译最新的libusb源代码1.0.8。

以下是我用来声明 USB 接口(interface) 0 的一些 API 调用:

libusb_init(NULL);
libusb_open_device_with_vid_pid(NULL, vendor_id, product_id);
libusb_detach_kernel_driver(devh, 0);
libusb_claim_interface(devh, 0);
libusb_close(devh);
libusb_exit(NULL);

上例中变量说明:

static struct libusb_device_handle *devh = NULL;
uint16_t vendor_id;
uint16_t product_id;

要获取供应商 ID 和产品 ID,您可以运行以下命令(例如我的设备信息)

$ lsusb
...
Bus 001 Device 013: ID 0930:6544 Toshiba Corp. Kingston DataTraveler 2.0 Stick (2GB)
...

粗体冒号分隔的字符串分别包含供应商和产品 ID。

如何编译代码:

我使用以下命令来编译我的代码:

/bin/bash libtool --silent --tag=CC --mode=link g++ -Wall -Wundef -Wunused -Wshadow -D_DEBUG -I../libusb -g -O2 -o read read.cpp ../libusb/libusb-1.0.la -lusb-1.0 -lrt

将解压后的libusb-1.0.8目录下的libtool复制到编译区

希望这对您有所帮助。

关于linux - 需要 libusb 基本示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4813764/

相关文章:

c - 非规范和非回声模式不适用于管道

linux - VMWare guest 无法连接到主机服务器

c - 如何识别 USB ISO 传输中用于 CRC(校验和)的数据字节?

linux - 用于 USB 目标用户空间驱动程序的 libusb

linux - 模拟 USB 设备以实现自动化

c++ - 如何将成员函数指针传递给 libusb?

php - 如何检查是否有正在运行的 wget 实例

linux - SUSE Linux Enterprise 中的 perl $filename 与 ./$filename

linux - wc -m in linux excess 1 值

macos - USB 存储设备的无代码 kext