在一定时间内获取 Com 端口串行读取



我正在迈出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('nr')
y=float(x)
print(y)
#time.sleep(0.1)
if y > 3:
print("too far!")

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

阅读时间.睡眠

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

谢谢

您可以使用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('nr')
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)

最新更新