1.要透過libusb來操控USB Device,首先您需要安裝libusb。Debian的使用者操作指令如下:
-先尋找適當的usb套件。
$apt-cache search libusb
libftdi0 - Library to control and program the FTDI USB controller
libhid-dev - userspace USB HID development files
libhid0 - userspace USB HID access library
libusb++-0.1-4c2 - userspace C++ USB programming library
libusb++-dev - userspace C++ USB programming library development files
libusb-0.1-4 - userspace USB programming library
libusb-dev - userspace USB programming library development files
python-hid - Python wrapper for USB HID access library
sulu - File Mananger for Samsung Uproar and YEPP
-安裝libusb開發版本(Note:開發版才會有header file可供連結參考)
$apt-get install libusb-dev
2.撰寫程式尋找您要的USB Device。
#include
usb_dev_handle *dev_handle;
// Search device and open it
int devopen(void)
{
struct usb_bus *busses, *bus;
int c, i, a;
struct usb_device *dev;
usb_init();
usb_find_busses();
usb_find_devices();
busses = usb_get_busses();
for (bus = busses; bus; bus = bus->next) {
for (dev = bus->devices; dev; dev = dev->next) {
struct usb_device_descriptor *desc;
desc = &(dev->descriptor);
printf("Vendor/Product ID: %04x:%04x\n", desc->idVendor,
desc->idProduct);
if ((desc->idVendor == 0x1234) && (desc->idProduct == 0x4321)) {
goto a;
}
}
}
if ((bus == NULL) || (dev == NULL))
return -1;
a:
dev_handle = usb_open(dev);
if (dev_handle == NULL) {
printf("USB IO open failed.\n");
return -1;
}
usb_reset(dev_handle);
return 0;
}
// Output interface
// 0x02 is (Output direction | endpoint address).
// 2000 is time out value.
int devwrite(char *buffer, int len)
{
return usb_bulk_write(dev_handle, 0x02, buffer, len, 2000);
}
// Input interface
// 0x86 is (Input direction | endpoint address).
int devread(char *buffer, int len)
{
return usb_bulk_read(dev_handle, 0x86, buffer, len, 2000);
}
int main(void)
{
int result = 0;
char write_buffer[10] = {0};
char read_buffer[10] = {0};
result = devopen();
if (result < 0)
{
printf("Can't open usb device.\n");
} else
{
// send command to usb device.
write_buffer[0] = 0x0B;
write_buffer[1] = 0x01;
write_buffer[2] = 0x02;
result = devwrite(write_buffer, 3);
if (result == 3)
{
// get response from usb device
result = devread(read_buffer, 10);
}
}
return 0;
}
3.編譯上述程式
gcc -g -O0 -o xxx xxx.c -lusb
4.請使用Superuser權限執行它。或者將其檔案屬性進行變更。
chown root xxx
chgrp root xxx
chmod +s xxx
透過上述的機制,您將可以不用撰寫Linux USB Device Driver,即可操作Device Driver。
參考資料:
‧Jollen的Bolg--"libusb 簡介與第一個範例" (http://www.jollen.org/blog/2008/01/libusb_hello_world.html)
‧libusb Developers Guide (http://libusb.sourceforge.net/doc/index.html)
‧testlibusb.c (在libusb的source code中)
感謝Jserv的建議與協助,讓偶有機會做此嘗試。
1 則留言:
「安裝libusb開發版本」或許會令人誤解,改稱「安裝libusb開發套件」,應該清楚一些 :)
Thanks!
張貼留言