Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

115 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Drone Software

Autonomous drone flight controller for Raspberry Pi 4B + APM 2.8, featuring gyro-based heading hold, GPS-assisted navigation, BMP280 + VL53L0X altitude hold, pre-flight IMU cross-calibration with Kalman filtering, vibration health monitoring, multi-condition emergency landing, RSSI-gradient Return to Launch, flight logging, thermal camera streaming, and ground station tools.


Picture

WhatsApp Image 2026-06-28 at 7 14 49 PM

Hardware

Component Details
Flight Controller APM 2.8
Companion Computer Raspberry Pi 4B 2GB
IMU / Compass MPU-6050 (I2C 0x68)
Barometer (primary) MS5611 (onboard APM 2.8)
Barometer (secondary) BMP280 (I2C, Adafruit CircuitPython)
Rangefinder VL53L0X ToF (I2C 0x29)
GPS NEO-6M (UART /dev/serial0, 9600 baud)
RC Receiver FlySky (connected to APM RC input)
Thermal Camera AMG8833 8×8 (I2C 0x69)
Gas Sensor MQ-2 digital (GPIO)
Buzzer Active buzzer (GPIO 17)
LoRa Radio SX127x 433 MHz (SPI, pySX127x)
Connection APM → Pi via USB (/dev/ttyACM0)

MPU-6050 / VL53L0X wiring (I2C bus 1):

Pin Raspberry Pi
SDA GPIO 2 (pin 3)
SCL GPIO 3 (pin 5)
VCC 3.3V (pin 1)
GND GND (pin 6)

Communication Protocols

MAVLink — Pi ↔ APM 2.8 (USB Serial)

Property Value
Protocol MAVLink v1
Transport USB Serial (/dev/ttyACM0)
Baud rate 115200
Library DroneKit
  • DroneKit sends channel override commands (vehicle.channels.overrides) for Ch1–Ch4.
  • APM sends back telemetry: battery, RC channels, heartbeat, armed state, baro altitude, IMU attitude.
  • Heartbeat monitored every 0.1s — exceeding PACKET_LOSS_TIMEOUT (3s) triggers emergency landing.
  • Parameters read/written via direct MAVLink PARAM_REQUEST_READ / PARAM_SET, bypassing DroneKit cache.

PWM — APM ↔ ESCs / Motors

Property Value
Pulse width range 1000–2000 µs
Neutral (roll/pitch/yaw) 1500 µs
Min throttle 1100 µs
  • In ALT_HOLD mode, Ch3 is a rate command: 1500 = hold, >1500 = climb, <1500 = descend.
  • Ch4 (yaw) nudged ±YAW_PWM_LIMIT (100 µs) to correct heading drift.

I2C — Pi ↔ MPU-6050 / BMP280 / VL53L0X / AMG8833

Device Bus Address Library
MPU-6050 I2C bus 1 0x68 smbus2
BMP280 I2C bus 1 auto adafruit-circuitpython-bmp280
VL53L0X I2C bus 1 0x29 smbus2 (pure driver)
AMG8833 I2C bus 1 0x69 smbus2

GPS — NEO-6M (UART)

Property Value
Port /dev/serial0
Baud 9600
Sentences GGA, RMC
Library pyserial
  • GPSTracker thread parses NMEA at 1 Hz, locks home position on first fix.
  • Dead reckoning fills gaps when GPS is stale (integrates speed + heading).
  • WiFiLocationSender streams GPS state to laptop over UDP port 5055 at 1 Hz.

LoRa — SX127x 433 MHz (SPI)

Property Value
Frequency 433.0 MHz
Spreading Factor SF7
Bandwidth 125 kHz
Library pySX127x (Communication Protocol/pySX127x/)
  • Used by drone_rtl/rssi.py for RSSI gradient scanning during RTL.
  • Base station transmits a periodic beacon; drone reads RSSI of last received packet.

Files

Root — Flight Scripts

File Purpose
Drone_automation.py Main flight script — takeoff, hover, landing, GPS lock, emergency handling, in-flight vibration monitor, BMP280 altitude PID, MPU anomaly detector
compass_anchor.py Public API wrapper — exposes pitch(), roll(), heading(), error_from()
compass_pi.py MPU-6050 driver, complementary filter, sensor thread, standalone GUI
pre_flight_cal.py Pre-flight APM vs Pi IMU cross-calibration — Kalman filter, vibration health check, param write/verify
gps_tracker.py NEO-6M NMEA parser thread, dead reckoning, home position lock
payload_sensors.py Buzzer, MQ-2 gas sensor, AMG8833 thermal camera drivers
angle_detector.py Optical flow pan angle detection (Lucas-Kanade) — deferred until hardware available

Ground Station / Laptop Tools

File Purpose
flight_db.py SQLite flight logger — telemetry, events, GPS, thermal tables
flight_viewer.py Flask web viewer for flight_logs.db — http://localhost:5000
export_flights.py Export flight_logs.db to JSON (flight_exports/)
laptop_gps_map_receiver.py Receives UDP GPS packets from drone, serves live Leaflet map at http://localhost:8080
wifi_location_sender.py Sends GPSTracker state to laptop over UDP (runs on Pi)
base_station_receiver.py Monitors a folder for new files received from the drone
drone_file_sender.py rsync-based file transfer from Pi to base station over SSH
thermal_streamer.py Reads AMG8833 at 10 Hz, streams UDP packets to laptop (runs on Pi)
thermal_viewer.py Receives thermal UDP stream, renders live interpolated heatmap (runs on laptop)
imu_dashboard_pro.py Pygame IMU dashboard with Mahony filter — standalone Pi visualiser

drone_rtl/ — Return to Launch Module

File Purpose
main.py RTL entry point — monitors battery voltage and Ch5 kill switch
rtl.py RSSI gradient scan + IMU dead reckoning navigation, two-phase soft landing
rssi.py SX127x LoRa RSSI reader for gradient navigation
imu.py IMU dead reckoning — gyro yaw integration + x/y position estimate
mavlink_control.py MAVLink helpers — NED velocity, yaw command, land, disarm
vl53l0x_landing.py Pure smbus2 VL53L0X ToF driver for ground detection
uwb.py UWB serial distance reader (stub)
config.py All RTL tunable constants

Communication Protocol/ — Radio Comms

File Purpose
Raspberry Pi Communication.py NRF24L01 + LoRa dual-radio telemetry
Comm.py Communication helpers
lora_mpu6050_transfer.py LoRa + MPU-6050 combined transfer
lora_tx_test.py LoRa TX test
pySX127x/ SX127x LoRa Python driver

Data

Path Contents
flight_logs.db SQLite database — all flight telemetry, events, GPS, thermal
flight_exports/ JSON exports per flight + flights_summary.json

Tech Stack

Layer Technology
Language Python 3.13
MAVLink / APM comms DroneKit
IMU driver smbus2 (I2C)
Sensor fusion Complementary filter (gyro + accel, 98/2 split)
Trim correction filter Simplified 1D Kalman filter (pitch + roll)
Altitude hold (primary) APM MS5611 via ALT_HOLD mode
Altitude hold (secondary) BMP280 via Adafruit CircuitPython + PID controller
Landing rangefinder VL53L0X ToF (pure smbus2 driver)
GPS NEO-6M NMEA over UART + dead reckoning
RTL navigation RSSI gradient (LoRa SX127x) + IMU dead reckoning fusion
Vibration analysis Rolling-window stddev (pre-flight) + per-axis Kalman-weighted (trim)
Flight logging SQLite via flight_db.py
Flight viewer Flask web app
Thermal camera AMG8833 8×8 via smbus2, streamed over UDP
Compass UI (standalone) OpenCV + NumPy
Threading Python threading (100 Hz sensor loop, GPS loop, file sender)

Installation

1. Fix DroneKit for Python 3.10+ (including 3.13):

sed -i 's/collections\.MutableMapping/collections.abc.MutableMapping/g' \
    $(pip show dronekit | grep Location | awk '{print $2}')/dronekit/__init__.py
sed -i 's/collections\.Callable/collections.abc.Callable/g' \
    $(pip show dronekit | grep Location | awk '{print $2}')/dronekit/__init__.py
sed -i 's/collections\.Mapping/collections.abc.Mapping/g' \
    $(pip show dronekit | grep Location | awk '{print $2}')/dronekit/__init__.py
python -c "from dronekit import connect, VehicleMode; print('DroneKit OK')"

2. Fix pyserial conflict:

pip uninstall serial -y
pip install pyserial

3. Enable I2C and UART on the Pi:

sudo raspi-config
# Interface Options → I2C → Enable
# Interface Options → Serial Port → Enable (disable login shell, enable hardware port)

Verify devices:

sudo i2cdetect -y 1
# Should show: 29 (VL53L0X), 68 (MPU-6050), 69 (AMG8833), BMP280 address

4. Add user to dialout group:

sudo usermod -a -G dialout $USER
# Then reboot

5. Install dependencies:

pip install -r requirements.txt

If opencv-python times out on Pi:

sudo apt install python3-opencv -y
python3 -m venv --system-site-packages venv

6. APM setup (via Mission Planner):

  • Disable pre-arm checks: ARMING_CHECK = 0
  • Calibrate RC: Initial Setup → Mandatory Hardware → Radio Calibration
  • Confirm USB port: dmesg | tail -20 — look for ttyACM0

Running

Main flight script:

python Drone_automation.py

RTL module (standalone — triggers on low battery or Ch5):

cd drone_rtl
python main.py

Flight log web viewer (laptop):

python flight_viewer.py
# Open http://localhost:5000

Export flights to JSON:

python export_flights.py
# Output: flight_exports/flight_N.json + flights_summary.json

Live GPS map (laptop):

python laptop_gps_map_receiver.py   # laptop — serves http://localhost:8080
python wifi_location_sender.py      # Pi — streams GPS over UDP

Thermal camera stream:

python thermal_viewer.py            # laptop — start first
python thermal_streamer.py          # Pi — auto-discovers laptop

Compass UI standalone:

python compass_pi.py

Features

Pre-Flight Calibration (pre_flight_cal.py)

Runs automatically before every flight. Compares Pi MPU-6050 against APM's internal IMU via MAVLink, then writes corrected trim parameters to APM EEPROM.

  • Phase 1 — Static sampling (3s, motors off): baseline gyro noise on all axes.
  • Phase 2 — Dynamic sampling + vibration health check: motors at PREFLIGHT_THROTTLE (1350 PWM).
  • Phase 3 — Kalman-filtered corrections: fuses static and dynamic measurements. High noise → trusts static more.
  • Phase 4 — Write params + reboot: writes AHRS_TRIM_X/Y and INS_MPU6K_FILTER, verifies via direct MAVLink read, reboots APM.

Vibration abort thresholds (pre-flight):

Axis Threshold Failure means
X / Y (roll/pitch) 3.0 deg/s stddev Prop imbalance, bent shaft, loose mount
Z (yaw) 2.5 deg/s stddev ESC desync, winding fault, bad bearing

GPS-Assisted Takeoff

  • GPSTracker thread reads NEO-6M NMEA continuously.
  • Flight waits for GPS lock (configurable min satellites, HDOP, stable hold time) before arming and before takeoff.
  • Home position locked on first GPS fix — used for RTL dead reckoning reference.
  • Ch5 arm switch and Ch6 autonomous switch gate the arming and takeoff sequence.

ALT_HOLD Vertical Takeoff

  • APM armed in STABILIZE, then switched to ALT_HOLD for climb.
  • BMP280 secondary barometer provides a PID-corrected altitude hold layer on top of APM's internal baro loop.
  • VL53L0X ToF sensor hands off from baro at 3m AGL for precise landing flare and ground detection.
Phase Throttle What happens
Armed idle 1100 ESCs initialise
Climb 1600 APM climbs to TARGET_ALTITUDE
Hold 1500 APM holds altitude via baro loop
Descend 1400 APM descends smoothly

In-Flight Vibration Monitor

Reads APM attitude rates as primary gyro source at 10 Hz. Rolling window of 30 samples per axis, evaluated every ~1 second.

Axis In-flight threshold
X (roll) 6.0 deg/s stddev
Y (pitch) 6.0 deg/s stddev
Z (yaw/ESC) 5.0 deg/s stddev

Breach during climb or hover triggers emergency landing. During descent, logs a warning and continues.

Heading Hold (Yaw)

  • MPU-6050 gyro tracks rotation at 100 Hz in a background daemon thread.
  • Complementary filter: 98% gyro + 2% accel for pitch/roll. Yaw is gyro-only.
  • lock_north() marks current physical direction as 0° after GPS lock.
  • Yaw correction = 1500 - YAW_KP × error, clamped to ±YAW_PWM_LIMIT.

Return to Launch (drone_rtl/)

Triggered by low battery or Ch5 kill switch. Two complementary navigation modes:

  1. RSSI gradient scan — rotates through 8 headings (45° steps), samples LoRa RSSI at each, flies toward strongest signal. Re-scans every 3m. Terminates when RSSI ≥ −65 dBm.
  2. IMU dead reckoning — integrates velocity commands into x/y position. Used as fallback or fused with RSSI heading (weighted blend).

Two-phase soft landing:

  • Phase 1 (above 3m) — APM baro descent at 0.6 m/s.
  • Phase 2 (below 3m) — VL53L0X ToF. Flares to 0.3 m/s at 400mm, cuts motors at 150mm. Falls back to baro 0.15m if VL53L0X unavailable.

Emergency Landing

Trigger Condition
Low battery Voltage < BATTERY_LAND_VOLTAGE (10.8V)
Packet loss No MAVLink heartbeat for PACKET_LOSS_TIMEOUT (3.0s)
In-flight vibration Any gyro axis exceeds in-flight threshold
Malfunction Any unhandled Python/DroneKit exception

controlled_land() uses ALT_HOLD + THROTTLE_DESCEND for soft baro-managed touchdown. If it fails, emergency_fallback() clears overrides and switches APM to LAND mode.

Pilot Abort / Kill Switch

  • Ch5 (PWM > 1500) — kills mission at any stage.
  • Ch2 pitch stick (> ±200 from centre) — aborts during climb.
  • Ch6 RC takeover (PWM > 1500) — Pi clears overrides, APM switches to STABILIZE. Flip Ch6 down to resume.

Flight Logging (flight_db.py)

SQLite WAL-mode database with five tables:

Table Contents
flights Start/end time, outcome, notes
telemetry Per-tick: altitude, velocity, attitude, vibration, throttle, battery, BMP280, GPS heading, mode
events Named events with severity, phase, altitude, battery
gps_log Per-tick GPS state: lat/lon, fix, satellites, HDOP, speed, course, source
thermal_log Per-tick AMG8833 64-pixel array (JSON) + min/max/mean °C

Thermal Camera (thermal_streamer.py + thermal_viewer.py)

  • Pi reads AMG8833 at 10 Hz, packs 64 floats into a UDP struct packet.
  • Laptop auto-discovered via UDP broadcast beacon — no hardcoded IPs.
  • Viewer renders a live bicubic-interpolated heatmap with per-pixel temperature labels.

Configuration

Drone_automation.py

Parameter Default Description
YAW_KP 3.0 Yaw correction gain
YAW_PWM_LIMIT 100 Max ± PWM on yaw channel
BATTERY_LAND_VOLTAGE 10.8 Emergency land voltage (3S). Use 14.4 for 4S
PACKET_LOSS_TIMEOUT 3.0 Seconds without heartbeat before emergency land
THROTTLE_CLIMB 1600 Climb rate command
THROTTLE_HOLD 1500 Altitude hold command
THROTTLE_DESCEND 1400 Descent rate command
THROTTLE_NEUTRAL 1100 Idle/disarm PWM
TARGET_ALTITUDE 1.0 Metres to climb before hovering
CLIMB_TIMEOUT 15 Max seconds to reach altitude
HOVER_DURATION 5 Seconds to hold hover
DESCENT_TIMEOUT 20 Max seconds to reach ground
INFLIGHT_VIBRATION_X/Y 6.0 In-flight roll/pitch abort threshold (deg/s stddev)
INFLIGHT_VIBRATION_Z 5.0 In-flight yaw/ESC abort threshold
VIBRATION_WINDOW_SIZE 30 Rolling window samples
VIBRATION_CHECK_INTERVAL 10 Ticks between vibration checks
AH_KP / AH_KI / AH_KD — BMP280 altitude PID gains
AH_DEADBAND_M — BMP280 PID deadband (metres)
GPS_LOCK_STABLE_S — Seconds GPS must be stable before arming

pre_flight_cal.py

Parameter Default Description
PREFLIGHT_THROTTLE 1350 Motor test PWM (below liftoff)
TRIM_THRESHOLD_DEG 0.5 Min error to write a param
TRIM_SANITY_MAX_DEG 10.0 Max error before aborting calibration
VIBRATION_ABORT_X/Y 3.0 Pre-flight roll/pitch abort threshold
VIBRATION_ABORT_Z 2.5 Pre-flight yaw/ESC abort threshold
KALMAN_PROCESS_VARIANCE 0.01 Kalman model uncertainty
EEPROM_FLUSH_DELAY 3.0 Seconds to wait after writing before reboot
REBOOT_WAIT 10 Seconds to wait after reboot before reconnecting

drone_rtl/config.py

Parameter Default Description
RTL_SPEED 0.6 m/s horizontal velocity during RTL
RSSI_SCAN_STEPS 8 Headings to sample (45° steps)
RSSI_HOME_RSSI_THRESH -65 dBm — RSSI ≥ this = home reached
RSSI_RESCAN_DIST_M 3.0 Re-scan after travelling this far
VL53L0X_GROUND_MM 150 mm — below this = ground contact
VL53L0X_FLARE_MM 400 mm — begin throttle flare
VL53L0X_HANDOFF_MM 3000 mm — hand off from baro to VL53L0X
DESCENT_TIMEOUT_S 30 Hard timeout if VL53L0X fails

Telemetry Format

Every tick of the flight loop prints one line:

[HOVER] Batt:11.8V | HB:0.1s | Mode:ALT_HOLD | Alt:1.02m | Ch3:1500 |
Pi Pitch:0.3° Roll:-0.2° | APM Pitch:0.4° Roll:-0.1° |
VibX:1.23 Y:1.41 Z:0.98 | YawErr:0.8° | Hdg:2.1° | CmpLock:True |
GPS:Fix:YES Sats:9 HDOP:1.2 Src:GPS Lat:-27.4698000 Lon:153.0251000

Pre-Flight Checklist

  • Battery voltage above 10.5V (3S) before arming
  • Drone on flat surface, pointing desired hold direction
  • Props installed and tight
  • I2C enabled — MPU-6050 at 0x68, VL53L0X at 0x29, AMG8833 at 0x69
  • UART enabled — NEO-6M on /dev/serial0
  • APM pre-arm checks disabled (ARMING_CHECK = 0)
  • RC calibrated in Mission Planner
  • USB port confirmed (ttyACM0 or ttyUSB0)
  • DroneKit patched for Python 3.10+ (collections.abc fix applied)
  • pyserial installed (not serial dummy package)
  • Stay clear of motors during calibration dynamic phase

Vibration Diagnosis Guide

Failed axis Likely cause Fix
X and/or Y Propeller imbalance Balance props
X and/or Y Bent motor shaft Replace motor
X and/or Y Loose motor mount Tighten, add threadlock
Z (yaw) ESC desync Recalibrate all ESCs simultaneously
Z (yaw) Motor winding fault Spin motor by hand — feel for roughness
Z (yaw) Damaged bullet connector Inspect and re-solder
All axes high MPU-6050 not mounted rigidly Add vibration damping foam under Pi

Known Limitations

Limitation Detail
Yaw drift MPU-6050 has no magnetometer — yaw is gyro-only, drifts ~1–3°/min. Add HMC5883L for long flights.
Baro accuracy MS5611 ±0.5–1.0m indoors/wind. Don't set TARGET_ALTITUDE below 1.0m.
RTL without GPS RTL uses RSSI + IMU dead reckoning — no absolute position. Accuracy degrades with distance and signal interference.
Python GIL Three concurrent threads share the GIL. Occasional 20–50ms loop jitter is normal — APM handles the 400Hz control loop internally.
DroneKit unmaintained Last updated 2018. Requires manual patch for Python 3.10+. Consider migrating to pymavlink directly.
UWB stub drone_rtl/uwb.py is a stub — requires UWB hardware and UWB_PORT/UWB_BAUD constants added to config.py.

Deferred / Future

  • GPS / LOITER mode — position hold and waypoint navigation. Requires GPS wired to APM. Would replace baro-only altitude hold with full 3D position hold.
  • Magnetometer — true north heading to eliminate gyro yaw drift. HMC5883L or QMC5883L on APM I2C.
  • angle_detector.py — optical flow pan angle detection (Lucas-Kanade). Deferred until optical flow camera or lidar is available.
  • UWB ranging — drone_rtl/uwb.py stub ready. Requires UWB module wired to Pi UART.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages