0

假设我有两个功能:

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 循环来实现这一点。我以前从未使用过 parallel 和 python 做过任何事情,并且不确定哪个是最引人注目的方向。

4

1 回答 1

2

为了让你更接近听起来你想要的东西:

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)
于 2013-01-18T00:58:33.283 回答