Python threading.Timer返回值

时间:2018-05-02 08:19:32

标签: python recursion

我在Python中使用threading.Timer()来集成陀螺仪值。 从leftTurn()调用turn函数。现在我想在达到最大角度时返回True to leftTurn()。我的问题是turn()内的递归。是否有可能让leftTurn()知道转弯何时完成?

class navigation():

    def __init__(self):
        self.mpu = mpu6050(0x68)

    def getOffset(self):
        gyro_data = self.mpu.get_gyro_data()
        offset = abs(gyro_data['z'])
        return offset

    def turn(self, angle,offset,maxAngle):
        gyro_data = self.mpu.get_gyro_data()    
        gyroZ = abs(gyro_data['z'])
        angle = abs(angle + (gyroZ-offset)*0.01)

        if angle < maxAngle:        
            threading.Timer(0.001, self.turn, [angle,offset,maxAngle]).start()
        else:
            motor().stop()
            return True





class motor():

    ...

    def leftTurn(self, maxAngle):
        self.left()
        offset = navigation().getOffset()
        navigation().turn(0,offset,maxAngle)

2 个答案:

答案 0 :(得分:1)

class navigation():

def __init__(self):
    self.mpu = mpu6050(0x68)

def getOffset(self):
    gyro_data = self.mpu.get_gyro_data()
    offset = abs(gyro_data['z'])
    return offset

def turn(self, angle,offset,maxAngle):
    gyro_data = self.mpu.get_gyro_data()    
    gyroZ = abs(gyro_data['z'])
    angle = abs(angle + (gyroZ-offset)*0.01)

    if angle < maxAngle:        
        thread = threading.Timer(0.001, self.turn, [angle,offset,maxAngle])
        thread.start()  # Start the thread
        thread.join()  # >ait for the thread to end
        return True
    else:
        motor().stop()
        return True

因为您不需要turn的返回值,并且您只想知道线程已经结束,您可以使用Thread.join()等待线程结束。

  

Timer是Thread

的子类

答案 1 :(得分:0)

与往常一样,您应该尝试用循环替换递归。在这种情况下,我会这样做:

def turn(self, angle, offset, maxAngle):
    while angle < maxAngle:
        threading.wait(0.001)
        gyro_data = self.mpu.get_gyro_data()    
        gyroZ = abs(gyro_data['z'])
        angle = abs(angle + (gyroZ-offset)*0.01)
    else:
        motor().stop()
        return True

我想知道为什么你在原始代码中使用threading,无论如何你真的需要使用它。