gpt4 book ai didi

python-3.x - Python3 双向串行通信 : Reading In Data

转载 作者:行者123 更新时间:2023-12-01 00:25:17 25 4
gpt4 key购买 nike

我正在尝试通过 Python3 建立双向通信。有一个激光测距仪插入我的一个 USB 端口,我想向它发送/接收命令。我有一张可以发送的命令以及它们会返回什么,所以这部分已经存在了。

我需要的是一种实时进行的便捷方式。到目前为止,我有以下代码:

import serial, time

SERIALPORT = "/dev/ttyUSB0"
BAUDRATE = 115200

ser = serial.Serial(SERIALPORT, BAUDRATE)
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = None #block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 0 #timeout for write

print ("Starting Up Serial Monitor")

try:
ser.open()
except Exception as e:
print ("Exception: Opening serial port: " + str(e))

if ser.isOpen():
try:
ser.flushInput()
ser.flushOutput()
ser.write("1\r\n".encode('ascii'))
print("write data: 1")
time.sleep(0.5)
numberOfLine = 0
while True:
response = ser.readline().decode('ascii')
print("read data: " + response)
numberOfLine = numberOfLine + 1
if (numberOfLine >= 5):
break
ser.close()
except Exception as e:
print ("Error communicating...: " + str(e))
else:
print ("Cannot open serial port.")

所以在上面的代码中,我发送了“1”,它应该触发激光探测器的“getDistance()”函数并返回以毫米为单位的距离。我在 Putty 上试过这个,它可以工作,返回最多 4 位数字的距离。但是,当我启动上面的 Python 脚本时,我的输出只有以下内容:
Starting Up Serial Monitor
Exception: Opening serial port: Port is already open.
write data: 1
read data:

它永远存在。没有读取数据或任何内容。

我错在哪里?

最佳答案

显然更简单的代码版本解决了这个问题。

import serial
import time

ser = serial.Serial('/dev/ttyUSB0', 115200, timeout = 1) # ttyACM1 for Arduino board

readOut = 0 #chars waiting from laser range finder

print ("Starting up")
connected = False
commandToSend = 1 # get the distance in mm

while True:
print ("Writing: ", commandToSend)
ser.write(str(commandToSend).encode())
time.sleep(1)
while True:
try:
print ("Attempt to Read")
readOut = ser.readline().decode('ascii')
time.sleep(1)
print ("Reading: ", readOut)
break
except:
pass
print ("Restart")
ser.flush() #flush the buffer

根据需要输出:
Writing:  1
Attempt to Read
Reading: 20
Restart
Writing: 1
Attempt to Read
Reading: 22
Restart
Writing: 1
Attempt to Read
Reading: 24
Restart
Writing: 1
Attempt to Read
Reading: 22
Restart
Writing: 1
Attempt to Read
Reading: 26
Restart
Writing: 1
Attempt to Read
Reading: 35
Restart
Writing: 1
Attempt to Read
Reading: 36

关于python-3.x - Python3 双向串行通信 : Reading In Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com