PyUSBとは
Pythonからlibusbを利用してUSB機器を操作する機能拡張モジュールです。
PyUSB |
ホームページ |
SourceForgeプロジェクトページ |
libusb |
SourceForgeプロジェクトページ |
libusb-win32 |
PythonでEZUSB-FX2を動かす
(2010-07-23更新)
PyUSBを利用し,パイプ番号を指定してバルク転送を実行するモジュールのソースをつぎに示します。 プログラム本体として実行すると,50行目以降のサンプルプログラムが動作します。
当研究室ではつぎの環境でEZUSB-FX2マイコンボード(発売元: ストロベリー・リナックス)を動作させることができました。
- Windows XP, Python 2.4.4, PyUSB 0.3.5, libusb-win32 0.1.8.0
- Mac OS X 10.4.11 (PPC G4), Python 2.5.2, PyUSB 0.4.1, libusb 0.1.12
Mac OS X 10.6.4 (Intel Core 2 Duo), Python 2.6.5, PyUSB 0.4.3**, libusb 1.0.8*, libusb-compat 0.1.3*
Mac OS X 10.6では,つぎのように環境変数・オプションを指定してビルドしています。
*
./configure CC="gcc -arch x86_64 -arch i386 -arch ppc" CXX="g++ -arch x86_64 -arch i386 -arch ppc" CPP="gcc -E" CXXCPP="g++ -E"
**
MACOSX_DEPLOYMENT_TARGET="10.6" ARCHFLAGS="-arch x86_64 -arch i386 -arch ppc" python2.6 setup.py install
当研究室ではモーションキャプチャの研究に使用しています。
『pyusbモジュールについて。』(PythonMatrixJp),『libusbについて』(Linux工作室)を参考にさせていただきました。
1 import usb
2
3 class UsbDevice:
4 def __init__(self, idVendor, idProduct):
5 busses = usb.busses()
6 for bus in busses:
7 devices = bus.devices
8 for device in devices:
9 #print hex(device.idVendor), hex(device.idProduct)
10 if (device.idVendor, device.idProduct) == (idVendor, idProduct):
11 self.device = device
12 self.configuration = self.device.configurations[0]
13 self.interface = self.configuration.interfaces[0][0]
14 self.endpoints = []
15 self.pipes = []
16 for endpoint in self.interface.endpoints:
17 self.endpoints.append(endpoint)
18 self.pipes.append(endpoint.address)
19 return
20 raise RuntimeError, 'Device not found'
21
22 def open(self):
23 if hasattr(self, 'handle'):
24 raise RuntimeError, 'Device already opened'
25 self.handle = self.device.open()
26 self.handle.setConfiguration(self.configuration)
27 self.handle.claimInterface(self.interface)
28 self.handle.setAltInterface(self.interface)
29
30 def close(self):
31 if hasattr(self, 'handle'):
32 self.handle.releaseInterface()
33 del self.handle
34 else:
35 raise RuntimeError, 'Device not opened'
36
37 def bulkWrite(self, pipeno, buffer, timeout=100):
38 if hasattr(self, 'handle'):
39 self.handle.bulkWrite(self.pipes[pipeno], buffer, timeout)
40 else:
41 raise RuntimeError, 'Device not opened'
42
43 def bulkRead(self, pipeno, size, timeout=100):
44 if hasattr(self, 'handle'):
45 data = self.handle.bulkRead(self.pipes[pipeno], size, timeout)
46 return map(lambda x: 0xFF & x, data)
47 else:
48 raise RuntimeError, 'Device not opened'
49
50 if __name__=='__main__':
51 device = UsbDevice(0x0547, 0x1002) # EZ-USB FX2
52 device.open()
53 #print device.pipes
54 device.bulkWrite(0, [0])
55 print device.bulkRead(2, 12, 1000)
56 device.close()
Pythonのページに戻る
SasadaLabWiki