I am writing an application in python to acquire data using a serial communication. I use the pyserial library for establishing the communication. What is the best approach to request data in an interval (eg every 2 seconds). I always have to the send a request, wait for the answer and start the process again.
Asked
Active
Viewed 338 times
0
-
show example of the code you have. Makes it more clear what to recommend. – David Bern Aug 28 '17 at 06:53
-
Serial communication never offering used a `time.sleep()` functions. Send request >> wait data `while ser.inWaiting() < 1 : data=ser.read(ser.inWaiting()); if data : break;` >> make new request ! Opps need a `try-except` for what happen on serial bus! – dsgdfg Aug 28 '17 at 07:01
2 Answers
0
if this a "slow" process, that does not accurate time precision, use a while loop and time.sleep(2) to timeout the process for 2 seconds.

sancelot
- 1,905
- 12
- 31
0
I thought about using a separate thread to prevent the rest of the applicaiton from freezing. The thread takes a function which requests data from the instrument.
class ReadingThread(Thread):
'''Used to read out from the instrument, interrupted by an interval'''
def __init__(self, controller, lock, function, queue_out, interval=3 , *args, **kwargs):
Thread.__init__(self)
self.lock = lock
self.function = function
self.queue_out = queue_out
self.interval = interval
self.args = args
self.kwargs = kwargs
self.is_running = True
def run(self):
while self.is_running:
with self.lock:
try:
result = self.function(self.args, self.kwargs)
except Exception as e:
print(e)
else:
self.queue_out.put(result)
time.sleep(self.interval)
def stop(self):
self.is_running = False

Molitoris
- 935
- 1
- 9
- 31