Setup Development Environment
Before writing drone AI code, you need a proper development environment. This lesson walks you through installing Python tools, connecting to a simulator, and running your first autonomous flight.
Environment Architecture
Sponsored
Installation Guide
# Step 1: Create virtual environment
python -m venv drone-env
source drone-env/bin/activate # Linux/Mac
# drone-env\Scripts\activate # Windows
# Step 2: Install DroneKit
pip install dronekit
pip install dronekit-sitl
# Step 3: Install MAVProxy (for command-line monitoring)
pip install pymavlink mavproxy
# Step 4: Install additional libraries
pip install numpy matplotlib
# Step 5: Start SITL simulator
dronekit-sitl start --model quad --instance 0
Connecting to SITL
python
from dronekit import connect, VehicleMode, LocationGlobalRelative
# Connect to the simulator
print("Connecting to simulator...")
vehicle = connect('tcp:127.0.0.1:5762', wait_ready=True)
# Check connection
print(f"Connected to vehicle: {vehicle.version}")
print(f"Mode: {vehicle.mode.name}")
print(f"Armed: {vehicle.armed}")
print(f"GPS: {vehicle.gps_0}")
# Get vehicle parameters
print(f"\nVehicle Parameters:")
print(f" Battery voltage: {vehicle.battery.voltage}V")
print(f" Battery level: {vehicle.battery.level}")
print(f" Ground speed: {vehicle.groundspeed}")
print(f" Altitude: {vehicle.location.global_relative_frame.alt}")
First Autonomous Flight
Sponsored
python
from dronekit import connect, VehicleMode, LocationGlobalRelative
def arm_and_takeoff(vehicle, target_alt):
"""Arm the vehicle and fly to target altitude"""
print(f"Arming and taking off to {target_alt}m...")
# Set mode to GUIDED
vehicle.mode = VehicleMode("GUIDED")
while vehicle.mode.name != "GUIDED":
time.sleep(0.5)
print(f" Mode: {vehicle.mode.name}")
# Arm the vehicle
vehicle.armed = True
while not vehicle.armed:
time.sleep(0.5)
print(f" Armed: {vehicle.armed}")
# Takeoff
vehicle.simple_takeoff(target_alt)
# Wait to reach target altitude
while True:
alt = vehicle.location.global_relative_frame.alt
print(f" Altitude: {alt:.1f}m")
if alt >= target_alt * 0.95:
break
time.sleep(1)
print(f" Reached target altitude: {alt:.1f}m")
def fly_square(vehicle, side_length=10, altitude=10):
"""Fly a square pattern"""
print(f"\nFlying {side_length}m square at {altitude}m...")
# Get current position
home = vehicle.location.global_relative_frame
# Calculate 4 corners
corners = []
for i in range(4):
angle = math.radians(i * 90)
lat = home.lat + (side_length / 111320) * math.cos(angle)
lon = home.lon + (side_length / (111320 * math.cos(math.radians(home.lat)))) * math.sin(angle)
corners.append(LocationGlobalRelative(lat, lon, altitude))
# Fly to each corner
for i, corner in enumerate(corners):
print(f" Flying to corner {i+1}...")
vehicle.simple_goto(corner)
time.sleep(8) # Wait to reach corner
print(" Square complete!")
def land(vehicle):
"""Land the vehicle"""
print("Landing...")
vehicle.mode = VehicleMode("LAND")
while vehicle.location.global_relative_frame.alt > 0.5:
time.sleep(1)
print("Landed!")
vehicle.armed = False
vehicle.close()
# Main program
vehicle = connect('tcp:127.0.0.1:5762', wait_ready=True)
arm_and_takeoff(vehicle, 10)
time.sleep(2)
fly_square(vehicle, side_length=10, altitude=10)
time.sleep(2)
land(vehicle)
MAVProxy Ground Station
python
"""
MAVProxy commands for monitoring:
1. Start MAVProxy:
mavproxy.py --master=tcp:127.0.0.1:5762
2. Useful commands:
mode GUIDED # Set flight mode
arm throttle # Arm the motors
takeoff 10 # Take off to 10 meters
wp load mission.txt # Load waypoint mission
wp list # List loaded waypoints
status # Show vehicle status
param show # Show parameters
map # Open map display
"""
# Programmatic MAVProxy commands via DroneKit
def monitor_vehicle(vehicle):
"""Print vehicle status every second"""
print("\n=== Vehicle Monitor ===")
for i in range(10):
print(f"\r Mode: {vehicle.mode.name:10s} "
f"Alt: {vehicle.location.global_relative_frame.alt:6.1f}m "
f"Speed: {vehicle.groundspeed:5.1f}m/s "
f"Batt: {vehicle.battery.voltage}V", end="")
time.sleep(1)
print()
Using AirSim for Visual Simulation
python
"""
AirSim Setup (Optional â for visual simulation):
1. Install AirSim:
pip install airsim
2. Download AirSim environment:
https://github.com/microsoft/AirSim/releases
3. Python AirSim example:
"""
def airsim_example():
"""Connect to AirSim and read drone state"""
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
# Take off
client.takeoffAsync().join()
print("AirSim: Drone took off")
# Get state
state = client.getMultirotorState()
print(f" Position: {state.kinematics_estimated.position}")
print(f" Velocity: {state.kinematics_estimated.linear_velocity}")
# Move to a point
print(" Moving to point (10, 10, -5)...")
client.moveToPositionAsync(10, 10, -5, 5).join()
# Take a photo
responses = client.simGetImages([
airsim.ImageRequest("0", airsim.ImageType.Scene)
])
print(f" Captured image: {len(responses[0].image_data_uint8)} bytes")
# Land
client.landAsync().join()
client.enableApiControl(False)
print(" AirSim: Landed and released control")
Project Structure Template
python
"""
Recommended project structure for drone AI projects:
drone_ai_project/
|-- config/
| |-- params.yaml # Vehicle parameters
| |-- missions/ # Waypoint mission files
|-- src/
| |-- __init__.py
| |-- connection.py # Vehicle connection logic
| |-- navigation.py # Waypoint navigation
| |-- perception.py # Computer vision
| |-- controller.py # PID / control logic
|-- tests/
| |-- test_navigation.py
| |-- test_perception.py
|-- scripts/
| |-- run_mission.py # Main mission runner
|-- requirements.txt
|-- README.md
"""
# requirements.txt content
requirements = [
"dronekit>=2.9.2",
"dronekit-sitl>=3.3.0",
"pymavlink>=2.4.0",
"mavproxy>=1.8.0",
"numpy>=1.24.0",
"opencv-python>=4.8.0",
"matplotlib>=3.7.0",
]
print("requirements.txt:")
for req in requirements:
print(f" {req}")
Connection Helper Module
Advertisement
python
from dronekit import connect
class DroneConnection:
def __init__(self, connection_string='tcp:127.0.0.1:5762', baud=57600):
self.connection_string = connection_string
self.baud = baud
self.vehicle = None
def connect(self, timeout=30):
print(f"Connecting to {self.connection_string}...")
try:
self.vehicle = connect(
self.connection_string,
baud=self.baud,
wait_ready=True,
timeout=timeout
)
print(f"Connected! Version: {self.vehicle.version}")
return self.vehicle
except Exception as e:
print(f"Connection failed: {e}")
sys.exit(1)
def wait_for_gps(self, min_satellites=10, timeout=60):
print("Waiting for GPS lock...")
start = time.time()
while time.time() - start < timeout:
gps = self.vehicle.gps_0
if gps and gps.satellites_visible >= min_satellites:
print(f" GPS lock: {gps.satellites_visible} satellites")
return True
time.sleep(1)
print(" GPS lock timeout!")
return False
def print_status(self):
v = self.vehicle
print(f"\n=== Vehicle Status ===")
print(f" Version: {v.version}")
print(f" Mode: {v.mode.name}")
print(f" Armed: {v.armed}")
print(f" Battery: {v.battery.voltage}V ({v.battery.level}%)")
print(f" GPS: {v.gps_0.satellites_visible} sats")
print(f" Alt: {v.location.global_relative_frame.alt:.1f}m")
def close(self):
if self.vehicle:
self.vehicle.close()
print("Connection closed")
# Usage
drone = DroneConnection()
vehicle = drone.connect()
drone.wait_for_gps()
drone.print_status()
# ... your mission code here ...
drone.close()
Hands-On Project: Build a Complete Mission Script
python
from dronekit import connect, VehicleMode, LocationGlobalRelative
class AutonomousMission:
def __init__(self, connection='tcp:127.0.0.1:5762'):
self.vehicle = None
self.connection = connection
def connect(self):
print(f"Connecting to {self.connection}...")
self.vehicle = connect(self.connection, wait_ready=True)
print(f"Connected! Mode: {self.vehicle.mode.name}")
def arm_and_takeoff(self, alt=10):
print(f"Taking off to {alt}m...")
self.vehicle.mode = VehicleMode("GUIDED")
time.sleep(1)
self.vehicle.armed = True
while not self.vehicle.armed:
time.sleep(0.5)
self.vehicle.simple_takeoff(alt)
while self.vehicle.location.global_relative_frame.alt < alt * 0.95:
print(f" Alt: {self.vehicle.location.global_relative_frame.alt:.1f}m")
time.sleep(1)
print(f" Reached {alt}m!")
def goto_point(self, lat, lon, alt):
self.vehicle.simple_goto(LocationGlobalRelative(lat, lon, alt))
def monitor(self, duration=5):
for _ in range(duration):
pos = self.vehicle.location.global_relative_frame
print(f" Pos: ({pos.lat:.6f}, {pos.lon:.6f}, {pos.alt:.1f}m)")
time.sleep(1)
def land(self):
print("Landing...")
self.vehicle.mode = VehicleMode("LAND")
while self.vehicle.location.global_relative_frame.alt > 1:
time.sleep(1)
self.vehicle.armed = False
print("Landed!")
def run(self):
self.connect()
self.arm_and_takeoff(10)
self.monitor(3)
self.land()
self.vehicle.close()
# Execute: mission = AutonomousMission()
# mission.run()
Summary
- DroneKit-Python is the primary API for drone control via MAVLink
- SITL provides a simulated flight environment for testing
- MAVProxy offers command-line monitoring and control
- AirSim adds visual simulation with Unreal Engine (optional)
- Always test in simulation first before flying real hardware
- Use the connection helper pattern for reliable vehicle connections
- The development stack: Python code -> DroneKit -> MAVLink -> SITL/Firmware
You now have a complete foundation for building drone AI applications. Start with SITL simulation, master the APIs, then move to real hardware!