Search code examples
pythontello-drone

How to make a tello drone fly indefinitely while something is happening?


I am writing a tello drone control program. I need to make the drone fly while a key is pressed on the keyboard otherwise it stops. Here is my code:

class Keybord_Recognition(QtCore.QObject):

    def __init__(self, drone):
        super(Keybord_Recognition, self).__init__()
        self.drone = drone

    def key_recog(self, k):
        if k.event_type == 'down':
            if k.name == 'w':
                self.drone.move_forward(30)

            elif k.name == 's':
                self.drone.move_back(30)

            elif k.name == 'a':
                self.drone.move_left(30)

            elif k.name == 'd':
                self.drone.move_right(30)

            elif k.name == 'z':
                self.drone.move_up(30)

            elif k.name == 'x':
                self.drone.move_down(30)

    def run(self):
        keyboard.hook(self.key_recog)

    def stop(self):
        keyboard.unhook(self.key_recog)

How can I do what I need?


Solution

  • You will need a while loop to constantly check different directions, moreover there is no need to add another position as static-fly (no move). However if you want to break the while loop for any reason simply add an except KeyboardInterrupt: at the end.

    more specific change your code to this:

    try:
         while True:
               if k.name == 'w':
                  self.drone.move_forward(30)
        
                elif k.name == 's':
                    self.drone.move_back(30)
        
                elif k.name == 'a':
                    self.drone.move_left(30)
        
                elif k.name == 'd':
                    self.drone.move_right(30)
        
                elif k.name == 'z':
                    self.drone.move_up(30)
        
                elif k.name == 'x':
                    self.drone.move_down(30)
    
    except KeyboardInterrupt:
        print("Press Ctrl-C to exit")
        pass