PySerial:带有字母和引号的奇怪输出
PySerial : weird output with letter and quotation marks
所以我正在尝试使用 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 代码中,我对其进行编码,以便输出应该是 numeric.Below 是 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'
其次,一般人运行一个python脚本在shell上,会有一个'>>'表示运行ning进程已经完了,然后shell就可以关闭了。然而,在我的 python 脚本的输出被打印之后,脚本似乎仍然是 运行ning 因为没有出现“>>”。我尝试使用 ctrl+c 来杀死但无法关闭,当我尝试关闭 shell 时,会弹出一个 window 说 'your program is still running, do you want to kill it?'。那么,在打印输出后,无论如何要完成 运行ning 吗?
我是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 从我的 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 代码中,我对其进行编码,以便输出应该是 numeric.Below 是 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'
其次,一般人运行一个python脚本在shell上,会有一个'>>'表示运行ning进程已经完了,然后shell就可以关闭了。然而,在我的 python 脚本的输出被打印之后,脚本似乎仍然是 运行ning 因为没有出现“>>”。我尝试使用 ctrl+c 来杀死但无法关闭,当我尝试关闭 shell 时,会弹出一个 window 说 'your program is still running, do you want to kill it?'。那么,在打印输出后,无论如何要完成 运行ning 吗?
我是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()