我目前正在为学校做一个树莓派项目,我在我的车里从OBD2到usb传感器读取数据。
当我使用Screen连接到串行端口时,一切工作正常,但是当我尝试在python中执行时,serial.readline()返回一个空字符串。
有人知道我如何从python的串行端口检索数据吗?
我已经试过了所有可行的方法。
import serial
ser = 0
#Function to Initialize the Serial Port
def init_serial():
global ser
ser = serial.Serial()
ser.baudrate = 38400
ser.port = '/dev/ttyUSB0'
ser.timeout = 1
ser.open() #Opens SerialPort
# print port open or closed
if ser.isOpen():
print 'Open: ' + ser.portstr
#Function Ends Here
init_serial()
temp = raw_input('Type what you want to send, hit enter:rn')
ser.write(temp) #Writes to the SerialPort
while 1:
bytes = ser.readline() #Read from Serial Port
print bytes #Print What is Read from Port
您可能没有发送有效的数据来获得响应。我相信ODB2接口使用AT命令集。发送ATn可能是一个很好的起点。
我使用蓝牙ODB2接口,发现串行波特率是固定的。使用其他波特率无法正确获取数据。
我建议从putty或其他支持串行端口的终端进行测试,直到您得到设备的正确响应。然后使用有效的设置来排除代码故障。
您的命令中没有发送rn, ELM327要求在命令末尾添加一个新的行字符。