玩轉USB HID系列:Linux下使用Python開發USB HID

玩轉USB系列:Linux下使用Python開發USB HID

實驗環境

  1. ubuntu 16.04 LTS 64-bit
  2. python 3
  3. STM32做下位機

開發步驟

安裝pyusb 庫

pip install pyusb

我們來與HID設備通訊!

我的STM32信息:
interface 0
END POINT 0x01: OUT
END POINT 0x82: IN
包大小:64 byte

完成功能:PC機向STM32寫入2個字節(查詢命令)
STM32返回5個字節:[0]:數據長度(這裏應該爲4)[0]-[4]:一個double的電壓值的內存形式

import usb.util
import usb.core
import sys
from ctypes import *
import types  
import struct
import time
write_buffer=[0x02,0x64]

class Point(Union):
    _fields_ = [ ('charx',  c_char*8),('double',  c_double)]


def Init_usb_hid_device(vid,pid):
	dev=usb.core.find(idVendor= vid, idProduct= pid)
	if(dev==None):
	    	return None
	else:
		# Attach and detach the usb,must use this code ahead 
		if dev.is_kernel_driver_active(0):
		    dev.detach_kernel_driver(0)
		dev.set_configuration()
		return dev

def hid_get_adc_volt():
	global volt
	hid_dev.write(0x01,write_buffer,1000)
	receive_buffer=hid_dev.read(0x82,64,1000)
	test_2 = (c_char*4)()
	test_2[0]=receive_buffer[1]
	test_2[1]=receive_buffer[2]
	test_2[2]=receive_buffer[3]
	test_2[3]=receive_buffer[4]
	print(struct.unpack('f',bytes(test_2)))
	time.sleep(0.5)




hid_dev=Init_usb_hid_device(0x0483,0xa010)
if(hid_dev!=None):
	while(1):	
		hid_get_adc_volt()
	
else:
	print("HID device not found!")

注意

Windows中這樣做好像不好用(至少我實驗是不行的)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章