Now that preflight checks are complete, let’s add in some flight movements! We can use our front range sensor to detect if we are approaching an object. Let’s add some code in our else case so that we fly forward until our drone spots an obstacle. Since we don’t know how long it will take for our drone to find an obstacle, we will use an infinite while loop and use break
once we spot something. We will also use our move
command in short bursts so that we can check for walls more frequently!
First, we create an infinite while loop, since we do not know how long it will take to find an obstacle.
while True:
Next, we will add in our flight movement and conditional check for obstacle detection. Since this while loop is continuously running, if we make our move command execute for a short amount of time, then our conditional check for an obstacle will run more frequently. You could think of this as your drone is closing its eyes for the amount of time you give it a move command. The shorter the drone has its eyes closed, the more frequently it can open its eyes to check for an obstacle.
drone.set_pitch(30)
drone.move(0.2)
if drone.detect_wall(distance):
print("Object detected")
break
We also add a break
at the end of our conditional check to make sure we exit that infinite while loop we made!
Lastly, all we need to do is print a message indicating that an obstacle was found and send the drone a land command.
Here is the completed code for this lesson:
from codrone_edu.drone import *
drone = Drone()
drone.pair()
distance = 50
if drone.detect_wall(distance):
print("Takeoff area is not clear. Shutting down")
else:
drone.takeoff()
while True:
drone.set_pitch(30)
drone.move(0.2)
if drone.detect_wall(distance):
print("Object detected")
break
print("Obstacle detected.. Landing!")
drone.land()
drone.close()