Python 线程.计时器返回值



我正在使用线程。Python 中的 Timer(( 用于集成陀螺仪值。 turn 函数从 leftTurn(( 调用。现在我想在达到最大角度时向 leftTurn(( 返回一个 True。我的问题是 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)
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(( 等待线程结束。

计时器是线程的子类

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

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,以及你是否真的需要使用它。

最新更新