我在使用pyUSB庫從ELM327 OBDII向USB設備讀取數據時遇到問題。我知道我需要在寫入端點上向設備寫入命令,並在讀取端點上讀取接收到的數據。它似乎並不想爲我工作。使用pyUSB從ELM327 OBDII向USB設備讀取數據
我寫了這個我自己的類obdusb:
import usb.core
class obdusb:
def __init__(self,_vend,_prod):
'''Handle to USB device'''
self.idVendor = _vend
self.idProduct = _prod
self._dev = usb.core.find(idVendor=_vend, idProduct=_prod)
return None
def GetDevice(self):
'''Must be called after constructor'''
return self._dev
def SetupEndpoint(self):
'''Must be called after constructor'''
try:
self._dev.set_configuration()
except usb.core.USBError as e:
sys.exit("Could not set configuration")
self._endpointWrite = self._dev[0][(0,0)][1]
self._endpointRead = self._dev[0][(0,0)][0]
#Resetting device and setting vehicle protocol (Auto)
#20ms is required as a delay between each written command
#ATZ resets device
self._dev.write(self._endpointWrite.bEndpointAddress,'ATZ',0)
sleep(0.002)
#ATSP 0 should set vehicle protocol automatically
self._dev.write(self._endpointWrite.bEndpointAddress,'ATSP 0',0)
sleep(0.02)
return self._endpointRead
def GetData(self,strCommand):
data = []
self._dev.write(self._endpintWrite.bEndpointAddress,strCommand,0)
sleep(0.002)
data = self._dev.read(self._endpointRead.bEndpointAddress, self._endpointRead.wMaxPacketSize)
return data
所以我再使用這個類,並使用此代碼調用GetData方法:
import obdusb
#Setting up library,device and endpoint
lib = obdusb.obdusb(0x0403,0x6001)
myDev = lib.GetDevice()
endp = lib.SetupEndpoint()
#Testing GetData function with random OBD command
#0902 is VIN number of vehicle being requested
dataArr = lib.GetData('0902')
PrintResults(dataArr)
raw_input("Press any key")
def PrintResults(arr):
size = len(arr)
print "Data currently in buffer:"
for i in range(0,size):
print "[" + str(i) + "]: " + str(make[i])
這永遠只能輸出數字1和數組中的[0]和[1]元素爲60。沒有其他數據已從命令返回。無論設備是否連接到汽車,都是這種情況。我不知道這2條信息是什麼。我期待它返回一串十六進制數字。有人知道我在這裏做錯了嗎?
感謝您的評論。我不知道它期待回車。由於沒有太多的信息,這些東西很難研究。我可以用命令發送回車還是必須單獨發送? ATAT命令實際上做了什麼?如果我使用它,我可以省略時間延遲?你能否向我指出一些與此相關的資源?這是很多問題:P再次感謝:) – Granttastic 2013-05-08 22:04:34
@Granttastic,更新了我的答案! :) – 2013-05-09 18:35:33
你能幫我關於獲取VIN號碼響應這個問題嗎? http://stackoverflow.com/questions/19158165/unable-to-get-vin-number-response-from-obd-2-device – iCoder 2013-10-05 06:47:35