gpt4 book ai didi

python - PySerial : weird output with letter and quotation marks

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

所以我尝试使用 Python 读取 Arduino 板上 DS18B20 温度传感器的值。在我的Python代码中,我使用Pyserial来访问端口,下面是代码。

import serial
def readTemp():
temp = serial.Serial('COM3', 9600)
line = temp.readline().strip()
while line:
print(line.strip())
line = temp.readline().strip()
temp.close()

def main():
readTemp()

main()

在我的 Arduino 代码中,我对其进行了编码,以便输出应该是数字。下面是 Arduino 的输出:

21.3125
22.3750
22.3750
22.3750
22.3750

但是,当我运行Python代码时,输​​出添加了一些字母和引号,但我不知道为什么以及如何删除它们。以下是 Python 的输出。

b'22.3750'
b'22.0625'
b'22.0625'
b'22.0625'
b'22.0625'

其次,通常当人们在shell上运行python脚本时,会有一个“>>”表示运行过程已经完成,然后就可以关闭shell了。但是,在打印我的 python 脚本的输出后,该脚本似乎仍在运行,因为没有出现“>>”。我尝试使用 ctrl+c 来杀死但无法,当我尝试关闭 shell 时,会弹出一个窗口,提示“您的程序仍在运行,是否要杀死它?”。那么打印输出后是否有办法完成运行呢?

我是Python新手,刚刚学习pyserial。非常感谢您,我将感谢您的帮助。

最佳答案

关于第一个问题,

别担心,这些值以字节形式读取。前面的b表示字节。您可以将其转换为字符串使用解码('utf-8')

代码中需要更改

替换

print(line.strip())

bytesValue = line.strip()
numericValue = int(bytesVale.decode('utf-8'))
print(numericValue)

关于第二个问题,您的进程尚未完成,因为它正在监听设备。条件

while line:

使进程保持事件状态。

如果您希望程序只读取一个值并退出,可以使用 if 而不是 while

line = temp.readline().strip()
if line:
bytesValue = line.strip()
numericValue = int(bytesVale.decode('utf-8'))
print(numericValue)
temp.close()

关于python - PySerial : weird output with letter and quotation marks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53456475/

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