Matthias
Matthias

Reputation: 471

Python threading.Timer return value

I'm using the threading.Timer() in Python for integration of Gyroscope values. The turn function is called from leftTurn(). Now I want to return a True to leftTurn() when the maximum angle is reached. My problem is the recursion inside turn(). Is it somehow possible to let leftTurn() know when the turn is completed?

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)

Upvotes: 1

Views: 1260

Answers (2)

Yassine Faris
Yassine Faris

Reputation: 991

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

Because you don't need the return value of turn and you just want to know of the thread have ended you can use Thread.join() to wait for a thread to end.

Timer is a subclass of Thread

Upvotes: 1

Konrad Talik
Konrad Talik

Reputation: 916

As always, you should try to replace recursion with loop. In this case I would do it like this:

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

I wonder why you use threading in your original code and whether you actually need to use it anyway, however.

Upvotes: 0

Related Questions