pyserial time based repeated data request

367 views Asked by At

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.

2

There are 2 answers

0
sancelot On

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.

0
Molitoris On

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