0

I want to write a Python program that will sample a sensor at a fixed sampling rate. Is there any elegant way of doing this?

Currently, I am using the time.time and time.sleep commands to enforce this manually. While this does work, it is creating a small drift. Also, it seems to be a not very nice way of doing so, and I hope there is a more pythonic way of doing this:

def mock_signal(x):
    # Just a random number as the sensor signal
    return np.random.random()*x


def sampling(fs=1, x=1):
    T = 1/fs # sampling period
    t_ground = time.time()
    while True:
        t_start = time.time()
        y = mock_signal(x)
        print('%.5f | Sensor Value %.2f' % (t_start - t_ground, y))
        t_duration = time.time()
        # Sleeping for the remaining period
        time.sleep(T - (t_duration-t_start))

Ideally, I would like to have a function or class that would sample the sensor (basically call the 'mock_signal' function) and append the new sample to a list or array. The latest entry in said array should than be accessible by a call similar to the multiprocessings Connection.recv()

Thanks in advance :)

Nico
  • 49
  • 5
  • 1
    [This question](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python) has some ideas on how to implement timed repeated functions. – glibdud Feb 18 '19 at 14:06

1 Answers1

0

May you can try something like that.

import threading

t_ground = time.time()

def sampling():
    t_ground = time.time()
    threading.Timer(T, sampling).start()
    t_start = time.time()
    y = mock_signal(1)

    print('%.5f | Sensor Value %.2f' % (t_start - t_ground, y))

It's just an example. You need to change it to your need.

andercruzbr
  • 454
  • 2
  • 10