gpt4 book ai didi

python - 需要在Python中不断监控串口数据

转载 作者:太空狗 更新时间:2023-10-30 01:24:21 25 4
gpt4 key购买 nike

现在我正在使用 Arduino 将数据从模拟传感器发送到 COM4。我正在尝试制作一个持续监控该数据并查找特定参数的 python 脚本。

我试过类似的方法,但它没有正确提醒我

import serial
from Tkinter import *
import tkMessageBox

port = "COM4"
ser = serial.Serial(port,9600)
value = 0

while 1:
value = ser.read()
if value > 400:
tkMessageBox.showwarning(
"Open file",)
time.sleep(1)

最佳答案

如果您使用的serial 包是pySerial , 注意 Serial.read() method 的定义:

read(size=1)

Parameter: size – Number of bytes to read.

Returns: Bytes read from the port.

Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.

虽然您正在尝试处理 byte 对象,但您可能(取决于 Python 版本)正在处理 strbytes(数组)对象.这些对象不一定对应于整数值。

即使从 read() 接收到 byte 对象,最大的无符号整数也将是 255。将 value 与 400 进行比较没有意义。尝试使用简单的调试输出查找返回对象的类型。

print type(value)

如果你需要处理一个str对象,检查ord()的使用用于转换。

(flush 建议是指原始问题,它使用了 print,而不是 tkinter)。

参见 how-to-flush-output-of-python-print ,并尝试命令行 shell,而不是可能影响输出缓冲的 IDE。

关于python - 需要在Python中不断监控串口数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2752809/

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