Setup Development Environment
Drone software earns trust by failing in simulation first. Before any autonomy code touches real hardware, you need a stack that lets you write Python missions, connect them to an autopilot, and watch the results without propellers spinning. This lesson builds that stack from scratch: a clean virtual environment, DroneKit for the control API, MAVProxy for command-line visibility, SITL as the simulated aircraft, and optionally AirSim when you need rendered camera images for perception work.
When you finish you will have a working environment, an understanding of how each layer talks to the next, and a reusable connection helper that your later lessons â navigation, perception, path planning â will all import.
The stack, layer by layer
Everything in drone AI development sits on the same vertical: your script calls a library, the library serializes MAVLink messages, the messages travel over TCP or a serial link, and an autopilot â real or simulated â executes them.
| Layer | Tool | Role |
|---|---|---|
| Your code | Python scripts | Missions, perception, planning |
| Control API | DroneKit-Python | High-level vehicle commands |
| Protocol | MAVLink via pymavlink | Message serialization |
| Routing | MAVProxy | Console, logging, module system |
| Autopilot | ArduPilot SITL or PX4 SITL | Simulated firmware |
| Visual sim | AirSim with Unreal | Camera images and physics |
The design intent is reuse: the exact same script that flies against SITL will connect to a real flight controller by changing one connection string. That property is what makes simulation-first development valuable rather than ceremonial â you are testing the code you will actually run, not a mock of it.
Each layer also fails in its own way, and knowing where to look saves hours. If the connection times out, the problem is transport: SITL is not running or the TCP port is wrong. If the connection opens but attributes stay unknown, the problem is readiness: telemetry has not flowed long enough for watchers to populate. If commands are accepted but nothing moves, the problem is mode logic: the vehicle is not in a mode that honors the command. Diagnosing in that order â transport, readiness, then semantics â keeps you from rewriting mission code when the actual fault was a stopped simulator.
Creating the environment
Isolation comes first. DroneKit's dependencies are old enough that they fight with system packages, so give every project its own virtual environment and pin requirements inside the repository.
# Step 1: isolate the environment
python -m venv drone-env
source drone-env/bin/activate # Linux and macOS
# drone-env\Scripts\activate # Windows PowerShell
# Step 2: control stack
pip install dronekit dronekit-sitl
pip install pymavlink mavproxy
# Step 3: numeric and vision tooling
pip install numpy matplotlib opencv-python
# Step 4: start the simulated aircraft
dronekit-sitl start --model quad --instance 0
SITL downloads a firmware build on first run and listens on a local TCP port â 5762 for the first instance. MAVProxy can sit between your script and SITL to expose a console (mavproxy.py --master=tcp:127.0.0.1:5762), which is invaluable for watching parameter changes and mode transitions while your code runs.
Connecting and reading state
The connection object is your window into the vehicle. Everything DroneKit exposes â mode, arm state, battery, GPS, attitude â arrives as attributes that update in the background as MAVLink messages decode.
from dronekit import connect
print("Connecting to simulator...")
vehicle = connect("tcp:127.0.0.1:5762", wait_ready=True, timeout=30)
print(f"Version: {vehicle.version}")
print(f"Mode: {vehicle.mode.name}")
print(f"Armed: {vehicle.armed}")
print(f"Battery: {vehicle.battery.voltage} V")
print(f"GPS: {vehicle.gps_0.satellites_visible} satellites")
print(f"Altitude: {vehicle.location.global_relative_frame.alt:.1f} m")
wait_ready=True blocks until the attribute watchers report healthy values, which prevents the classic beginner failure of reading None because the first telemetry frame had not arrived yet. Always gate on readiness before touching vehicle state.
Your first autonomous flight
Guided mode is the entry point for scripted control: switch mode, arm, command takeoff, wait for altitude, then issue goto commands. The routine below arms, climbs, flies a square, and lands â the minimal complete mission that exercises every part of the stack.
import math
import time
from dronekit import connect, VehicleMode, LocationGlobalRelative
def arm_and_takeoff(vehicle, target_alt):
print(f"Arming and taking off to {target_alt} m...")
vehicle.mode = VehicleMode("GUIDED")
while vehicle.mode.name != "GUIDED":
time.sleep(0.5)
vehicle.armed = True
while not vehicle.armed:
time.sleep(0.5)
vehicle.simple_takeoff(target_alt)
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)
def fly_square(vehicle, side_m=10, altitude=10):
home = vehicle.location.global_relative_frame
for i in range(4):
angle = math.radians(i * 90)
lat = home.lat + (side_m / 111320) * math.cos(angle)
lon = home.lon + (side_m / (111320 * math.cos(math.radians(home.lat)))) * math.sin(angle)
print(f" Leg {i + 1}")
vehicle.simple_goto(LocationGlobalRelative(lat, lon, altitude))
time.sleep(8)
def land(vehicle):
vehicle.mode = VehicleMode("LAND")
while vehicle.location.global_relative_frame.alt > 0.5:
time.sleep(1)
vehicle.armed = False
vehicle.close()
vehicle = connect("tcp:127.0.0.1:5762", wait_ready=True)
arm_and_takeoff(vehicle, 10)
time.sleep(2)
fly_square(vehicle, side_m=10, altitude=10)
time.sleep(2)
land(vehicle)
Run it against SITL repeatedly. Break the square by removing the wait, run two missions back to back, disconnect mid-flight â simulation exists so those mistakes cost nothing.
A connection helper worth reusing
Production scripts wrap connection logic once and import it everywhere, with timeouts, GPS gating, and status reporting baked in.
import sys
import time
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 open(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)
except Exception as exc:
print(f"Connection failed: {exc}")
sys.exit(1)
print(f"Connected: {self.vehicle.version}")
return self.vehicle
def wait_for_gps(self, min_satellites=10, timeout=60):
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 with {gps.satellites_visible} satellites")
return True
time.sleep(1)
print("GPS lock timeout")
return False
def status(self):
v = self.vehicle
print(f"mode={v.mode.name} armed={v.armed} "
f"battery={v.battery.voltage} V alt={v.location.global_relative_frame.alt:.1f} m")
def close(self):
if self.vehicle:
self.vehicle.close()
link = DroneConnection()
link.open()
link.wait_for_gps()
link.status()
link.close()
The GPS gate is the piece people skip and later regret: arming autonomous missions before a solid fix is how simulated habits turn into real fly-aways.
Visual simulation with AirSim
When the mission depends on pixels â obstacle detection, landing-pad recognition, semantic segmentation â SITL's numeric world is not enough. AirSim wraps an Unreal Engine environment around the same MAVLink interface and adds image capture.
import airsim
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
client.takeoffAsync().join()
state = client.getMultirotorState()
position = state.kinematics_estimated.position
print(f"Position: {position.x_val:.1f}, {position.y_val:.1f}, {position.z_val:.1f}")
client.moveToPositionAsync(10, 10, -5, 5).join()
responses = client.simGetImages([airsim.ImageRequest("0", airsim.ImageType.Scene)])
print(f"Captured {len(responses[0].image_data_uint8)} bytes")
client.landAsync().join()
client.enableApiControl(False)
AirSim returns raw or compressed buffers you can hand straight to OpenCV, which makes it the standard bridge between control lessons and perception lessons. The trade-off is setup weight: Unreal projects are gigabytes, so treat AirSim as optional until a lesson actually needs imagery.
Project layout and requirements
Keep configuration, source, and scripts separate from day one; mission parameters drift fast and you want diffs for them.
drone_ai_project/
|-- config/
| |-- params.yaml
| |-- missions/
|-- src/
| |-- connection.py
| |-- navigation.py
| |-- perception.py
| |-- controller.py
|-- tests/
| |-- test_navigation.py
|-- scripts/
| |-- run_mission.py
|-- requirements.txt
|-- README.md
# requirements.txt
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
Pin versions, commit the file, and recreate environments from it. A mission that only runs on one laptop's forgotten global install is a liability.
Verifying the installation end to end
Before writing mission logic, prove the stack with a smoke script that exercises every layer once: open the connection, wait for readiness, read mode and battery, confirm a GPS fix, and close cleanly. Run it from a fresh terminal in a freshly activated environment so you know the imports resolve without your editor's help, and make it exit with a nonzero status on failure so it can run in continuous integration later.
Two checks catch nearly every setup problem. First, confirm SITL responds before your script runs: open MAVProxy against the same port and watch heartbeats arrive; if the console shows nothing, the simulator never started and no Python code will fix that. Second, confirm attribute watchers populate: print mode, arm state, and satellite count twice, a few seconds apart, and verify the values are real rather than defaults.
Keep a reference run saved â output text, SDK versions, firmware version â so future environment rebuilds can be compared against a known-good baseline. When a later lesson fails mysteriously, the first question is whether the stack still reproduces that baseline, and a two-minute smoke test answers it, usually before you have finished forming a hypothesis about your own code. Only once the smoke script passes consistently should you trust the environment enough to debug your own mission code, because most first-day failures are wiring problems wearing the costume of programming errors.
Common Mistakes
Installing DroneKit into the system Python
Fix: Use a per-project virtual environment; global installs collide across projects and break on OS upgrades.
Running mission code before wait_ready and GPS gates pass
Fix: Block until telemetry is healthy and satellites are sufficient; None values and stale fixes cause most first-run failures.
Testing autonomous logic directly on hardware
Fix: Rehearse against SITL with the same script; only the connection string should change for real flights.
Hard-coding waypoints and parameters in source
Fix: Keep missions and parameters in config files so changes are versioned and reviewable.
Best Practices
- Start MAVProxy alongside your script during development to watch modes and parameters live.
- Wrap connection, GPS gating, and cleanup in a helper class imported by every script.
- Write a smoke test that connects, reads state, and disconnects; run it before each session.
- Keep a known-good SITL baseline â if a mission fails, first prove the simulator still arms and takes off.
- Record your SDK and firmware versions with each experiment; silent version drift wastes days.
Key Takeaways
- The drone development stack layers Python over DroneKit, MAVLink, MAVProxy, and a SITL autopilot, with AirSim added when camera imagery is required.
- Isolate every project in a virtual environment and pin requirements so the control stack stays reproducible.
- Connection readiness and GPS gating are mandatory gates before any autonomous command; they prevent the majority of first-run failures.
- The arm, takeoff, guided-goto, and land sequence is the minimal complete mission â rehearse it until breaking it is instructive rather than scary.
- Simulation-first is a workflow, not a phase: the same scripts run against SITL and real hardware, changing only the connection string.