You are on page 1of 7

ArguPilotMegaCodeOutline

byMarkGrennan02042013
https://docs.google.com/document/d/1OCEMtCq7NjrYeEroSsMPQCZNP0QvMxqYPPCJy2zZHI/edit?usp=sharing

ThisoutlineislicensedundertheGNULesserGeneralPublicLicenseaspublishedbytheFreeSoftware
Foundationeitherversion2.1oftheLicense,or(atyouroption)anylaterversion.
ThisoutlinedoesnotcoverallthecodeusebyArduPilotMega(APM).Forthat,readthesourcecode.Ittriesto
outlinehowthecodeisstructuredandwheremajorfunctionsarelocated.

Flyingisthegoal.TodothistheAPMmustoutputcontrolthemotorandaerodynamicservicesandtake
inputsfromthereceiver.Toflyautonomouslyithastosenseitsenvironmentandmakedecisionsthatchange
theoutputs.TosenseitsenvironmenttheArdupilothas:
12-bit ADC resolution for
3 Axis Gyros
3 Axis Accelerometers
AirSpeed (optional)
voltage dividers for battery voltage
pressure sensor and temp for accurate altitude
GPS for
location
ground speed
altitude
Magnetic compass (optional)

Aircraftmustbalanceairspeedandlifttofightgravity.Theymustflywithintheirflightenvelope.Thesesensor
inputsarefilteredthroughproportionalintegralderivative(PID)routinestolimitandchangestheoutputs.This
preventstheaircraftfromturningtooquicklytothenextwaypointandcombinemotorspeedandelevatorto
climbwithoutexceedingairspeed.

ArduPilotMegaasofVersion2.6.8
CodeAuthors:DougWeibel,JoseJulio,JordiMunoz,JasonShort,AndrewTridgell,RandyMackay,
PatHickey,JohnArneBirkeland,OlivierAdler,AmilcarLucas,GregoryFletcher

Ifyouknowbasicelectronicsandyouunderstandbinarycomputingbutyouarenotfamiliarwithprogramingan
Arduino(Atmel)youcanlearnalmostallyouneedfromtheInternet.Hereareafewgreatplacestostart.

CornellECE4760DesigningwithMicrocontrollers
DescriptionofPulsewidthmodulation
DIYDronesWebinar1YouTube

Largepartsofthecodeareincludedorexcluded(ifdef)andenabledordisableddependingonthetypeof
aircraftyouwillbeusing.

APM_config.hdefinesyouboard(APM1/APM2...)andifyouareusingasimulatorHardwareIntheLoop(HIL).

config.hdefinesdefaultandautomaticconfigurationconstantsThisiswhereyoucanmakechanges.

defines.hdefinesconstantsuseforcalculationslike:
ToRad(x)(x*0.01745329252)//*pi/180
ToDeg(x)(x*57.2957795131)//*180/pi
BATTERY_VOLTAGE(x)(x*(g.input_voltage/1024.0))*g.volt_div_ratio
andtheRELAY_PIN(47)aswellasenumerationsofthingslikeFlightModeandap_message.

Parameters.hdefinesglobal(public)memoryvariablesusedtocontroltheAPfunction.

GSC.hInterfacedefinitionforthevariousGroundControlSystem

ArduPlane.pde
Arduinoprogramsstartbyrunningtwosubroutines,setup()andloop().
setup()calledoneatboot
memcheck_init()libraries/memcheck/memcheck.cpp
fillsmemorywithsentinelvaluestohelppreventmemoryexhaustion.
init_ardupilot()system.pdeInitializeserialports,I2Cbus,theallotherAPMSensors
load_parameters()loadparametersfromEEPROM
DataFlash.Init()loginitialization
barometer.init(&timer_scheduler)
adc.init()inittheAnalogtoDigitalconverters(APM1only)
g_gps>init(GPS::GPS_ENGINE_AIRBORNE_4G)InittheGPSevenifinflight
init_rc_in()setsuprcchannelsfromradio
init_rc_out()setsupthetimerlibs
pinMode(C_LED_PIN,OUTPUT)GPSstatusLED
pinMode(A_LED_PIN,OUTPUT)GPSstatusLED
pinMode(B_LED_PIN,OUTPUT)GPSstatusLED
timer_scheduler.set_failsafe(failsafe_check)createa1khinterruptfordatareads.
ifENABLE_AIR_START
fixRCinputchannels
g_gps>update()
reload_commands_airstart()resumeAUTOfromwhereweleftoff
else
startup_ground()blinkLEDsaswelevelandgetGPSlockandzeropointson
giros,barometer,airspeedandtrimtransmitter
set_mode(MANUAL)
reset_control_switch()

loop()
calledcontinuouslyAcounter(mainLoop_count)isusedtocontrolhowoftendifferentloops
areexecuted.

Fast_loop()executeat50Hz(20ms)
read_radio()radio.pde
Ifselected
throttle_failsave()radio.pde
update_GPS()
updateroll_sensorfromsensororGPS
updatepitch_sensorfromsensororGPS
read_airspeed()sensors.pde
read_IMU()
calc_altitude_error()smooththealtitudereadings
update_current_flight_mode()
stabilize()applydesiredrollandpitch
set_servos_4() FLY!

medium_loop()
isdividedintofivedifferentsubroutines,eachperformedonceeachtimemedium_loopis
called.

0.update_GPS()at10Hs(100ms)
calc_gndspeed_undershoot()
1.read_control_switch()
navigate()performnavigationcomputationsrollbasedonbearingerror
2.read_receiver_rssi()
update_alt()readbarometer10hzonAPM1only
update_commands()checkmissionwaypoints
2.Sendeachselectedhighratetelemetry
Log_Write_Attitude(roll,pitch,yaw)
Log_Write_control_tuning()
Log_Write_Nav_Tuning()
Log_Write_GPS(iTOW,lat,Lng,alt,speed,course,GPS.Fix,GPS.NumSats)
3.controltheslowloop
Zeromedium_loopCounter
setdelta_ms_medium_loopandmedium_loopTimer_ms
read_battery()
slow_loop()

slow_loop() Thisloopshouldexecuteat31/3Hz
performoneofthefollowingcases.Eachoneshouldincrementslow_loopCounter.
0:Calculatetheplane'sdesiredbearing
navigate()
1:Performsystem/userfunctions
update_aux_servo_function()
enable_aux_servos()
read_control_switch()readmodeswitchfromtransmiter
2:update_events()heartbeat
check_ups_mux()switchbetweenUSBandRadiotelimity

FUNCTIONS:
update_GPS()
Checkifweneedtoperformagroundstart.
CountgoodGPSfixestobettercalculatealtitude.
IfLat=0
print"!!badloc"ontheconsole
else
init_home()
SetiTOW=GPS.Time
Setcurrent.lng=GPS.Longitude
Setcurrent.lat=GPS.Lattituede
Setcurrent_alt=calculatedorGPS.Altitude
Setground_sourse=GPS.Ground_Course
CalculateCOGX
CalculateCOGY
Setground_speed=GPS.Ground_Speed
Setspeed_3d=GPS.Speed_3d/100

update_current_flight_mode()
Preformvirusflightmodes.
RTL: NULL
LOITER: NULL
AUTO:
calc_throttle()
FLY_BY_WIRE_A:NULL
FLY_BY_WIRE_B:
STABILIZE:
Setnav_roll=0
Setnav_pitch=0
TAKEOFF:
Setnav_roll=0
Setnav_pitch=takeoff_pitch
Setservo_out[CH_THROTTLE]=THROTTLE_MAX
LAND:
Setnav_pitch=landing_pitch
Setnav_roll=0
calc_throttle()
CIRCLE:
Setnav_roll=HEAD_MAX/3
Setservo_out[CHTHROTTLE]=THROTTLE_CRUISE
MANUAL:
Readradioroll,pitchandthrottleandapplytoservos.
/*Printchannelroll,pitchandthrottle*/
read_IMU()
Read_adc_raw() getthecurrentvaluesfroIMUsensors
Matrix_update() IntergratetheDCMmatrix
Normalize() NormalizetheDCMmatrix
Drift_correction() Preformdriftcorrection
Euler_angles() Calculatepitch,roll,yaw
FILEEND

system.pde
Theinit_ardupilotfunctionprocesseseverythingweneedforaninairrestartWewilldeterminelaterifweare
actuallyonthegroundandprocessagroundstartinthatcase.

init_ardupilot()
initneededserialports0(USBCONSOLE)
serialport1(GPSdata)
serialport3(xBeeTelemetry)
InitradioandreadcriticalconfigurationsAPM_RC.Init()
Readcriticalconfiginformationtostartread_EEPROM_startup()
APMADClibraryinitializationAPM_ADC.Init()
APMAbsPressuresensorinitializationAPM_BMP085.Init()
DataFlashloginitializationDataFlash.Init()
GPSInitializationGPS.init()
Inittheservos
readintheflightswitchesupdate_servo_switches()

FUNCTIONS:
startup_ground()
allthecalibrations,etc.thatweneedduringagroundstart

set_failsafe()

startup_IMU_ground()

update_GPS_light()
SetGPSLEDonifwehaveafixorBlinkGPSLEDifwearereceivingdata

resetPerfData()
FILEEND

radio.pde
ReadrollinputAPM_RC.InputCh(CH_ROLL)
ReadpitchinputAPM_RC.InputCh(CH_PITCH)
Calculatemixedchannels
readtheotherfivechannelsandstorevalues
Calculatethethrottlevalue
FUNCTIONS:
throttle_failsafe
trim_control_surfaces
Storecontrolsurfacetrimvalues
trim_radio
read_radio_limits
setinitialservovaluelimitsforcalibrationroutine
FILEEND

Attitude.pde
stabilize()
Functionthatcontrolsaileron/rudder,elevator,rudder(if4channelcontrol)andthrottleto
producedesiredattitudeandairspeed.
crash_checker()
calc_throttle()
noairspeedsensor,weusenavpitchtodeterminetheproperthrottleoutput
Withairspeedsensor,throttlecontrolwithairspeedcompensation
Setservovalue

calc_nav_yaw()
calc_nav_pitch()
calc_nav_roll()
roll_slew_limit(
throttle_slew_limit(

PID()
reset_I()
set_servos_4()
Settheflightcontrolsurfaceservosbasedonthecurrentcalculatedvalues
readOutputCh()

commands.pde
commands_process.pde
control_modes.pde
DCM.pde
debug.pde
EEPROM.pde
events.pde
GCS_ardupilot.pde
GCS_DebugTerminal.pde
GCS_Jason_text.pde
GCS_Standard.pde
GCS_Splain.pde
HIL_output.pde
Log.pde
navigation.pde
sensors.pde
setup.pde
test.pde

You might also like