Comprehensive Autonomous Flight Examples

Complete code examples for autonomous drone programming in ADC Time Warp

Navigate to: Autonomous Flight Skills | Main Documentation

Basic Autonomous Flight Patterns

These fundamental patterns form the building blocks of autonomous flight programs.

Example 1: Simple Takeoff, Move, and Land

from codrone_edu.drone import *

drone = Drone()
drone.pair()

# Takeoff
drone.takeoff()

drone.set_pitch(30)
# Set forward power to 30%
drone.move(2)
# Move forward for 2 seconds

drone.hover(1)
# Stabilize for 1 second

# Land
drone.land()
drone.close()

Example 2: Square Pattern

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Fly in a square pattern
for i in range(4):
    drone.set_pitch(30)
    # Set forward power to 30%
    drone.move(2)
    # Move forward for 2 seconds
    drone.hover(0.5)
    # Stabilize for 0.5 seconds
    
    # Turn 90 degrees
    drone.turn_right(90, 0.5)
    # Turn right 90 degrees
    drone.hover(0.5)
    # Stabilize for 0.5 seconds

drone.land()
drone.close()

Example 3: Controlled Hovering and Stabilization

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Hover at current position
drone.hover(2)

# Move with controlled speed
drone.set_pitch(20)  # Lower power for precision
# Set forward power to 20%
drone.move(1.5)
# Move forward for 1.5 seconds
drone.set_pitch(0)   # Stop forward movement
drone.hover(1)       # Stabilize before next action
# Stabilize for 1 second

# Continue with next movement
drone.set_roll(20)
# Roll right at 20% power
drone.move(1)
# Continue movement for 1 second
drone.set_roll(0)
# Roll right at 0% power
drone.hover(1)
# Stabilize for 1 second

drone.land()
drone.close()

Sensor-Based Navigation

Use sensors to make intelligent decisions during autonomous flight.

Color Sensor Examples

Example 1: Detect Color and React

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

while True:
    color = drone.get_color_data()
    
    # Check if red is detected
    if color[0] > 100 and color[1] < 50 and color[2] < 50:  # Red
        drone.hover(1)
        # Stabilize for 1 second
        drone.set_roll(20)
        # Roll right at 20% power
        drone.move(0.5)
        # Continue movement for 0.5 seconds
        drone.set_roll(0)
        # Roll right at 0% power
        break
    
    # Continue moving forward
    drone.set_pitch(30)
    # Set forward power to 30%
    drone.move(0.1)
    # Move forward for 0.1 seconds
    drone.hover(0.1)
    # Stabilize for 0.1 seconds

drone.land()
drone.close()

Example 2: Follow Color-Based Path

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Follow path based on color markers
path_colors = ['red', 'green', 'blue']  # Define your path
current_target = 0

for target_color in path_colors:
    found = False
    while not found:
        color = drone.get_color_data()
        
        if target_color == 'red' and color[0] > 100:
            found = True
        elif target_color == 'green' and color[1] > 100:
            found = True
        elif target_color == 'blue' and color[2] > 100:
            found = True
        else:
            drone.set_pitch(30)
            # Set forward power to 30%
            drone.move(0.1)
            # Move forward for 0.1 seconds
            drone.hover(0.1)
            # Stabilize for 0.1 seconds
    
    # Perform action at color marker
    drone.hover(1)
    # Stabilize for 1 second
    drone.set_throttle(-10)
    # Move down at 10% power
    drone.move(0.3)
    # Continue movement for 0.3 seconds
    drone.set_throttle(0)
    # Move up at 0% power
    drone.hover(1)
    # Stabilize for 1 second

drone.land()
drone.close()

Distance Sensor Examples

Example 1: Stop at Specific Distance

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

target_distance = 20

while True:
    distance = drone.get_front_range()
    
    if distance <= target_distance:
        drone.hover(1)
        # Stabilize for 1 second
        break
    
    drone.set_pitch(20)
    # Set forward power to 20%
    drone.move(0.1)
    # Move forward for 0.1 seconds
    drone.hover(0.1)
    # Stabilize for 0.1 seconds

# Perform action at target distance
drone.set_roll(25)
# Roll right at 25% power
drone.move(0.5)
# Continue movement for 0.5 seconds
drone.set_roll(0)
# Roll right at 0% power
drone.hover(1)
# Stabilize for 1 second

drone.land()
drone.close()

Example 2: Maintain Distance from Wall

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Maintain 30cm distance from wall
target_distance = 30
tolerance = 5  # Allow 5cm variation

for i in range(10):  # Check 10 times
    distance = drone.get_front_range()
    
    if distance > target_distance + tolerance:
        # Too far, move forward
        drone.set_pitch(15)
        # Set forward power to 15%
        drone.move(0.2)
        # Move forward for 0.2 seconds
    elif distance < target_distance - tolerance:
        # Too close, move backward
        drone.set_pitch(-15)
        # Set backward power to 15%
        drone.move(0.2)
        # Continue movement for 0.2 seconds
    else:
        # Perfect distance
        drone.hover(0.5)
        # Stabilize for 0.5 seconds
    
    drone.hover(0.3)
    # Stabilize for 0.3 seconds

drone.land()
drone.close()

Example 3: Navigate Through Obstacle Course

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Navigate through obstacles using distance sensor
min_safe_distance = 25  # Minimum safe distance in cm

while True:
    front_distance = drone.get_front_range()
    left_distance = drone.get_left_range()
    right_distance = drone.get_right_range()
    
    # Check if path is clear ahead
    if front_distance > min_safe_distance:
        # Path clear, move forward
        drone.set_pitch(30)
        # Set forward power to 30%
        drone.move(0.2)
        # Move forward for 0.2 seconds
    elif left_distance > right_distance:
        # Turn left if more space
        drone.turn_left(45, 0.4)
        # Turn left 45 degrees
    else:
        # Turn right if more space
        drone.turn_right(45, 0.4)
        # Turn right 45 degrees
    
    drone.hover(0.2)
    # Stabilize for 0.2 seconds
    
    # Exit condition (e.g., after certain time or distance)

drone.land()
drone.close()

Gyro Sensor Examples

Example 1: Precise 90-Degree Turn

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Reset gyro to zero
drone.reset_gyro()

# Turn until gyro reads 90 degrees
target_angle = 90
tolerance = 5  # Allow 5 degree tolerance

while True:
    current_angle = drone.get_gyro_yaw()
    
    if abs(current_angle - target_angle) <= tolerance:
        drone.hover(1)
        # Stabilize for 1 second
        break
    
    # Turn right if angle is less than target
    if current_angle < target_angle:
        drone.set_yaw(30)
        drone.move(0.1)
        # Continue movement for 0.1 seconds
    else:
        drone.set_yaw(-30)
        drone.move(0.1)
        # Continue movement for 0.1 seconds
    
    drone.hover(0.1)
    # Stabilize for 0.1 seconds

# Continue with next movement
drone.set_pitch(30)
# Set forward power to 30%
drone.move(2)
# Move forward for 2 seconds
drone.land()
drone.close()

Example 2: Maintain Heading While Moving

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Reset gyro
drone.reset_gyro()
target_heading = 0  # Maintain original heading

for i in range(20):  # 20 iterations
    current_heading = drone.get_gyro_yaw()
    heading_error = current_heading - target_heading
    
    # Correct heading if drifted
    if abs(heading_error) > 5:  # More than 5 degrees off
        if heading_error > 0:
            # Drifted right, correct left
            drone.set_yaw(-10)
        else:
            # Drifted left, correct right
            drone.set_yaw(10)
    else:
        drone.set_yaw(0)
    
    drone.set_pitch(30)
    # Set forward power to 30%
    drone.move(0.1)
    # Move forward for 0.1 seconds
    drone.hover(0.1)
    # Stabilize for 0.1 seconds

drone.land()
drone.close()

Line Following

Follow lines on the ground using color sensor feedback.

Example 1: Basic Line Following

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Calibrate color sensor (adjust these values based on your field)
black_threshold = 50  # Below this is considered black
white_threshold = 200  # Above this is considered white

# Follow line for specified duration
max_iterations = 100
for i in range(max_iterations):
    color = drone.get_color_data()
    brightness = sum(color) / 3  # Average RGB values
    
    if brightness < black_threshold:
        # On black line, adjust left
        drone.set_roll(-15)
        # Roll left at 15% power
        drone.set_pitch(25)
        # Set forward power to 25%
    elif brightness > white_threshold:
        # Off line, adjust right
        drone.set_roll(15)
        # Roll right at 15% power
        drone.set_pitch(25)
        # Set forward power to 25%
    else:
        # On line, go straight
        drone.set_roll(0)
        # Roll right at 0% power
        drone.set_pitch(30)
        # Set forward power to 30%
    
    drone.move(0.1)
    # Continue movement for 0.1 seconds
    drone.hover(0.05)
    # Stabilize for 0.05 seconds

drone.land()
drone.close()

Example 2: Line Following with Stop Condition

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Follow line until red marker is detected
black_threshold = 50
red_detected = False

while not red_detected:
    color = drone.get_color_data()
    brightness = sum(color) / 3
    
    # Check for red marker (stop condition)
    if color[0] > 150 and color[1] < 80 and color[2] < 80:
        red_detected = True
        drone.hover(1)
        # Stabilize for 1 second
        break
    
    # Line following logic
    if brightness < black_threshold:
        drone.set_roll(-10)
        # Roll left at 10% power
        drone.set_pitch(20)
        # Set forward power to 20%
    else:
        drone.set_roll(10)
        # Roll right at 10% power
        drone.set_pitch(20)
        # Set forward power to 20%
    
    drone.move(0.1)
    # Continue movement for 0.1 seconds
    drone.hover(0.05)
    # Stabilize for 0.05 seconds

# Perform action at red marker
drone.set_throttle(-15)
# Move down at 15% power
drone.move(0.3)
# Continue movement for 0.3 seconds
drone.set_throttle(0)
# Move up at 0% power
drone.hover(1)
# Stabilize for 1 second

drone.land()
drone.close()

Obstacle Avoidance

Navigate around obstacles using distance sensors.

Example 1: Simple Obstacle Avoidance

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Navigate while avoiding obstacles
safe_distance = 30  # cm
max_iterations = 50

for i in range(max_iterations):
    front_dist = drone.get_front_range()
    
    if front_dist < safe_distance:
        # Obstacle detected, turn away
        left_dist = drone.get_left_range()
        right_dist = drone.get_right_range()
        
        if left_dist > right_dist:
            # More space on left, turn left
            drone.turn_left(90, 0.5)
            # Turn left 90 degrees
        else:
            # More space on right, turn right
            drone.turn_right(90, 0.5)
            # Turn right 90 degrees
        
        drone.hover(0.5)
        # Stabilize for 0.5 seconds
    else:
        # Path clear, move forward
        drone.set_pitch(30)
        # Set forward power to 30%
        drone.move(0.2)
        # Move forward for 0.2 seconds
        drone.hover(0.1)
        # Stabilize for 0.1 seconds

drone.land()
drone.close()

Example 2: Advanced Obstacle Avoidance with Recovery

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

safe_distance = 25
stuck_threshold = 3  # If stuck for 3 iterations
stuck_count = 0
last_position = None

for i in range(100):
    front_dist = drone.get_front_range()
    left_dist = drone.get_left_range()
    right_dist = drone.get_right_range()
    
    # Check if stuck (all directions blocked)
    if (front_dist < safe_distance and 
        left_dist < safe_distance and 
        right_dist < safe_distance):
        stuck_count += 1
        
        if stuck_count >= stuck_threshold:
            # Back up and try different direction
            drone.set_pitch(-20)
            # Set backward power to 20%
            drone.move(0.5)
            # Continue movement for 0.5 seconds
            drone.turn_left(180, 0.6)
            # Turn left 180 degrees
            drone.hover(1)
            # Stabilize for 1 second
            stuck_count = 0
        else:
            drone.hover(0.2)
            # Stabilize for 0.2 seconds
    else:
        stuck_count = 0
        
        # Normal obstacle avoidance
        if front_dist < safe_distance:
            if left_dist > right_dist:
                drone.turn_left(45, 0.4)
                # Turn left 45 degrees
            else:
                drone.turn_right(45, 0.4)
                # Turn right 45 degrees
            drone.hover(0.3)
            # Stabilize for 0.3 seconds
        else:
            drone.set_pitch(30)
            # Set forward power to 30%
            drone.move(0.2)
            # Move forward for 0.2 seconds
            drone.hover(0.1)
            # Stabilize for 0.1 seconds

drone.land()
drone.close()

Precision Positioning

Use multiple sensors for accurate positioning and alignment.

Example 1: Precise Landing on Target

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Navigate to target using distance and color sensors
target_color = 'green'  # Target marker color
target_distance = 15  # cm above target

# Approach target
while True:
    color = drone.get_color_data()
    distance = drone.get_front_range()
    altitude = drone.get_height()  # If available
    
    # Check if target color is detected
    if (color[1] > 100 and  # Green detected
        distance < 30 and  # Close to target
        altitude < 50):    # Low altitude
        break
    
    # Adjust position
    if distance > 30:
        drone.set_pitch(20)
        # Set forward power to 20%
        drone.move(0.2)
        # Move forward for 0.2 seconds
    elif altitude > 50:
        drone.set_throttle(-15)
        # Move down at 15% power
        drone.move(0.2)
        # Continue movement for 0.2 seconds
    else:
        drone.set_pitch(10)
        # Set forward power to 10%
        drone.move(0.1)
        # Move forward for 0.1 seconds
    
    drone.hover(0.1)
    # Stabilize for 0.1 seconds

# Fine-tune position
drone.hover(1)
# Stabilize for 1 second

# Descend slowly to target
for i in range(5):
    drone.set_throttle(-10)
    # Move down at 10% power
    drone.move(0.2)
    # Continue movement for 0.2 seconds
    drone.hover(0.3)
    # Stabilize for 0.3 seconds

drone.land()
drone.close()

Example 2: Align with Object Using Multiple Sensors

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Align precisely with object using distance sensors
target_distance = 20  # cm
tolerance = 2  # cm tolerance
max_iterations = 20

for i in range(max_iterations):
    front = drone.get_front_range()
    left = drone.get_left_range()
    right = drone.get_right_range()
    
    # Check if aligned (front distance correct and sides equal)
    front_ok = abs(front - target_distance) <= tolerance
    sides_equal = abs(left - right) <= tolerance
    
    if front_ok and sides_equal:
        drone.hover(1)
        # Stabilize for 1 second
        break
    
    # Adjust position
    if not front_ok:
        if front > target_distance:
            drone.set_pitch(15)
            # Set forward power to 15%
            drone.move(0.1)
            # Move forward for 0.1 seconds
        else:
            drone.set_pitch(-15)
            # Set backward power to 15%
            drone.move(0.1)
            # Continue movement for 0.1 seconds
    
    if not sides_equal:
        if left > right:
            drone.set_roll(-10)
            # Roll left at 10% power
            drone.move(0.1)
            # Continue movement for 0.1 seconds
        else:
            drone.set_roll(10)
            # Roll right at 10% power
            drone.move(0.1)
            # Continue movement for 0.1 seconds
    
    drone.hover(0.2)
    # Stabilize for 0.2 seconds

# Perform action when aligned
drone.set_throttle(-10)
# Move down at 10% power
drone.move(0.3)
# Continue movement for 0.3 seconds
drone.set_throttle(0)
# Move up at 0% power
drone.hover(1)
# Stabilize for 1 second

drone.land()
drone.close()

Error Recovery

Implement robust error handling and recovery mechanisms.

Example 1: Retry Failed Actions

from codrone_edu.drone import *

drone = Drone()
drone.pair()

def attempt_action(max_attempts=3):
    """Attempt an action with retry logic"""
    for attempt in range(max_attempts):
        try:
            drone.takeoff()
            drone.hover(1)
            # Stabilize for 1 second
            
            # Perform main action
            drone.set_pitch(30)
            # Set forward power to 30%
            drone.move(2)
            # Move forward for 2 seconds
            drone.hover(1)
            # Stabilize for 1 second
            
            # Verify success (e.g., check sensor reading)
            distance = drone.get_front_range()
            if distance < 30:  # Success condition
                return True
            
            # If not successful, try recovery
            drone.set_pitch(-20)
            # Set backward power to 20%
            drone.move(0.5)
            # Continue movement for 0.5 seconds
            drone.hover(1)
            # Stabilize for 1 second
            
        except Exception as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            if attempt < max_attempts - 1:
                # Wait before retry
                drone.hover(2)
                # Stabilize for 2 seconds
                continue
            else:
                return False
    
    return False

# Execute with retry
if attempt_action():
    print("Action successful!")
    drone.land()
else:
    print("Action failed after all attempts")
    drone.land()

drone.close()

Example 2: Safe Mode on Error

from codrone_edu.drone import *

drone = Drone()
drone.pair()

def safe_landing():
    """Emergency safe landing procedure"""
    try:
        drone.hover(1)
        # Stabilize for 1 second
        drone.set_pitch(0)
        # Stop forward/backward movement
        drone.set_roll(0)
        # Roll right at 0% power
        drone.set_yaw(0)
        drone.set_throttle(-20)
        # Move down at 20% power
        drone.move(1)
        # Continue movement for 1 second
        drone.land()
    except:
        # If landing fails, try to stop all movement
        drone.set_pitch(0)
        # Stop forward/backward movement
        drone.set_roll(0)
        # Roll right at 0% power
        drone.set_yaw(0)
        drone.set_throttle(0)
        # Move up at 0% power

try:
    drone.takeoff()
    
    # Main autonomous sequence
    for i in range(10):
        # Check for errors
        try:
            distance = drone.get_front_range()
            
            # Safety check: if too close to obstacle
            if distance < 10:
                raise Exception("Too close to obstacle!")
            
            # Normal operation
            drone.set_pitch(30)
            # Set forward power to 30%
            drone.move(0.2)
            # Move forward for 0.2 seconds
            drone.hover(0.1)
            # Stabilize for 0.1 seconds
            
        except Exception as e:
            print(f"Error detected: {e}")
            safe_landing()
            break
    
    # Normal landing if no errors
    drone.land()
    
except Exception as e:
    print(f"Critical error: {e}")
    safe_landing()

drone.close()

Multi-Sensor Fusion

Combine multiple sensors for more reliable navigation.

Example 1: Color + Distance Navigation

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()

# Navigate using both color and distance sensors
target_color = 'blue'
target_distance = 25  # cm

while True:
    color = drone.get_color_data()
    distance = drone.get_front_range()
    
    # Check if both conditions met
    color_match = color[2] > 100  # Blue detected
    distance_ok = 20 <= distance <= 30
    
    if color_match and distance_ok:
        drone.hover(1)
        # Stabilize for 1 second
        break
    
    # Adjust based on sensors
    if not color_match:
        # Search for color by moving forward
        drone.set_pitch(25)
        # Set forward power to 25%
        drone.move(0.2)
        # Move forward for 0.2 seconds
    elif not distance_ok:
        if distance > 30:
            drone.set_pitch(20)
            # Set forward power to 20%
            drone.move(0.1)
            # Move forward for 0.1 seconds
        else:
            drone.set_pitch(-20)
            # Set backward power to 20%
            drone.move(0.1)
            # Continue movement for 0.1 seconds
    
    drone.hover(0.1)
    # Stabilize for 0.1 seconds

# Perform action
drone.set_roll(20)
# Roll right at 20% power
drone.move(0.5)
# Continue movement for 0.5 seconds
drone.land()
drone.close()

Example 2: Complete Multi-Sensor Navigation

from codrone_edu.drone import *

drone = Drone()
drone.pair()

drone.takeoff()
drone.reset_gyro()

# Multi-sensor navigation system
def navigate_to_target(target_color, target_distance, max_time=30):
    """Navigate using color, distance, and gyro sensors"""
    start_time = time.time()
    
    while time.time() - start_time < max_time:
        # Get all sensor readings
        color = drone.get_color_data()
        front_dist = drone.get_front_range()
        heading = drone.get_gyro_yaw()
        
        # Check if target reached
        color_match = False
        if target_color == 'red':
            color_match = color[0] > 100 and color[1] < 80
        elif target_color == 'green':
            color_match = color[1] > 100 and color[0] < 80
        elif target_color == 'blue':
            color_match = color[2] > 100 and color[0] < 80
        
        distance_ok = abs(front_dist - target_distance) <= 5
        heading_ok = abs(heading) <= 10  # Maintain straight heading
        
        if color_match and distance_ok and heading_ok:
            drone.hover(1)
            # Stabilize for 1 second
            return True
        
        # Multi-sensor decision making
        if not color_match:
            # Search for color, maintain heading
            if abs(heading) > 10:
                # Correct heading first
                if heading > 0:
                    drone.set_yaw(-10)
                else:
                    drone.set_yaw(10)
            else:
                drone.set_pitch(25)
                # Set forward power to 25%
                drone.move(0.2)
                # Move forward for 0.2 seconds
        
        elif not distance_ok:
            # Adjust distance
            if front_dist > target_distance:
                drone.set_pitch(20)
                # Set forward power to 20%
                drone.move(0.1)
                # Move forward for 0.1 seconds
            else:
                drone.set_pitch(-20)
                # Set backward power to 20%
                drone.move(0.1)
                # Continue movement for 0.1 seconds
        
        elif not heading_ok:
            # Correct heading
            if heading > 0:
                drone.set_yaw(-15)
            else:
                drone.set_yaw(15)
            drone.move(0.1)
            # Continue movement for 0.1 seconds
        
        drone.hover(0.1)
        # Stabilize for 0.1 seconds
    
    return False

# Use the navigation function
import time
if navigate_to_target('green', 25):
    print("Target reached!")
    # Perform action
    drone.set_throttle(-15)
    # Move down at 15% power
    drone.move(0.3)
    # Continue movement for 0.3 seconds
    drone.hover(1)
    # Stabilize for 1 second

drone.land()
drone.close()

Complete Mission Examples

Full autonomous mission sequences combining multiple techniques.

Example 1: Complete Navigation Mission

from codrone_edu.drone import *
import time

drone = Drone()
drone.pair()

def complete_mission():
    """Complete autonomous mission sequence"""
    
    # Phase 1: Takeoff and initial positioning
    drone.takeoff()
    drone.hover(2)  # Stabilize
    # Stabilize for 2 seconds
    drone.reset_gyro()
    
    # Phase 2: Navigate to first waypoint using line following
    print("Phase 2: Following line to waypoint 1")
    for i in range(50):
        color = drone.get_color_data()
        brightness = sum(color) / 3
        
        if brightness < 50:  # On line
            drone.set_roll(-10)
            # Roll left at 10% power
            drone.set_pitch(25)
            # Set forward power to 25%
        else:
            drone.set_roll(10)
            # Roll right at 10% power
            drone.set_pitch(25)
            # Set forward power to 25%
        
        # Check for red marker (waypoint)
        if color[0] > 150:
            drone.hover(1)
            # Stabilize for 1 second
            break
        
        drone.move(0.1)
        # Continue movement for 0.1 seconds
        drone.hover(0.05)
        # Stabilize for 0.05 seconds
    
    # Phase 3: Navigate to object using distance sensor
    print("Phase 3: Approaching object")
    while True:
        distance = drone.get_front_range()
        
        if distance <= 20:
            drone.hover(1)
            # Stabilize for 1 second
            break
        
        drone.set_pitch(25)
        # Set forward power to 25%
        drone.move(0.2)
        # Move forward for 0.2 seconds
        drone.hover(0.1)
        # Stabilize for 0.1 seconds
    
    # Phase 4: Perform action (e.g., push/pull)
    print("Phase 4: Performing action")
    drone.set_roll(25)
    # Roll right at 25% power
    drone.move(0.5)
    # Continue movement for 0.5 seconds
    drone.hover(1)
    # Stabilize for 1 second
    drone.set_roll(-25)
    # Roll left at 25% power
    drone.move(0.5)
    # Continue movement for 0.5 seconds
    drone.hover(1)
    # Stabilize for 1 second
    
    # Phase 5: Return to start using gyro
    print("Phase 5: Returning to start")
    drone.turn_right(180, 0.6)
    # Turn right 180 degrees
    drone.hover(1)
    # Stabilize for 1 second
    
    # Follow line back
    for i in range(50):
        color = drone.get_color_data()
        brightness = sum(color) / 3
        
        if brightness < 50:
            drone.set_roll(10)
            # Roll right at 10% power
            drone.set_pitch(25)
            # Set forward power to 25%
        else:
            drone.set_roll(-10)
            # Roll left at 10% power
            drone.set_pitch(25)
            # Set forward power to 25%
        
        # Check for start marker (green)
        if color[1] > 150:
            drone.hover(1)
            # Stabilize for 1 second
            break
        
        drone.move(0.1)
        # Continue movement for 0.1 seconds
        drone.hover(0.05)
        # Stabilize for 0.05 seconds
    
    # Phase 6: Land
    print("Phase 6: Landing")
    drone.land()

# Execute mission
try:
    complete_mission()
except Exception as e:
    print(f"Mission error: {e}")
    drone.land()

drone.close()

Example 2: Multi-Waypoint Mission with Error Recovery

from codrone_edu.drone import *
import time

drone = Drone()
drone.pair()

def navigate_to_waypoint(target_color, max_time=15):
    """Navigate to a waypoint defined by color"""
    start_time = time.time()
    
    while time.time() - start_time < max_time:
        color = drone.get_color_data()
        distance = drone.get_front_range()
        
        # Check for target color
        found = False
        if target_color == 'red' and color[0] > 150:
            found = True
        elif target_color == 'green' and color[1] > 150:
            found = True
        elif target_color == 'blue' and color[2] > 150:
            found = True
        
        if found and distance < 30:
            drone.hover(1)
            # Stabilize for 1 second
            return True
        
        # Navigate toward waypoint
        if distance > 30:
            drone.set_pitch(25)
            # Set forward power to 25%
            drone.move(0.2)
            # Move forward for 0.2 seconds
        elif distance < 20:
            drone.set_pitch(-20)
            # Set backward power to 20%
            drone.move(0.2)
            # Continue movement for 0.2 seconds
        else:
            drone.set_pitch(20)
            # Set forward power to 20%
            drone.move(0.2)
            # Move forward for 0.2 seconds
        
        drone.hover(0.1)
        # Stabilize for 0.1 seconds
    
    return False

def complete_multi_waypoint_mission():
    """Complete mission visiting multiple waypoints"""
    waypoints = ['red', 'green', 'blue']  # Define waypoint sequence
    
    drone.takeoff()
    drone.hover(2)
    # Stabilize for 2 seconds
    drone.reset_gyro()
    
    for i, waypoint in enumerate(waypoints):
        print(f"Navigating to waypoint {i+1}: {waypoint}")
        
        success = navigate_to_waypoint(waypoint)
        
        if success:
            print(f"Waypoint {i+1} reached!")
            # Perform action at waypoint
            drone.set_throttle(-10)
            # Move down at 10% power
            drone.move(0.3)
            # Continue movement for 0.3 seconds
            drone.set_throttle(0)
            # Move up at 0% power
            drone.hover(1)
            # Stabilize for 1 second
        else:
            print(f"Failed to reach waypoint {i+1}")
            # Error recovery: try to continue
            drone.hover(2)
            # Stabilize for 2 seconds
            continue
    
    # Return to start
    print("Returning to start")
    drone.turn_right(180, 0.6)
    # Turn right 180 degrees
    drone.hover(1)
    # Stabilize for 1 second
    
    # Navigate back (simplified)
    drone.set_pitch(30)
    # Set forward power to 30%
    drone.move(3)
    # Move forward for 3 seconds
    drone.hover(1)
    # Stabilize for 1 second
    
    drone.land()

# Execute with error handling
try:
    complete_multi_waypoint_mission()
except Exception as e:
    print(f"Mission failed: {e}")
    try:
        drone.land()
    except:
        pass

drone.close()

✅ Best Practices for Autonomous Missions

  • Always test each phase separately before combining
  • Calibrate sensors before every run
  • Implement error recovery for critical sections
  • Use hover() between actions for stability
  • Test in various lighting conditions
  • Document sensor values that work consistently
  • Have backup strategies for common failures