【问题标题】:Getting a Com Port serial reading in a certain period of time在特定时间段内获取 Com 端口串行读数
【发布时间】:2019-12-30 22:23:12
【问题描述】:

我正在迈出 Python 编程的第一步。我正在使用通过 USB 到 TTL 串行连接连接到 Windows 7 计算机的 TFMini Plus 激光雷达。

我正在通过这段代码获得读数:

import time
import serial
import datetime
import struct
import matplotlib.pyplot as plt

ser = serial.Serial(
        port="COM1",
        baudrate = 115200,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=1
)

while 1:
        x = ser.readline().decode("utf_8").rstrip('\n\r')
        y=float(x)
        print(y)
        #time.sleep(0.1)
        if y > 3:
                print("too far!")

我希望每 X 秒读取一次(可以根据用户的选择进行设置),但我找不到方法。当我使用 time.sleep() 时,读数都一样:

Readings with time.sleep on

基本上我想延迟读数的频率,或者让它有选择地从捕获的读数中给我一个读数。我该怎么做?

谢谢

【问题讨论】:

    标签: python serial-port lidar lidar-data


    【解决方案1】:

    您可以使用schedule 包。即:

    import time
    import serial
    import schedule
    
    ser = serial.Serial(
            port="COM1",
            baudrate = 115200,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
    )
    
    def read_serial_port():
        x = ser.readline().decode("utf_8").rstrip('\n\r')
        y=float(x)
        print(y)
        if y > 3:
            print("too far!")
    
    rate_in_seconds = 10
    schedule.every(rate_in_seconds).seconds.do(read_serial_port)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    【讨论】:

    • 嘿,arghol,非常感谢。那行得通!每次我们读取串行端口时,我只需要添加一个额外的刷新输入:ser.flushInput()。我把它放在 def read_serial_port 中,在 readline() 行之前
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多