From control requirements to PIL test: development of a structure to Autopilot implementation

This article presents the development of Autopilot (AP) blocks for a fixed-wing aircraft and the implementation of a Processor In the Loop (PIL) test platform. The AP entails the control, guidance, and navigation blocks. The control block design employed classical control theory considering a Piper ¼ aircraft model, and the MILF-8785C design requirements standard. The PIL test platform is composed of an AP running in a microcontroller and a simulated aircraft on a PC (Personal Computer). The results of three missions carried out on the PIL platform are presented. In these missions, the performed maneuvers are such that lateral and longitudinal controls are required. In all three cases, all predefined waypoints are achieved, indicating the success of the developed AP project. The AP test implemented in a microcontroller that can be embedded onto an aircraft for a real flight mission indicates the usefulness of the developed PIL platform.


I. INTRODUCTION
An Unmanned Aerial Vehicle (UAV) can be autonomous or remotely controlled and, in several countries, a human pilot on the ground ready to take on the mission via radio control is required. However, despite these restrictions, research related to autonomous vehicles is being carried out, whether related to the physical structure of the vehicle [1], [2], either to the applications of these vehicles, such as the study of the feasibility of using UAVs in VOR (VHF Omnidirectional Range) inspection [3], the use of UAVs as base stations to offer wireless connectivity for users without the necessity of new terrestrial infrastructure [4], application of UAVs in precision agriculture [5]. ITS (Intelligent Transportation Systems) is another example of an application applied to flying accident report agents, flying roadside units (RSUs), flying speed cameras, flying police eyes, and flying dynamic traffic signals [6]. The coordination of activities of these vehicles in a swarm can be also mentioned: developing HIL platforms to test classical UAV swarm control application scenarios [7], exploring the use of distributed control in UAV swarm for the purpose of terrain mapping [8], developing design and software-in-the-loop implementation of adaptive formation controllers for fixed-wing unmanned aerial vehicles (UAVs) [9], or applying coordinated control method to continuously track a moving target using a group of UAVs [10], to name a few.
In order to operate autonomously, a UAV must have an AutoPilot (AP) for carrying out a mission. Several commercial AP are available on the market, but the addition of new features is not an easy task. In purpose to accelerate the development of new systems, references [11] and [12] propose the use of commercial APs as a low-level system by adding new features in a matured system. Once a new AP or subsystem is developed, bench testing is required before field testing. Processor-In-the-Loop (PIL) tests provide an effective platform for the development and test of the embedded system [13], [14]. PIL should be adopted whenever possible to validate hardware and software under the most realistic conditions. This work presents the design of an AP and the tasks involved in its development: aircraft modeling, aircraft control design, and the implementation of the guidance VOLUME XX, 2017 algorithm and control loops. It also addresses the development of a test platform for an AP for a fixed-wing UAV. On a test platform, it is possible to use two types of aircraft models: an aircraft simulated by a flight simulator, such as the X-Plane [15], [16], or an aircraft simulated by its mathematical model such as, for instance, in [9], in which the mathematical models of fixed wing UAVs are simulated in Matlab, for implement an adaptive formation control of these vehicles. Reference [17] uses an accurate nonlinear model of the aircraft dynamics to investigate an approach of a loop-shaping for distressed fixed-wing aircraft experiencing control loss due to surface or power failure. Reference [18] proposes an AP and Path Planning for a UAV in flying wing configuration. Analytical aerodynamics computer programs were used to find the aerodynamic coefficients and, with them, the mathematical equations of the UAV were simulated. Reference [19] shows a prototype of a gun-launched micro air vehicle system (GLMAV) developed for long-distance observation capabilities. Based on wind-tunnel measurements, a model of the transient phase (the phase in which the UAV is changing its configuration from projectile to a rotary-wing micro air vehicle) is built, allowing the design and simulation of control laws for this phase. In both cases, obtaining the model of a specific aircraft requires extensive work, either through the use of design tools (for X-Plane) or mathematical equations. In this work, the identification of an aircraft model was not carried out. A mathematical model available in the literature [20] was used and relevant information is presented about the mathematical model of a fixed-wing aircraft and its use on a test platform as proposed. In this text, the term "aircraft" refers to the aerial platform (on which the AP will be shipped), while "UAV" refers to the platform with the AP onboard, capable of performing an autonomous mission. In many situations, however, these terms may be interchangeable. The term "Unmanned Aerial System" is used for the complete system consisting of aircraft, AP, payload, and ground station.
Depending on the problem to be solved and the platform to be used, there are several proposals for the control loops. For instance, [21] presents an overview of controller design based on chosen specifications for a mini-helicopter. Reference [22] investigates the control problem of a quadricopter considering uncertain parameters, external disturbances, and input saturation. The solution proposes different control approaches such as robust controller and adaptive switching gain.. Reference [23] applies a modelindependent control strategy called high-order differential feedback control to a quadrotor unmanned aerial vehicle. Reference [24] main concern is the control of a system facing an external disturbance corresponding to sensor failures. The solution employs a PID Sliding Mode Control (SMC), and the controlled system is a quadrotor dynamic model. Reference [25] deals with the problem of altitude control of the variable load quadrotor unmanned aerial vehicle, and a robust sliding mode controller (SMC) is proposed. Reference [26] discusses the development of a control architecture for hybrid UAVs, those which combine the beneficial features of fixed-wing UAVs and rotary wings UAVs. The control architecture is done based on model-free control principles. For fixed-wing aircraft, the control loops are typically well established. However, flight qualities definitions for UAV, which result in specification of parameters to be used in the control loops design for UAVs, does not exist [27] or, at least, are not established. One possibility is to use the parameters employed for human-piloted aircrafts [28]. In this work, the Longitudinal and Latero Directional control loops are designed using classical control theory, employing the aircraft mathematical model. The design of the control loops uses the definitions of Aircraft Classes, Flight Quality, and Flight Phase [29] for the specifications of the design parameters of the aircraft flight modes.
The development of an AP in a modularized way allows the development of each subsystem independently [30], [31]. In addition, a bench test platform that allows testing new proposals for each subsystem is quite appropriate for the rapid development of APs using new algorithms in their subsystems. In academic and business environments, a platform such as the proposed can be used for the development and implementation of new control, guidance and navigation algorithms. The new algorithm can be introduced in the complete AP, embedded in a microprocessor, and the virtual flight mission test can be executed. So, the performance of the new algorithm (as part of an AP) can be verified in a faster way.
In this work, the control block was implemented by the control loops designed using the specification parameters in [29], as stated before. The designed guidance algorithm follows the proposal made by [32], which interacts with the navigation and the control blocks. The navigation block resides in the platform's AP, where algorithms to filter data read from sensors or for sensor data fusion can be implemented. However, in this work, no algorithm is implemented in this block. The information received from the aircraft model is passed directly to the guidance and control blocks. Since in this work the algorithms are encapsulated in their respective blocks, changing a specific algorithm does not impose an alteration in other blocks in the system. In this way, developers of new AP functionalities can benefit from the development carried out in a modular way.
For the implementation of the PIL test platform, it is necessary to define the devices that compose the platform and to establish communication among them (simulated aircraft and embedded AP). The aircraft is simulated in MATLAB and the information of its current state is sent to the AP embedded in a microcontroller. The AP calculates the control surface commands to be imposed on the aircraft and returns these data to the aircraft.
With the platform implemented, initial PIL tests were carried out with the control loops embedded in the microcontroller. Then, the entire AP system developed was implemented in the microcontroller and simulated flight missions were carried out on the PIL platform. In the three experiments presented, the aircraft completed the missions, passing through the waypoints defined at the beginning of each mission. In two missions, an altitude variation was imposed. In both cases, the maximum error between the reference velocity and the aircraft velocity does not exceed 16%, remaining less than 5% during most of the flight.
The rest of the paper is organized as described in the flowchart in Figure 1. In section II, the blocks of an AP and an UAS used in the context of this work are described. These blocks are responsible for making the aircraft perform the flight mission successfully. In this work the aircraft is a mathematical model of a Piper J-3 Cub ¼ scale, which is presented in Section III. In this section it is also presented the linearized Longitudinal and Latero Directional models and a discussion about the stability and flying qualities is done. Section IV presents the control loop design using classic control theory for the aircraft linearized models, which constitutes the Control block of the AP. In Section V it is presented the Guidance Algorithm used in the Guidance block of the AP. With the Control block and the Guidance block working they were embedded in a microcontroller communicating with the aircraft model running in MATLAB environment in a PC. Then, the AP, in this work constituted by the Control and Guidance block, is embedded in a microcontroller and a PIL platform is built, as presented in Section VI. In Section VII the PIL mission tests are presented. Section VIII presents the conclusions of the work.

II. PROBLEM STATEMENT
An AP has several subsystems, which can be detailed in different ways. For instance, in [31] and [34], the classical Guidance, Navigation, and Control blocks composing the GN&C system are used to describe the autopilot. Reference [33] does not characterize the AP, it deals with the main elements of a UAV, including onboard processing units, navigation sensors, mission-oriented sensors, communication modules, and ground control stations. Reference [35] shows a UAV autopilot system is a closeloop control system, which comprises two parts: the state observer and the controller, and a typical off-the-shelf UAV autopilot system comprises of the GPS receiver, the micro inertial guidance system, and the onboard processor (state estimator and flight controller). Figure 2 depicts the platform proposed in [35], with an AP including three main subsystems: Navigation, Control, and Guidance.
The microcontroller executes the Navigation, Guidance and Control subsystems, and manages data exchange among subsystems.
The Guidance subsystem computes the maneuvers (reference signals) which the vehicle must perform to achieve the objective, according to the aircraft status and mission.
The Control subsystem receives information of the current aircraft state, and the maneuver to be performed to computes which commands will be given to the vehicle's control actuators. The Control Surface Manager is responsible for sending deflection commands to the aircraft's control surfaces, ailerons, rudder, and elevator.
The Navigation system encompasses the sensors that read the status of the aircraft and the algorithms that process the signals, in order to provide the data to be used by the AP subsystems. In this work, this module only receives the information from the simulated aircraft and sends it to the microcontroller, without performing any processing.
The Ground Control Station keeps the status of the aircraft mission up to date for the ground team and can send new commands to the AP. The Control Surface Manager and Control Station subsystems will not be explored in this work.

III. THE AIRCRAFT MODEL
The aircraft modeling and identification obtain the mathematical model necessary to design an aircraft's control loops using classic or modern control theories. The use of small-scale aircraft to test the control design of large aircraft is a technique that is receiving attention nowadays [36]. Thus, before performing tests on the target aircraft, tests are performed on a similar, but smaller, aircraft [37], [38]. The aircraft used in the PIL platform is a nonlinear mathematical model of a Piper J-3 Cub ¼ scale [20]. The aircraft model and movement equations were implemented in MATLAB® Simulink®. The Earth was considered an inertial referential. The rigid body dynamic equations of a fixed-wing aircraft, with six degrees of freedom (6-DOF), describe the translational and rotational dynamics. The adopted referential to these differential equations is the body system coordinates (xb, pointing to the aircraft nose; yb, pointing to the right wing, and zb, pointing down). The aircraft is considered to be symmetrical in the xz plane. This consideration simplifies the moment of inertia matrix, for which the elements corresponding to products of inertia are null. To perform a nonlinear simulation of the aircraft, it is also necessary to include expressions to keep updated the aircraft position (xn, yn, zn) and attitude (phi, theta, psi), in the navigation coordinate system (the coordinate system chosen to track the aircraft mission), North-East-Down frame (NED). In this study, the wind effects will be neglected, and the Earth will be represented as a flat surface [39]. A simplified nonlinear model for a 6-DOF aircraft is shown in Figure 3. The atmospheric model used was the International Standard Atmosphere (ISA), but disturbances such as gusts of wind on the three axes of the aircraft are disregarded.
In the implemented model, the aerodynamic coefficients are input parameters to the aerodynamic subsystem. The dynamic system for simulation is given by: where, f represents the rigid body dynamic and g the output equations. The state vector is: where, u, v, and w are the components of velocity in the NED frame, xn, yn, and zn axis, respectively; p, q and r are the angular velocity in the NED frame, xn, yn, and zn, respectively; , θ, and ψ are the Euler angles representing the aircraft's attitude; xn, yn, and zn are the aircraft's coordinate represented in the NED frame. The control vector is: where,  is the variation in throttle; e the deflection in the elevator command surface; a the deflection in the ailerons command surface; r the deflection in the rudder command surface. The output vector: where, VT is the air velocity,  is the angle of attack and  is the sideslip angle. The other elements were defined before.
A dynamic system as presented in (1), with the state vector, command vector, and output vector, may be used to represent a typical fixed-wing aircraft. The parameters used in the dynamic system must be related to the specific aircraft to be simulated. In this way, to implement a mathematical model of an aircraft, it is necessary to know its geometric parameters and aerodynamic coefficients.

A. PIPER J-3 CUB ¼ MODEL
The main geometric parameters of the Piper J-3 Cub ¼ are presented in Table I. The inertia parameters, mass, and moments of inertia matrix use the data given by [41]. The inertia matrix J was computed by the method of approximate numerical integration. In general, in the case of conventional fixed-wing aircrafts, it is assumed that the aircraft is symmetrical related to the xz plane. Where x is the longitudinal axis pointing to the aircraft's nose, z is the axis pointing to the aircraft's belly (both with origin in the center of gravity of the aircraft).
To complete the nonlinear model implementation that describes the aircraft dynamic movement, the aerodynamic derivatives, and control coefficients of the aircraft are necessary. In [20], the parameters of a Piper J-3 Cub ¼ were determined for the aircraft flying in different velocities (VT) by software Athena Vortex Lattice [AVL] and USAF Stability and Control Digital DATCOM. In this work, it was used the aerodynamic derivatives and control coefficients related to VT =20 m/s. Table II lists the parameters used for VT =20 m/s according to [20]. The longitudinal aerodynamic derivatives and control coefficients are: CL0, CD0, CL, CM, CLq, CMq, CLδe, and CMδe.  [39].

B. LINEARIZED LONGITUDINAL AND LATERO DIRECTIONAL MODELS
To design the controllers using classic control theory, it is necessary to linearize the nonlinear model. This can be done with the aircraft in an equilibrium condition. The trim condition considers the aircraft control surfaces set for a straight and leveled flight. In this condition, all translational and rotational accelerations are null, and this equilibrium condition is given by: This condition provides an initial state to the flight simulation, and the nonlinear equations can be linearized. In this work, the trim point in the flight envelop is VT,0 =20 m/s and H0 = 400 m, the aircraft altitude. The equilibrium states and input were computed by MATLAB® and are presented in Table IV.
Using the solution for the equilibrium state, it is possible to linearize the nonlinear mathematic model. The resulting linearized dynamic system is represented as in (6), and this representation can be used for both, longitudinal and Latero Directional modes.
In general, the Δ notation is neglected, but the new x  and u  variables are understood as deviations from the equilibrium. The linearized dynamic system to the Longitudinal mode has the state vector x, the control vector u, and output vector y: The matrices A, B, C and D are computed by MATLAB® using a developed script: The linearized dynamic system to the Latero Directional has the state space vectors: Proceeding in a similar way to the longitudinal case, the state space matrices can be found:

C. STABILITY AND FLYING QUALITIES
It is necessary to evaluate the aircraft's stability and control, and flying qualities before applying classic control theory to design control loops. Stability and control comprehend how an aircraft flies and can be controlled. Flight qualities are the characteristics of stability and control behavior of the aircraft [39].
Once the system is linearized, it is possible to analyze the stability parameters through the poles of the characteristic equation of the system. In addition, control loops with desired behaviors can be obtained by allocating the poles. In order to carry out these analyzes, each linearized dynamic system (Longitudinal and Latero Directional) must be studied according to its flight modes [42].
For the Longitudinal Dynamic, it was considered the: Phugoid Mode (pair of complex poles conjugated closest to the origin); and Short Period Mode (pair of conjugated complex poles furthest from the origin). For the Latero Directional Dynamic, it was considered the: Dutch Rolling Mode (pair of conjugated complex poles); Pure Rolling Mode (real pole in the left semi-plane, very stable); and Spiral Mode (real pole close to the origin, often slightly unstable).

IV. CONTROL LOOP DESIGN
To perform the control loop design of a system, it is necessary to define the requirements. This work uses the flying qualities according to the MILF-8785C specification [29]. This document classifies the aircrafts according to the geometric and inertial parameters. The specifications for the control design consider also the flight phase for which the design is considered. By the MILF-8785C, the Piper J-3 Cub ¼, can be classified as a small, light airplane, class I. Regarding the flight phase, category C is more adequate, since the control flight system proposed has the objective to allows an autonomous flight following a pre-defined trajectory. Finally, once the proposed flight control design should provide a small margin of error, Level 1 flight quality has been adopted. For an aircraft with these classifications, the flight quality specifications are as in Table V.
Using the linearized model, the control loops for the Longitudinal and Latero Directional movements were designed, allowing the system to operate in points or conditions near the equilibrium. The actuators' dynamics were considered ideal, so they were not modeled.
The controllers' design was not the main scope of this work, so, the details will not be presented. The loops and controllers design follow the approach presented in [43]. The simulations in the time domain were performed using MATLAB® Simulink® with the integration routine ode4 (Runge-Kutta) and sample time Ts equal to 10 ms.

A. LONGITUDINAL CONTROL SYSTEM
The longitudinal control design for the Piper J-3 1/4, was designed following [43] and its block diagram is presented in Figure 4. The aircraft is the linearized Longitudinal Dynamic system determined in Section 3. The pitch stability augmentation system (Loop1) is used when the aircraft is in level flight. The velocity control loop (Loop 2) tracks the reference velocity during the flight. It is the combination of the controlled pitch angle mode and the velocity feedback (VT), and a dynamic compensator for the   (Gc,VT). The altitude control system (Loop 3) allows the aircraft to be maintained at a fixed altitude. In the proposed longitudinal controller, the velocity and altitude controllers act in parallel with each other, preventing the control system to perform sudden movements and, after reaching the desired reference values, the aircraft returns to the equilibrium state.
The determination of the compensators' gains considered first Loop 1, and then Loop 2 and Loop 3. The gains of compensators PI (proportional and integral), Gc,θ, Gc,VT and Gc,H were obtained with Matlab's PID Tuner. The kq parameter was designed using the root locus method applied to the transfer function θ(s)/e(s), which can be obtained from the aircraft longitudinal linearized dynamic. To the kVT and kH parameters, it was heuristically assigned a value equal to 1 (one), which means that ideal sensors are being considered for the measurement of altitude and velocity. Table VI shows the designed gains.   Figure 5 shows the temporal longitudinal response in closed-loop, of the designed controllers. The reference used was a 25 m doublet in Hr. The control system switches between the Altitude control and the velocity and pitch angle controls, depending on the flight situation. The switching points are indicated by A switching when the Altitude control assumes the system command, and B switching when velocity and pitch angle control. In case of altitude changing, the Altitude control should be trigged when the aircraft is at a distance up to 5 m from the reference altitude (A switching). Otherwise, the velocity and pitch angle autopilots are triggered until the actual aircraft altitude is 5 m from the reference altitude (B switching).
The simulations in time domain were performed using MATLAB® Simulink® with the integration routine ode4 (Runge-Kutta) and sample time Ts equal to 10 ms. In general, for a UAV, the Latero Directional controller is designed to keep the aircraft pointing in the desired direction (compass heading). To control the yaw angle, a strategy commonly used is to keep the roll angle in a predetermined position until the aircraft reaches the desired reference. Therefore, the conventional method to implement this autopilot is to feedback the yaw angle (ψ) and use the roll angle (φ) autopilot as an internal loop in the yaw angle autopilot.
The Latero directional control design implemented for the Piper J-3 1/4 has the diagram shown in Figure 6 and incorporates the highlighted systems. The Latero directional stability system augmentation (Loop 1) is a combination of roll and yaw stability systems, as these movements are generally coupled. The roll angle control system (Loop 2) acts, in its simplest form, as a wing leveler. Finally, the yaw angle controller uses the roll angle control system as an internal loop to point the aircraft in a certain reference direction.
The aircraft is the linearized Latero directional Dynamic system determined in Section 3. The loops designs are made in sequence, Loop-1, Loop-2 and finally Loop-3. Loop 1 is the Latero directional stability system augmentation, which contemplates stability augmentation of the yaw angle and the roll angle. For yaw stability augmentation using yaw rate feedback, r, the control is performed so that the yaw angle error should be zero, damping the Dutch Roll movement. However, in coordinated flight (turn maneuver), the yaw rate must be constant and non-zero. Thus, to meet these two commitments, a usual solution is to use a washout filter, Gw, with the form: The Latero Directional controller was designed following the proposal of [43]. The gains of the PI compensator, Gc,φ, were obtained with the Matlab PID Tuner. The parameters kp and kr were designed using the Root Locus method, and kφ was chosen equal unit, which means that ideal sensor is being considered for the measurement of roll angle. To calculate φref from the yaw angle, ψ, it was used the expression u0/( g), in which u0 is the nominal velocity of the aircraft (20m/s), g is the gravity acceleration, and equal 1 (a value heuristically assigned). In Table VII the designed gains and some parameters used are presented.
With the Latero Directional control designed, the system behavior was studied. For the designed system, in case of a change in the yaw reference angle, the aircraft should maneuver to reaches the new yaw angle. During the maneuver, the roll angle changes, and when the desired yaw is reached, it returns to the null position, with the aircraft with leveled wings. Figure 7 shows the temporal Latero Directional response in closed-loop for the complete Latero Directional control system. The reference used was a 45 o amplitude doublet in ψr, at t =50 s. The graphics show that the linearized and the nonlinear aircraft models (both using the control system designed using the linearized model dynamics), have a similar response. The yaw angle follows the input reference, ψr, with an accommodation time of 32.50 s.

V. GUIDANCE ALGORITHM
In the proposed AP, the aircraft mission is specified by a waypoint matrix, composed of the geographic coordinates (NED frame) of the points to be reached during the mission and the aerodynamic velocity planed for each waypoint.
The guidance system generates the reference heading angle by accessing the waypoint matrix during the mission, and repeat the processes for each waypoint (WP) in the waypoint matrix. The altitude and velocity are provided in the waypoint matrix, and the guidance system does not need to calculate them.
The guidance algorithm work with the information relative to the next WP to be reached and the current state of the aircraft and generates the references to be used by the control system. As already commented, the implemented algorithm is an adaptation of the one proposed by [32]. It deals with the heading generator, the monitoring and control of the Cross-track error, and the switching waypoint.

A. HEADING GENERATOR
The reference heading angle, the heading for which the aircraft should point, is computed based on the current UAV position (NUAV, EUAV), and its desired position (NWP(n+1), EWP(n+1)), defined by the next waypoint, WP(n+1), both positions given in the NED frame. Consider Figure 8, and a triangle formed by the line parallel to the East axis (NWP(n+1) coordinate), the line parallel to the North axis (EUAV coordinate), and the line connecting the UAV to the WP. In the triangle, ψref is the angle at the vertex in which the aircraft is located. So, ψref is computed as: The reference yaw angle, ref  , is sent as a reference to the AP control system.

B. MONITORING OF THE CROSS-TRACK ERROR
During the straight and level flight, when the aircraft is flying between two WPs (but not maneuvering for a WP switching), to avoid continuous correction in the trajectory and the flight parameters, it is defined a region around the segment connecting the two waypoints in which region no correction is executed. In this way, yaw angle corrections are imposed only when the UAV cross-path error is greater than an assigned value, i.e. the maximum acceptable transversal error [33]. The region where no correction is done is defined as an isosceles trapezoid, whose axis of symmetry is defined by the segment that connects a waypoint to the next one (WPn to WP(n+1)), Figure 9. The distance between the two WPs is ds, P_ref point is the projection of the aircraft's position on the line connecting the two consecutive waypoints; d_ref is the distance from P_ref to the next waypoint; and r  is the cross-track error and K and  are intermediate variables.
The maximum acceptable cross-track error, max  , is variable and decreases over segments a and b (longer and shorter bases). Consider Figure 8. The inclination of a leg of the isosceles trapezoid can be computed as: By triangle likeness: And then, the maximum acceptable cross-track error, max  , is given by: Figure 9. Cross-track error and the region where no correction is done. Adapted from Capelo 2017.
If the UAV cross-track error is less than max  during the direct flight phase, no correction to the aircraft heading should be made. Otherwise, if max r    , the new reference direction angle will be the angle between the current UAV position and the next WP, computed by the heading generator.
When the distance between the aircraft and the next waypoint is smaller than the minimum distance defined, it is considered that the WP was reached. Then, the aircraft now should be led to the next WP, and the guidance system switches to the next point in the waypoint matrix.

VI. EMBEDDING THE AP IN A MICROCONTROLLER
The validation of the guidance algorithm and the control laws which run in the microcontroller was performed in a PIL simulation environment. The test platform was implemented using the LM3S6965 microcontroller, an ARM® based controller [45].
To implement the AP in the hardware, it was necessary to define a communication protocol for data exchange among modules. It consists of a header and a terminator that indicate the beginning and end of transmission; a register that defines what information will be transmitted and a data set with the information to be transmitted.
In order to implement the control system developed in continuous time domain, it is necessary to discretize the control. The difference equations were determined by using the discrete equivalent technique, with a bilinear transformation (Tustin Method). The sampling period to solve the non-linear equations that describe the dynamics of the aircraft's movement was Ts = 0.01 s, the same used in SIMULINK.

A. PIL TEST PLATFORM
The defined data packet structure establishes communication between Simulink and the microcontroller platform. A local area network between the embedded AP and the simulated aircraft was created using Ethernet ports, and a specific IP address for each device was assigned.
During each step of simulation of the aircraft model, the input and output data interface is responsible for receiving and decoding the data packet sent by the microcontroller. In the codification and decodification of the data packets, it was used the S-Function Builder, a Simulink® block able to integrate codes in C/C++ Programming Language.
For the Reception and Decryption of the Data Pack coming from the microcontroller, the interface uses the UDP Receive block available in the Instrument Control Toolbox™. Then, it decodes (unpack) and makes the received variables available for subsequent processing of the nonlinear simulation model.
The data entry interface implemented in the test platform is responsible for receiving the data packets sent by the microcontroller, decoding, and making the received variables available for subsequent processing of the nonlinear simulation model. The Simulink® blocks used in the implementation of this interface are shown in Figure 10. The UDP Receive block configures and opens an interface for a specific IP address using the UDP protocol. The Unpack block is responsible for dividing the received data packet into a one-dimensional vector. The Byte Reversal block performs the necessary inversion in the order of bytes, since the microcontroller uses the big-endian data format and the MATLAB® uses the little-endian. The S-Function Builder block is responsible for decoding the data packet received from the hardware, which was assembled using the defined data packet structure for the communication between Simulink and the microcontroller platform.
In summary, at each simulation step, the routine for data input is called and then analyze the structure of the received data packet, group the bytes, extract the values of the variables being transmitted, and, finally, make these variables available to the input vector of the aircraft simulation model.
For the encoding and sending the data package to the microcontroller the data output interface implemented in the test platform, is responsible for coding and sending the data packet to the microcontroller. The data packet sent, in each simulation step, must contain the output vector variables of the aircraft nonlinear simulation model. The Simulink® blocks used in the implementation of this interface are shown in Figure 11.

Byte Reversal Pack
In UDP Send Figure 11. Simulink ® block diagram for encoding and sending the data package to the microcontroller.
The Data Type Conversion block is responsible for converting the variables to be sent, from the doubleprecision to the single-precision floating-point format. The S-Function Builder block is responsible for converting the output vector variables from the non-linear aircraft simulation model. The Pack block is used to convert the received one-dimensional vector into a data packet with 77 bytes in sequence. Finally, the UDP Send block is responsible for sending the data packet to the AP embedded in the microcontroller, to the specified IP address and local port, using the UDP protocol. The responses of the aircraft controlled by the control loops embedded in the microcontroller are very close to those performed by the continuous time control loops, indicating that the discrete control was performed satisfactorily. The final test of the designed control block is done when embedding the AP (control and guidance blocks) to perform a mission.

VII. PIL MISSION TESTS
The missions defined to tests are those in which the UAV must pass through predetermined geographical coordinates, or waypoints. These missions were simulated to assess the performance of the guidance and control systems developed in this work.
The results obtained with the PIL simulations performed using the developed test platform will be presented. Three missions were executed with the UAV traversing trajectories of predefined waypoints.
After reaching the last desired point, the mission is considered completed and the simulation is ended. The mapping of the desired waypoints, for each trajectory, in the local navigation coordinate system (NED frame) is shown in Table VIII. The definition of the waypoints was done in the MATLAB® environment.  The autopilot interacts with the aircraft simulation dynamics implemented in MATLAB® Simulink® environment, which employs the ode4 simulation algorithm (Runge-Kutta method) with a sampling period equal to 0.01 s. The simulations consist of performing flight trajectories considering the following conditions: • The atmospheric model does not take into account disturbances such as gusts of wind on the axes of the aircraft; • The mathematical modeling and the inertial and geometric parameters do not present errors; • The sensors do not have typical errors such as bias, scale factor, and nonlinearity. Figure 13 shows the platform in execution. During the execution of the PIL platform, twenty-four libraries were used in the code embedded in the microcontroller, for instance "lib/gpio.h", "lib/ethernet.h", "app/eth/eth_udp.h" for communication. For the missions presented in the article, the execution time in Matlab was, on average, 559 s for the microcontroller running at 50MHz. The codes necessary to reproduce the proposed platform as presented in this paper, with a short video showing the platform being executed, are available as a supplementary material posted with this article.
The codes to reproduce the proposed platform in microcontrollers from the Arduino family, specifically the microcontrollers ATmega328P (Arduino UNO) from Microchip, Stm32f103c8 from STM Microeletronics, Esp8266 and Esp32 from Expressif Systems, are also available as a supplementary material posted with this article. A. TRAJECTORY A Figure 14 presents the result after the simulated mission, where it is possible to verify that the aircraft has traveled all the pre-defined waypoints for Trajectory A. The simulation starts at Waypoint 1 (WP1) and ends at Waypoint (WP7). The aircraft traveled a route of approximately 7 km in total length and the duration of the mission was 5 min and 58 seconds (358 s). The figure also shows the responses for the aerodynamic velocity, altitude, and yaw angle of the aircraft. These are variables affected by the reference signals generated by the guidance system during the simulation and tracked by the designed control system. Notice that Trajectory A is a bidimensional trajectory, given that there is no variation in altitude. Figure 15 shows the result after the simulated mission showing that the aircraft has traversed all the pre-defined waypoints for Path B. The simulation starts at Waypoint 1 (WP1) and ends at Waypoint (WP7). The aircraft traveled a route of approximately 11 km in total length and the duration of the mission was 9 minutes and 22 seconds (562 s). The figure also shows the aircraft's airspeed, altitude, and yaw angle responses. As already commented, these are variables affected by the reference signals generated by the guidance system during the simulation and tracked by the designed control system.

B. TRAJECTORY B
In Trajectory B mission, there is altitude variation. In the aerodynamic velocity response, it is observed that, even though the reference velocity is constant, the velocity of the aircraft is not. This is because there are coupled movements in the aircraft dynamic. Changing altitude, the aircraft will change velocity. The velocity control was designed to keep the velocity as constant as possible. The results show that the error between the reference velocity and the aircraft velocity was less than 14% in two points of the trajectory. During most part of the flight, the velocity error is less than 5%. The altitude and yaw angle responses indicate that the aircraft performed the predetermined mission autonomously.
C. TRAJECTORY C Figure 16 shows the result after the simulated mission, where it is possible to verify that the aircraft has traversed all the pre-defined waypoints for Trajectory C. The simulation starts at Waypoint 1 (WP1) and ends at Waypoint (WP7). The aircraft traveled a route of approximately 8 km in total length and the duration of the mission was 6 minutes and 23 seconds (383 s). The figure also shows the aerodynamic velocity, altitude, and yaw angle of the aircraft, corresponding to the reference signals generated by the guidance system during the simulation and tracked by the designed control system.   In the Trajectory C mission, there is also altitude variation Similar to Trajectory B, the maximum aerodynamic velocity error was 16%, remaining less than 5% during most of the flight. In trajectory C, the yaw angle suffers a decrease in its value, a maneuver that was not done in the previous missions. As before, in Trajectory C the aircraft fulfilled the mission.

VIII. CONCLUSION
The stages of development for control and guidance blocks of an AP for a fixed-wing aircraft were presented. The implementation of a PIL test platform is carried out, by implementing the developed AP in a microcontroller, executing the aircraft model on a PC and establishing the communication between these two elements. Thus, the AP is responsible for piloting the simulated aircraft, leading it to perform a mission established by WPs. Tests on the PIL platform were presented, in which the aircraft performs the missions, reaching all the WP previously defined. The tests presented indicate the success of the developed AP project, as well as the functionality of the implemented PIL platform.
In this work, we consider an AP consisting of three blocks: navigation, guidance, and control. These blocks were developed in a modular way allowing individual modifications.
The design of control loops using classical control theory needs the aircraft's mathematical model, and a Piper ¼ scale mathematical model was employed. As design parameters, the MILF-8785C standard was used (since flight quality standards for autonomous aircraft are not yet fully established). For the design of the control loops, the linearized model was computed for a fixed speed. However, if it is desired to work with the aircraft in different flight conditions, linearization at different flight conditions can be performed, control loops for each condition can be designed and then bank of controllers can be used during the flight mission, in which each controller is used in the respective flight condition for which it was designed. The bank of controller may be implemented in the platform and the PIL test may be performed. The guidance block was performed using an algorithm available in the literature. No algorithms have been implemented in the navigation block, however, the block structure is present, available for use.
The PIL platform implemented can be used for designing an AP for another aircraft model. For this, it will be necessary just substitute the present model by mathematical model of the desired aircraft since the communication between microcontroller and PC is carried out. If the new aircraft is fixed wing, the control loop's structure can be used, being necessary just to design the controllers based in the new mathematical model. As the development of the PA was done in a modularized way, the implementation of new functionalities in one block is possible without changing other blocks. As the proposed platform is of low cost and can be used for the development of several algorithms, even though it is not possible to accurately estimate the cost effectiveness, it is understood that it is adequate given the time savings and accident prevention, as a bench test stage.
There is a work in progress related to the navigation block. Models of sensor errors are being introduced and algorithms for filtering the signals provided by them will be implemented in the navigation block. As a possible future work, the problem of detecting and avoiding obstacle can be addressed. For this, it must be developed the introduction of obstacle information, and sensors to detect these obstacles must be implemented in the navigation block. In the guidance block, an algorithm to use the information of the obstacle detection should be developed, so that the resulting AP will be capable of altering its mission during the flight. The evolution of the platform to a real-time system is being planned. The first step to be taken in this direction will be the use of Matlab's real time pacer function, to synchronize its time with the real time elapsed. For the real-time system, a more detailed study of aspects such as runtime and computational complexity will be made.
Since the PIL tests are always one of the last tests to be carried out before flight tests, it is considered that the developed PIL test platform is very useful for groups working with the development of PAs for autonomous aircraft.