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 :)