gpt4 book ai didi

linux - 使用Python通过Serial读取不固定数量的字节

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:29 24 4
gpt4 key购买 nike

我正在尝试从串行端口读取不固定数量的字节。我可以使用 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()

Code output

最佳答案

您可以使用:

import serial
import time

ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200, timeout=1)

while True:
val = ser.readline().strip()
if(val):
print (val)

关于linux - 使用Python通过Serial读取不固定数量的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55622990/

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