I want to run some physical devices in a time dependent manner, my program needs to synchronize with an external process, so accuracy is important. The code I need to run is quite simple, but I will have to wait in between, my first approach would be:
import serial
import time
device = serial.Serial('COM3')
while True:
device.write(command)
time.sleep(30)
However I want one loop to take 30 seconds excluding the code executing, the best way I can think of would be something like:
start = time.time()
cycle = 1
while True:
device.write(command)
while start + cycle*30 < time.time():
sleep(0.5)
But this doesn't feel like a great way to do this. Is there a better way?