Co-Design of a Controller and Its Digital Implementation: The MOBY-DIC2 Toolbox for Embedded Model Predictive Control

Several software tools are available in the literature for the design and embedded implementation of linear model predictive control (MPC), both in its implicit and explicit (either exact or approximate) forms. Most of them generate C code for easy implementation on a microcontroller, and the others can convert the C code into hardware description language code for implementation on a field programmable gate array (FPGA). However, a unified tool allowing one to generate efficient embedded MPC for an FPGA, starting from the definition of the plant and its constraints, was still missing. The MOBY-DIC2 toolbox described in this brief bridges this gap. To illustrate its functionalities, the tool is exploited to embed the controller and observer for a real buck power converter in an FPGA. This implementation achieves a latency of about $30~\mu \text{s}$ with the implicit controller and 240 ns with the approximate explicit controller.


I. INTRODUCTION
L INEAR model predictive control (MPC) [1], [2] is a model-based approach for the regulation and tracking of linear systems with multiple inputs and outputs, subject to affine inequality constraints.The traditional (implicit) formulation requires solving a quadratic programming (QP) optimization problem at each sampling time, which can be time-consuming and then not applicable for systems with very fast dynamics [3].For piecewise-affine (PWA) systems subject to mixed linear/logical constraints, the MPC optimization problem can be formulated as a mixed-integer QP [4].Explicit MPC [5] moves most of the computation offline, and the online computation of the control action (both for linear and PWA systems) reduces to the evaluation of a PWA function, which significantly reduces the computational effort.Many approximate explicit control functions have also been proposed [6], [7], [8], [9], [10], which can contribute to further increase the controller update rate.The common drawback of all the explicit solutions is the rapid growth of the number of parameters as the dimension of the system increases, due to the so-called curse of dimensionality [11].Some solutions have been proposed in the last decade for fast and efficient implementation of implicit [12], [13], [14] and explicit [15], [16], [17], [18] MPC on different platforms, including microcontrollers and field programmable gate arrays (FPGAs).
In the control literature, the implementation aspects and the corresponding support tools for creating real-time embedded controllers receive rather limited attention, while for practical applications these are of course crucial.In this brief, we present a second release of the MOBY-DIC 1 toolbox (briefly, MOBY-DIC2), 2 which extends the functionalities of the former version (MOBY-DIC1) [19].This toolbox supports the co-design process of a controller and its digital implementation, enabling easy deployment of MPC-based control solutions for real-time applications.MOBY-DIC2 is a MATLAB toolbox based on object-oriented programming, which allows carrying out the entire MPC design flow, from the definition of system dynamics and constraints to the embedded architectures, including implicit/explicit, exact/approximate MPC, and supporting both the microcontroller and FPGA implementations of the controllers and observers.The main strength of MOBY-DIC2 is the automatic generation of efficient VHDL 3  code, by setting the level of parallelism, the number of bits for the fixed-point representation of inputs, outputs, and coefficients, and the scalings to automatically interface with analog-to-digital and digital-to-analog converters (ADCs and DACs).To demonstrate all the functionalities of MOBY-DIC2, embedded architectures implementing implicit, explicit, approximate MPC controllers, and Kalman filters are generated for a switching buck converter.Processor-in-the-loop (PIL) simulations and tests on a real converter prototype are provided, showing the strengths and capabilities of the tool.

II. SURVEY ON AVAILABLE TOOLS
Several free and commercial tools are available to help the user in designing and/or implementing linear 1 Acronym of the FP7 European Project "MOdel-Based sYnthesis of DIgital electronic Circuits for embedded control" FP7-ICT-2009-4 (2010-2012).
2 Available online at https://github.com/COMPsys-UNIGE/MOBY-DIC 3 Very high-speed integrated circuit hardware description language.implicit/explicit MPC.The main ones are summarized in Fig. 1, which lists all the steps necessary to generate and simulate an embedded MPC controller.Starting from the definition of the system and constraints, an implicit MPC controller can be designed, for linear or PWA systems.An explicit (either exact or approximate) solution can then be computed.When the system state is not completely measurable, a state observer must also be designed.C and VHDL code must then be created for implementation of the controller and observer on a microcontroller or an FPGA, respectively, or to perform PIL simulations involving a computer running the plant model (not in real-time) and an embedded device implementing the controller and/or the observer.We now briefly describe the tools listed in Fig. 1 from left to right.
PROTOIP [26] provides a MATLAB interface to Xilinx Vitis high-level synthesis (HLS), allowing for the generation of an embedded circuit on a heterogeneous (microcontroller + FPGA) computing platform (in particular, Xilinx Zynq System on Chip) starting from an algorithm described in the C language.PROTOIP allows performing PIL simulations, using MATLAB and a Zynq board, and evaluating the circuit performances within MATLAB environment.
SPLIT [27] is a tool with a MATLAB interface for the generation of embedded implicit linear MPC, based on splitting algorithms, including the alternating direction method of multipliers (ADMM).Based on the matrices and constraints defining the QP optimization problem, a C code is generated for implementation on the microcontroller or, through PRO-TOIP [26], on heterogeneous computing platforms.
µAO-MPC [28] is a Python tool (with MATLAB interface) that allows generating C code for embedded implicit MPC starting from the definition of the system to regulate.
The hybrid toolbox [29] and multiparametric toolbox (MPT3) [30] are MATLAB tools that allow generating explicit MPC for linear and PWA systems.The hybrid toolbox also provides C files that can be deployed on the microcontroller.
ODYS Embedded MPC [31] uses a specific version of ODYS QP Solver [24] optimized for MPC applications and allows generating C code with industrial standards for very fast embedded implementation of implicit linear, linear timevarying, and nonlinear MPC and related state observers.PIL simulations can also be carried out.
MOBY-DIC1 allows designing, simulating, and implementing on FPGA explicit exact and approximate MPC, whereas the MATLAB MPC Toolbox [32] allows auto-generating C code from Embedded MATLAB functions for microcontroller implementation of both implicit and explicit (exact and approximate) MPC, based on the multiparametric solver described in [33].State estimators can also be designed and implemented, and PIL simulations are available.However, the MPC toolbox does not support code generation for FPGA implementation.MOBY-DIC2 fills this gap, by extending the functionalities of MOBY-DIC1.It embeds a top-level interface for the following tools, whose invocation is transparent to the user: MPT3 for the design of explicit MPC, Xilinx Vitis HLS for the generation of VHDL code of the implicit MPC, and Xilinx model composer and system generator for the PIL simulations, including Simulink and an FPGA.MOBY-DIC2 is compatible with both MPT3 and MPC toolbox, since an MPC controller previously generated with one of these tools can be easily imported in MOBY-DIC2 for FPGA implementation or PIL simulation.

III. LINEAR MPC
In this section, we briefly describe the formulation of MPC [1], [2] used within the MOBY-DIC2 toolbox for linear time-invariant (LTI) systems.We consider a dynamical system whose states, inputs, measurable parameters, unmeasurable disturbances, and outputs are denoted as and y ∈ R n y , respectively.The MPC controller aims at bringing the system state or output to a constant (regulation problem) or time-varying (tracking problem) reference r .All these variables are gathered in a vector z = [x T u T p T d T y T r T ] T .We use a subscript k to indicate the value of a variable at a discrete time instant kT s , where T s is the sampling period, and a subscript k + i|k to indicate the predicted value of a variable at time (k + i)T s , based on its value at time kT s , k ∈ N, i ∈ N. Starting from measurements or estimations of x k , p k , d k , and r k , . . ., r k+N (only for tracking problems), the MOBY-DIC2 toolbox allows generating linear MPC by solving the following optimization problem with a receding horizon approach: Authorized licensed use limited to the terms of the applicable license agreement with IEEE.Restrictions apply.
Within MOBY-DIC2, p and d are measured/estimated at every sampling instant and assumed to remain constant within the prediction horizon (i.e., p k+i|k = p k , and the same holds for d).In this optimization problem, expression (1a) contains the quadratic cost function to be minimized at time kT s , where is the time horizon where the constraints are imposed, Q = Q T and P = P T are the positive-semidefinite weight matrices, and R = R T is a positive definite weight matrix.The terms σ i (i = 0, . . ., N c ) are slack vectors of soft constraints.We have e k+i|k := x k+i|k − r k+i for state regulation/tracking problems, whereas e k+i|k := y k+i|k − r k+i for output regulation/tracking.Finally, ϵ k+i := u k+i − r u , where r u is the input reference.For tracking problems, an augmented model is automatically generated to achieve offset-free tracking [34], in which u k−1 becomes a system state with dynamics u k = u k−1 + u k , where u k is the new system input.Therefore, r u = 0.
The affine time-invariant prediction model is given in (1b)-(1c), whereas inequality (1d) represents the affine inequality constraints at each time (k + i)T s .Matrix i is diagonal and contains zeros or ones, indicating whether the corresponding constraint is hard or soft, respectively.Finally, (1e) fixes the input (control) for time instants outside the control horizon.
Within MOBY-DIC2 toolbox, MPC and state observers can also be designed and implemented for PWA systems, with a switching approach, i.e., a different controller/observer is designed for each system dynamics [35], [36].
IV. MOBY-DIC2 FUNCTIONALITIES Fig. 2 shows the main design flow of the MOBY-DIC2 toolbox for LTI systems.The green boxes represent the toolbox inputs, whereas the orange ones the outputs.

A. Controller Design
The first step for MPC design is to define the prediction model (1b)-(1c) and the affine inequality constraints.The model can be represented either in discrete or continuous time.In the latter case, it is automatically converted into a discrete-time model with a sampling time T s , specified by the user.If the controller latency is higher than T s , the update time T ctrl of the controller can be set as a multiple of T s .This means that only for the prediction phase, the LTI system is re-discretized with sampling time T ctrl .Both hard and soft constraints can be imposed for any variable at any prediction instant.The MPC parameters appearing in problem (1) are then set within a MATLAB structure, and an object representing either an implicit or an explicit MPC controller is created.We remark that the controllers can also be created using MPT3 or MPC toolbox and then converted into MOBY-DIC2 objects.
With the implicit controller, problem ( 1) is recast as a standard constrained QP with a sparse formulation, i.e., min Additional details regarding the construction of the matrices can be found in [37].MOBY-DIC2 solves problem (2) at each control interval T ctrl by resorting to either the MATLAB function quadprog or the ADMM algorithm [38].As better described in the following sections, code generation is supported only for ADMM, whereas quadprog can be used for software simulation purposes.
The explicit MPC controller is generated by invoking the MPT3 toolbox, which solves problem (1) through multiparametric QP.Then, the control action u k is represented as u k = f pwa (x k , p k , d k , r k , . . ., r k+N ), where f pwa is a PWA function defined over a generic polytopic partition, like the one shown in Fig. 3 (left).MOBY-DIC2 allows also approximating the function f pwa with another PWA function defined over a regular simplicial domain partition [6] (Fig. 3, right), to obtain lower computational effort and allowing to decrease the system sampling time.An object representing an approximate MPC controller can be created by specifying the number of partitions for each domain dimension.

B. Observer Design
Kalman filters and predictors can be easily created to estimate the system state and unmeasurable disturbance of an LTI system, by providing a process covariance matrix Q K , a measurement covariance matrix R K , and an observer sampling time T obs , which, for the reasons explained in Section IV-A, can be a multiple of the system sampling time T s .Summarizing, the relationship between the system sampling time T s , observer sampling time T obs , and controller sampling time T ctrl is T ctrl = αT obs = αβT s , where α and β are positive integer numbers.The Kalman observers are designed through the MATLAB function kalman, to obtain Authorized licensed use limited to the terms of the applicable license agreement with IEEE.Restrictions apply.

C. Embedded System Design
This functionality represents the main strength of the tool.The designed controller and observer can be set as internal properties of the LTI system object, to create a closed-loop system including the Kalman filter.An embedded system object can then be created, representing the circuit to be implemented in a microcontroller or FPGA.The block scheme of the embedded system is shown in Fig. 4; the green rectangle represents the hardware architecture generated by MOBY-DIC2, to be implemented in an FPGA or microcontroller (red rectangle).The controller and the observer can also be implemented individually.The circuit is thought to get the reference r k , . . ., r k+N (in case of tracking problems), the parameter p k , and the outputs y k through ADCs in a given range, which can be set within MOBY-DIC2, typically [0 4095] for 12-bit ADCs.These values are converted into the correct range through linear scalings, performed by SCALE blocks, and provided to the controller and observer, as shown in the figure.The control output u k is scaled to the DAC range.
For implicit MPC, the ADMM algorithm [38] is exploited by the circuit.ADMM steps are simple to implement and computationally very cheap, which makes this algorithm particularly suitable for implementation in embedded devices with limited computing resources [12].The main linear algebraic operation in each step is matrix-vector multiplication.In addition, there is no data dependence between the optimization variables in an iteration; this allows for the processing of each optimization variable in parallel, thus making ADMM particularly suitable for FPGA implementations [38], [39], [40].Also, QPGEN, OSQP, and SPLIT tools use the ADMM algorithm for the generation of C code.For FPGA implementation, two architectures can be generated: a fast one, which exploits parallelism to perform matrix-vector products, thus achieving a low latency at the cost of more hardware resources, and a small one, with higher latency and lower resource utilization.A fixed-point representation of data is chosen, where the user can set the number of bits.Also, the number of bits of ADC and DAC can be arbitrarily set.The toolbox creates C++ code, which is automatically converted into VHDL code through Vitis HLS, without any user intervention.In this case, also the VHDL code of the observer is generated through Vitis HLS.
For explicit and approximate MPC, the circuit architectures described in [16] are implemented.Also in this case, for FPGA implementation, a serial architecture and a parallel architecture are available, to trade off circuit size and latency.In this case, the code is generated directly in VHDL language.
C code can also be generated for microcontroller implementation of all kinds of controllers and observers, by exploiting the same algorithms used for the FPGA, with a floating point data representation.In this case, it is not possible to choose between serial (small) and parallel (fast) architectures.

D. Simulations
The MOBY-DIC2 toolbox allows performing different kinds of simulations of the closed-loop systems including all types of controllers and observers.The simplest simulation runs directly in MATLAB.The plots of the time evolution of all the measured and estimated variables are automatically generated.A Simulink model can be created for interactive simulations, where references and parameters can be varied online.Also, the plant model can be replaced by a more accurate one, which is often useful (as in the example shown in this brief) since the prediction model used to design the MPC controller may be simpler than the plant model used for simulation.MOBY-DIC2 interfaces also with Xilinx Model Composer and System Generator to generate the Simulink models for PIL simulations, as the one shown in Fig. 5, where the embedded system (controller and observer) runs on an FPGA connected to the computer.The scaling blocks for adapting the signals to the ADC and DAC ranges are also generated.This allows evaluating the effects of delays and quantization errors due to ADCs and DACs and fixed-point representation of data.The snippet of code in Fig. 6 shows how the main MOBY-DIC2 functionalities can be invoked with a few commands.

A. Experimental Results on a Buck Converter
The MOBY-DIC2 toolbox was used to generate different embedded systems (including different types of MPC controllers and a Kalman predictor) to be implemented on FPGA to regulate a real buck converter.A buck converter (see Fig. 7) is a switching DC-DC converter that allows transforming an input DC voltage v in to a lower DC output voltage v out .The circuit is composed of an inductor with voltage v and current i, a diode with voltage drop v d , an MOS transistor operating as a switch, an output capacitor, and a load absorbing a current i out .R L indicates the parasitic resistance of the inductor.The Authorized licensed use limited to the terms of the applicable license agreement with IEEE.Restrictions apply.The buck converter is a switching system, consisting of two states: when the PWM signal is high, the MOS conducts current (on phase); when the PWM signal is low, the MOS does not conduct (off phase).We assume that the converter always works in continuous conduction mode, i.e., with i > 0, with state equations as follows: where s = 1 in on phase and 0 in off phase.The goal of the controller is to set the duty cycle δ of the switch such that the average value of the output voltage (which is subject to some ripple) tracks a reference value vout,ref , by fulfilling hard constraints i ≤ i max and δ min ≤ δ ≤ δ max .The values of parameters and constraints are summarized in Table I.
The nonlinear model ( 3) can be used to simulate the converter, but is not suitable as a prediction model for linear MPC.To this aim, a linear averaged model can be derived [41], [42].By considering an augmented system, the averaged linear model can be written in discrete-time version as follows: where T s = 1/ f ≈ 33.3 µs.By assuming v in as a constant, this model is in the same form as model (1b)-(1c), where x = [ī vout δ], u = δ, p = i out , and y = vout , which can be assumed to be equal to v out (small-ripple approximation [42]) and then easily measured on the circuit.The average current ī must be instead estimated through a Kalman filter.
The inductor current i does not appear in model ( 4), and then the constraint on the inductor current must be reformulated in terms of the variables available in the prediction model.The inductor current is subject to a ripple, which can be evaluated, based on circuit equations, as δ(v in − v out )/(2 f L) [42].The constraint i ≤ i max can then be approximated as ī + δ(v in − vout )/(2 f L) ≤ i max .If δ is replaced by its maximum value δ max , the constraint becomes more conservative, but can be written as in expression (1d).This state constraint is imposed only at the prediction instant (k +1)T s , whereas input constraint δ min ≤ δ ≤ δ max is imposed only at the current instant kT s .
Implicit, explicit, and approximate MPC controllers were designed with T ctrl = T s , i.e., with α = β = 1.The PWA function defining the explicit controller is defined over a 5-D domain partitioned into six polytopes.The approximate controller was generated by partitioning the domain into regular simplices, with nine partitions along the state and reference dimensions and one partition along the parameter dimension.
The Kalman predictor for the estimation of ī was designed with T obs = T s starting from the averaged model ( 4), by setting a process covariance matrix Q K = diag(0.1,0.1) and a measurement covariance R K = 0.1.

B. Circuit Design
Three embedded system objects were created, including the Kalman predictor and the three designed MPC controllers.For each of them, available circuits were generated and implemented on a Zynq-7000 XC7Z020-1CLG484C FPGA, with a clock frequency of 50 MHz.
Explicit controllers use a 12-bit fixed-point representation, implicit controllers use an 18-bit fixed-point representation, whereas 12 bits were set for ADC and DAC.Table II shows the number of used look-up tables (LUTs), flip-flops (FFs), block random access memories (BRAM), and digital signal processors (DSPs) for all the circuit architectures.The percent values are relative to the total available resources in the Zynq board.Also, the circuit latency and estimated average power are listed.As expected, the approximate explicit MPC controller has the lowest latency, about two orders of magnitude lower than the sampling time T s , with a very low resource utilization.An even smaller, but slower, circuit is obtained with the explicit MPC controller.Due to the high level of parallelism, the latency of the fast implicit solution is still lower than T s at the cost of a much higher resource occupation (especially DSP) and power consumption.If parallelism is not exploited (see the last row of Table II), the latency is much higher than T s and the architecture cannot be exploited in real experiments.We remark that the latency value shown in the table is only related to the embedded system computation; a further delay of 1.46 µs must be added due to the ADC conversion of measurements.

C. PIL Simulations
A Simulink model was generated with MOBY-DIC, combined with the Xilinx Model Composer and System Generator, to perform PIL simulations (see Fig. 5).The state-space model automatically generated by MOBY-DIC2 is the linear prediction model used for MPC design.We replaced it with the nonlinear model (3) to get a more accurate simulation of the converter.The Zynq board implementing the implicit fast architecture was connected to the PC, and the simulation results are shown in Fig. 8.The top panel of the figure shows the time evolution of v out (blue), the value of vout estimated by the observer (red), and the reference output voltage (black, dashed).The middle panel shows i (blue), the estimated value of ī (red), and the bound i max (gray).Note that the current ripple visible in the blue profile is not estimated by the observer, which is designed based on the averaged model.The black dashed line is the output current i out .The bottom panel shows the evolution of δ (blue) and its bounds (gray).
The digital circuit correctly estimates ı and v out through the Kalman predictor and regulates v out to the variable reference v out,ref , even if the parameter i out changes.At the beginning, the controller brings v out to 1.8 V in about 4 ms.After 7.5 ms, the reference voltage is set to 3.3 V (left black boxes), and after 12.5 ms, the output current i out is varied from 0.8 to 1.2 A (right black boxes).The constraints are always satisfied.

D. Experiments
The FPGA implementing the fast implicit controller was connected to a real buck converter and we used the same scenario as for the PIL simulation.The constant input voltage is applied through a BREMI BRS 55 power supply, whereas the time-varying output current is set through a PEL 3031E DC electronic load.The output voltage and load current are acquired through ADCs, whereas the output voltage reference is changed from 1.8 to 3.3 V through a switch in the Zynq board and is, therefore, an internal digital signal.The controller's output δ is provided to a block described in VHDL code generating the PWM signal to be applied to the MOS of the buck converter.An LTS 6-NP Hall-effect probe was used to acquire the inductor current through an RIGOL DS1000Z oscilloscope, together with the output voltage v out and the PWM signal.Fig. 9 shows portions of the experimental results corresponding to the black rectangles in Fig. 8, i.e., during the changes in operating conditions.The experiment was repeated using two different control systems generated by MOBY-DIC2 and implemented on the FPGA: in one case, implicit MPC was used, and in the other, approximate explicit MPC was used.A Kalman predictor generated by MOBY-DIC2 was also used.The top panels show v out and v out,ref , the middle panels i, i out and i max , and the bottom panels δ, which is reconstructed in MATLAB starting from the measured PWM signal and its bounds.Note that in all the cases, the regulation is successful and the measured results are similar to the simulated ones.
Authorized licensed use limited to the terms of the applicable license agreement with IEEE.Restrictions apply.

VI. CONCLUSION
Controllers based on implicit, explicit, and approximate MPC, including a state observer, were designed and implemented on a Zynq-7000 FPGA for the regulation of a real switching buck converter.Explicit MPC controllers need limited hardware resources and achieve latencies of hundreds of nanoseconds, whereas the parallel implicit version requires much more resources (especially DSPs) with a latency of tens of microseconds.A smaller, yet too slow, circuit implementing implicit MPC has also been designed.
Without MOBY-DIC2, the same experiments would have required multiple tools (e.g., the MPC toolbox and PROTOIP), which are not guaranteed to be fully compatible and possibly require some manual modification to the generated code.MOBY-DIC2 allowed instead to carry out the whole design, simulation, and implementation process, by generating different control strategies and circuit architectures and comparing their performances.MOBY-DIC2 has proven to be an effective tool for control-circuit co-design and co-simulation.
Different QP solvers can possibly be added to MOBY-DIC2 for simulation and/or implementation purposes.The functionalities could also be extended to nonlinear MPC, which is possible due the fact that several circuit architectures are already available in the literature for the solution of nonlinear constrained optimization problems [43], [44], [45].

Fig. 1 .
Fig. 1.Functionalities of available tools.Commercial tools are marked with an asterisk.MPC toolbox is part of MATLAB.

Fig. 3 .
Fig. 3. Two-dimensional domain partitioned into generic polytopes (left) regular simplices (right), with seven and four partitions along the first and second dimensions, respectively.

Fig. 4 .
Fig. 4. Block scheme of the MOBY-DIC2 embedded system (green box) to be implemented on a digital device (red box).
MOS transistor is driven by a pulsewidth modulation (PWM) signal with frequency f and duty cycle δ ∈ [0, 1].

Fig. 9 .
Fig.9.Experimental results with implicit (green) and approximate MPC (magenta).Top panels: output voltage v out and its reference v out,ref (black dashed); middle panels: inductor current i, output current i out (black dashed), and constraint i max (gray); bottom panels: duty cycle δ and its bounds (gray).Cases 1 (left panels) and 2 (right panels) correspond to the black rectangles in Fig. 8. (a) Case 1.(b) Case 2.

TABLE II CIRCUIT
RESOURCE USAGE, LATENCY, AND POWER WITH ALL DIFFERENT CONTROLLERS