# ArduCopter Simulink Model

The Simulink file [arducopter.slx](https://github.com/fbredeme/ardupilot_simulink/blob/master/arducopter.slx) contains a model of the ArduCopter Stabilize and Althold controllers. The plant models of the copter itself can be generated by [system identification](https://ardupilot.org/copter/docs/systemid-mode.html). 

![](simulink_model.PNG?raw=true "Simulink screenshot")

To run the simulation, the relevant data from a *.bin log file needs to be loaded to the MATLAB workspace. This can be done with the two scripts that are provided:

1) **sim_pre.m**: Loads flightdata from dataflash logs  
Opens a dialog to select the flightdata logs for data extraction with Ardupilog. Then, subflights from the log can be selected in the command line. A subflight represents a time segment with one active flight mode. Therefore, flight mode changes divide the log in several subflights. After subflight selection, a array called "sidLogs" is created. Each element of the array represents one selected subflight.

2) **sid_sim_init.m**: Loads relevant data for the simulation of a subflight from the sidLogs array  
At first, the index of the subflight in the sidLogs array has to be configured in the first line of the script. The subflight can be cropped in its length by configuring start and stop time ("tStart" and "tEnd"). Setting these to "0" and "inf" respectively will load the whole subflight into the workspace. Finally, the variable "simMode" can be used to test different parts of the whole Simulink model. Transfer function models of the copter, if available, can be simulated by setting the variable to 0. In any other configuration, dummy models will be used. The other modes 2, 3 and 4 can be used to validate the implemented controllers against measured data. In these simulation modes, the logged target and actual values are given to the respective controller, ignoring the computed signals of the model. The correct control behaviour can be validated by comparing the computed output signals to the measured output signals with the "Data Inspector" of Simulink.

For the validation of the implemented controller models, one can use the script **sid_controller_validation.m** after the flight data has been loaded to the workspace with **sim_pre.m**. In this case, only the index of the loaded log file ("log_idx") has to be specified by the user. The script then asks the user for the controller type to be validated and runs the simulation automatically. Afterwards, the simulated outputs of the respective controller are plotted together with the measured outputs and the fit between the corresponding signals is calculated. Both the figures and the calculated fits are saved in the "results" folder.

## Prerequesites
- [Ardupilog](https://github.com/Georacer/ardupilog) (add local repo to path in Matlab)
- A dataflash log of a test flight with the following LOG_BITMASK: 135923