I want to save the velocity and position estimations from the encoder into a list to do extra analysis (and get the acceleration) and plotting. I simply tried to append the .encoder.vel_estimate to a list after a position changing command like below:
but it doesn’t work, it only saves a single value each time the line is run. I tried to see how it is done in the utils.py at the start_liveplotter function, but I couldn’t comprehend the loop.
EDIT1: I just found these two topics, but they are somewhat old, is there any better practice?
import time
velocity = []
pos = []
t = []
t_sample = 0.01 # Sample at 100Hz
t_wait = 6 # Wait six seconds between setpoint changes
t_start = time.time() # Timestamp for when we started sampling
while True:
odrv0.axis1.controller.input_pos = 10
t_0 = time.time()
while (time.time() - t_0 < t_wait):
velocity.append(odrv0.axis1.encoder.vel_estimate)
pos.append(odrv0.axis1.encoder.pos_estimate)
t.append(time.time() - t_start)
time.sleep(t_sample)
odrv0.axis1.controller.input_pos = 0
t_0 = time.time()
while (time.time() - t_0 < t_wait):
velocity.append(odrv0.axis1.encoder.vel_estimate)
pos.append(odrv0.axis1.encoder.pos_estimate)
t.append(time.time() - t_start)
time.sleep(t_sample)
Your issue is that the sampling code only runs once before the time.sleep(6) blocks for the six seconds. Here, we move it into a polling loop, so that there isn’t any actual blocking calls.
That’ll additionally capture the timestamps of each datapoint.
Note two things:
The while True loop will never exit - you should have some exit condition, such as a keyboard command (ctrl-C for instance), or an amount of time elapsing
Since there’s no limit to the amount of data stored in pos and velocity, it’ll quickly grow in memory size and may cause memory errors
Since you’re continuously appending to a list, Python will have to re-allocate the memory for this list. If you can pre-allocate it before hand (i.e. make a list of known length full of zeroes), this’ll greatly speed up the code.
Wow!! thanks a lot @solomondg I wasn’t expecting to get a full nice code!! Thank you again it works perfectly. I only added a break from the parent while to get data of a single cycle.