Параллельные циклы while в python для управления двигателем и сбора данных
Допустим, у меня есть две функции:
def moveMotorToPosition(position,velocity)
#moves motor to a particular position
#does not terminate until motor is at that position
а также
def getMotorPosition()
#retrieves the motor position at any point in time
На практике то, что я хочу, чтобы двигатель вращался взад и вперед (с помощью цикла, который дважды вызывает moveMotorToPosition; один раз с положительной позицией и один с отрицательной позицией)
Пока этот "контрольный" цикл повторяется, я хочу, чтобы отдельный цикл while извлекал данные с определенной частотой, вызывая getMotorPositionnd. Затем я установил бы таймер в этом цикле, который позволил бы мне установить частоту дискретизации.
В LabView (контроллер мотора поставляет DLL для подключения) я достигаю этого с помощью "параллельных" циклов while. Я никогда не делал ничего с параллелью и питоном раньше, и не совсем уверен, какое направление является наиболее убедительным.
1 ответ
Чтобы указать вам немного ближе к тому, что звучит так, как вы хотите:
import threading
def poll_position(fobj, seconds=0.5):
"""Call once to repeatedly get statistics every N seconds."""
position = getMotorPosition()
# Do something with the position.
# Could store it in a (global) variable or log it to file.
print position
fobj.write(position + '\n')
# Set a timer to run this function again.
t = threading.Timer(seconds, poll_position, args=[fobj, seconds])
t.daemon = True
t.start()
def control_loop(positions, velocity):
"""Repeatedly moves the motor through a list of positions at a given velocity."""
while True:
for position in positions:
moveMotorToPosition(position, velocity)
if __name__ == '__main__':
# Start the position gathering thread.
poll_position()
# Define `position` and `velocity` as it relates to `moveMotorToPosition()`.
control_loop([first_position, second_position], velocity)