我在使用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