【发布时间】:2021-12-07 14:23:06
【问题描述】:
我正在从机器读取数据到 Windows 7。使用 python,我读取串行端口,处理数据,然后将数据写入不同的串行端口。使用 com0com 空调制解调器仿真器,将数据发送到另一个程序。这是我正在使用的代码:
import serial
import time
ser = serial.Serial(port='COM7', baudrate=9600)
ser2 = serial.Serial(port='COM8', baudrate=9600)
value_one = None
while (True):
# Check if incoming bytes are waiting to be read from the serial input
# buffer.
# NB: for PySerial v3.0 or later, use property `in_waiting` instead of
# function `inWaiting()` below!
if (ser.in_waiting > 16):
# read the bytes and convert from binary array to ASCII
data_str = ser.read(ser.in_waiting).decode('ascii')
if (value_one == None):
time.sleep(1)
print(data_str)
value_one_parse = data_str[7:9]
print(value_one_parse)
value_one = float(value_one_parse)
print(value_one)
else:
time.sleep(1)
print(data_str)
value_two_parse = data_str[7:9]
print(value_two_parse)
value_two = float(value_two_parse)
print(value_two)
avg = ((value_one + value_two)/2)
print(avg)
avgprep = str(avg) + '\r\n'
print(avgprep)
ser2.write(avgprep.encode('utf-8'))
value_one = None
value_two = None
time.sleep(0.01)
那么如果 avgprep = 71.1,为什么我只收到程序的第一个数字 7?
【问题讨论】:
-
考虑使用日志记录,而不是大量的打印语句。
-
当您说
avgprep=71.1时,您的意思是print(avgprep)代码行打印'71.1'?如果是这样,听起来您正在尝试调试为什么ser2.write(b'71.1')似乎只发送'7'? -
在进行复杂的处理之前,您是否尝试过使用一个简单地显示接收到的数据而不考虑字节数的程序来检查操作?如果你能确认,想想它和现在的程序有什么区别。
-
是的 print(avgprep) 显示 71.1。它只发送 1 个字符,或者我只接收 1 个字符。只是不确定其余部分发生了什么。
标签: python serial-port pyserial write