I'm taking my first steps in Python programming. I'm using a TFMini Plus Lidar connected to a Windows 7 computer through a USB to TTL serial connection.
I'm getting readings through this code:
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!")
I want to have a single reading every X second (that can be set as per user choice), but I cannot find a way to do it. When I use time.sleep(), the readings get all the same:
Basically i want to delay the frequency of readings or make it to selectively give me a single reading from the ones captured. How can I do it?
Thanks
You could use the schedule
package. I.e.:
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)