python - 从 Arduino 检测 Python 中的状态变化

标签 python arduino

我正在尝试检测 Arduino 的开关是否打开或关闭,将数据发送到 Python 并在 GUI 中显示结果 下面的Python代码将把串口数据读取到Python中,如下所示; (不是我的代码,我必须添加)

import serial
ser = serial.Serial('com3',9600)
ser.flushInput()
ser.flushOutput()
while True:
        ser.flushInput()
        ser.flushOutput()
        passcode = ser.read()

        if passcode == b'1':
            print("Switch is ON")
        if passcode == b'0':
            print("Switch if OFF")

结果在Python IDE上显示如下[取决于结果] 这是串口输出结果

关闭时切换

关闭时切换

关闭时切换

开关已打开

开关已打开

开关已打开

现在我的问题是?

有什么方法可以让我在 Python 中读取“开关已打开”或“开关已关闭”[不是连续的串行结果],并理想地将结果显示到 Tkinter

最佳答案

我对你的问题的理解是“我怎样才能使它只在状态更改时打印输出?”。

为此,您需要在本地存储状态,然后将新状态与存储的状态进行比较。 最简单的方法是使用变量,例如:switch_state。

所以:

import serial

ser = serial.Serial('com3',9600)
switch_state = None  # 0 for off, 1 for on, None - not yet set

ser.flushInput()
ser.flushOutput()

while True:
        ser.flushInput()
        ser.flushOutput()
        passcode = ser.read()

        if passcode == b'1' and switch_state != 1:
            print("Switch is ON")
            switch_state = 1

        if passcode == b'0' and switch_state != 0:
            print("Switch if OFF")
            switch_state = 0

我还没有尝试过代码 - 但这应该是解决您问题的足够简单的解决方案。

关于python - 从 Arduino 检测 Python 中的状态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987108/

相关文章:

python - 如何在python中使用多处理在进程内创建进程?

python - 将管道放入字典

arduino - 在 OLED 显示屏上滚动长文本

Python 自动选择串口(适用于 Arduino)

c - Arduino 应有的 HTTPS 支持

python - 与 Arduino 的串行通信仅在屏幕运行时有效

c++ - Serial.read() 跳过串行输入

python - 使用 PyDict_SetItemString 进行引用计数

python - Django APIClient 发布为空

python - 如何让 gobject.idle_add() 通过引用传递参数?