2013-01-18 44 views
0

比方說,我有兩個功能:並行而在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兩次;一次使用正位置,一個使用負位置)

雖然'control'循環正在迭代,但我想要一個通過調用getMotorPositionnd來分離while循環以便以某個頻率提取數據。然後我會在這個循環上設置一個定時器,讓我設置採樣頻率。

在LabView中(電機控制器提供了一個DLL來掛鉤)我用'parallel'while循環來實現這一點。我以前從來沒有用過parallel和python做過什麼,也不確定哪個是最有說服力的方向。

+1

的'threading'和'multiprocessing'模塊將具有特別的意義嗎前進。 –

+0

你也可以使用[twisted](http://twistedmatrix.com/trac/);它是爲網絡而構建的,但它也可以進行任意調度 – Eevee

回答

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)