我正在尝试从串行端口读取不固定数量的字节。我可以使用read读取固定数量的字节,放入的字节数大于实际存在的字节数,这将导致它永远等待。输入的字节数少于实际出现的字节数将裁剪掉某些字符。使用read_all,输出似乎为空。 Readline()产生语法错误。我没有想法了,有什么想法吗?这是我的代码:
import time
import datetime
import serial
import os
# public variables
sensors = [] # list of sensor readings
wait = True
sensor_count = 10 # the zero based count of sensors
def pwr_solenoid(solenoid0=0, solenoid1=0, solenoid2=0, solenoid3=0):
# Defaults are for low signal values
# compile output
output = '9{solenoid0}{solenoid1}{solenoid2}{solenoid3}' \
.format(solenoid0=solenoid0, solenoid1=solenoid1, solenoid2=solenoid2, solenoid3=solenoid3).encode()
with serial.Serial('/dev/ttyACM0', baudrate=9600) as ser:
print("created connection to '/dev/ttyACM0'\n")
print("going to send:\t'{}'".format(output))
ser.write(output)
ser.reset_output_buffer()
# for testing to console
print("Value sent to the uC:\t'{}'".format(output.decode()))
# ***** READ from UART *****
#ser.in_waiting >= 12:
raw = ser.read(16)
print("printing raw value of ser.read(16)\n")
print(raw)
val = str(ser.read_all().decode()) # (3).decode()[2:])
#printing val
print("\n printing val using read_all \n")
print(val)
val1 = raw.decode()
#printing val of raw.decode()
print("\n pringting val of raw.decode() \n")
print(val1)
# print("printing value of ser.readline()\n"
# serreadlin = ser.readline() This line generates an error cannot use readline()
# print(serreadlin)
# print("printing val\n")
# print(val)
# exit()
答案 0 :(得分:0)
您可以使用:
import serial
import time
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200, timeout=1)
while True:
val = ser.readline().strip()
if(val):
print (val)