gpt4 book ai didi

Python threading.Timer返回值

转载 作者:行者123 更新时间:2023-12-01 09:28:50 27 4
gpt4 key购买 nike

我正在Python中使用threading.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()等待线程结束。

Timer is a subclass of Thread

关于Python threading.Timer返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50130038/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com