Technische Universität Clausthal Institut für Elektrische Informationstechnik Rapid Control Prototyping Using an STM32 Microcontroller BACHELORTHESIS CÁNDIDO OTERO MOREIRA Matrikelnummer: 461108 Betreuer: Erstgutachter: Zweitgutachter: Dipl. -Ing. Pablo Ballesteros Prof. Dr.-Ing. Christian Bohn Prof. Dr.-Ing. Christian Rembe Erklärung Eidesstatliche Erklärung Ich erkläre hiermit eidesstattlich, daß ich die vorliegende Arbeit selbständig und ohne fremde Hilfe angefertigt und alle Abschnitte, die wörtlich oder annähernd wörtlich aus einer Veröffentlichung entnommen sind, als solche kenntlich gemacht habe. Ferner, daß die Arbeit noch nicht veröffentlich und auch keiner anderen Prüfungsbehörde vorgelegt worden ist. Clausthal-Zellerfeld, den 28. August 2015 CONTENTS 1 Introduction ............................................................................................................................1 1.1 Introduction to Code Generation .....................................................................................2 1.2 Introduction to Model-Following Control .......................................................................3 1.2.1 The Plant ...................................................................................................................4 1.2.2 State-Space Representation .......................................................................................4 1.2.3 The Controller: State-feedback .................................................................................5 1.2.4 The Model-Following Perspective ............................................................................6 2 Hardware ................................................................................................................................7 2.1 Motor ...............................................................................................................................7 2.1.1 Motor diagram ...........................................................................................................7 2.1.2 Ports ...........................................................................................................................8 2.1.3 Sensors Specifications ...............................................................................................9 2.1.4 Technical Motor Specifications ................................................................................9 2.2 Microcontroller ..............................................................................................................10 2.2.1 Getting Started.........................................................................................................10 2.2.2 Features overview ...................................................................................................11 2.2.3 ADC and DAC peripherals .....................................................................................11 2.2.4 USARTs and UARTs peripherals ...........................................................................13 3 Code Generation ..................................................................................................................14 3.1 Requirements for Rapid Prototyping .............................................................................14 3.2 Toolboxes Overview......................................................................................................14 3.2.1 Embedded Coder Support Package for STMicroelectronics STM32F4-Discovery Board................................................................................... 14 3.2.2 Target Support Package – STM32F4 Adapter ........................................................15 3.2.3 Waijung Blockset ....................................................................................................17 3.3 Basic Operations ............................................................................................................18 3.3.1 Model Configuration for Code Generation .............................................................19 3.3.2 Analog-to-Digital Converter Configuration ............................................................19 3.3.3 Digital-to-Analog Converter Configuration ............................................................20 3.3.4 USART Communication Configuration ..................................................................21 3.3.5 PC Serial Communication Configuration ...............................................................23 3.3.6 SIL Simulation ........................................................................................................24 3.3.7 PIL Simulation ........................................................................................................26 4 Plant Modelling ....................................................................................................................27 4.1 Theoretical Method: Analysis of a DC Motor ...............................................................27 4.1.1 Velocity Control ......................................................................................................28 4.1.2 Position Control.......................................................................................................29 4.1.3 Results .....................................................................................................................29 4.2 Empirical Method: Grey-Box Model Estimation with MATLAB ................................30 4.2.1 Introduction to Experimental Estimation ................................................................30 4.2.2 Getting the Output ...................................................................................................31 4.2.3 Parameters Estimation .............................................................................................34 4.2.4 Results .....................................................................................................................35 A 5 Signal Adaptation.................................................................................................................38 5.1 Analog Output ...............................................................................................................38 5.1.1 PWM .......................................................................................................................38 5.1.2 DAC ........................................................................................................................39 5.2 Inverting Rotation Sense ...............................................................................................39 5.2.1 H Bridge ..................................................................................................................39 5.2.2 Custom Circuit ........................................................................................................39 5.3 Custom Circuit analysis .................................................................................................40 5.4 Amplifier Calibration ....................................................................................................43 5.4.1 Output Amplifier Calibration ..................................................................................43 5.4.1 Input Amplifier Calibration .....................................................................................44 6 Classic State Feedback .........................................................................................................45 6.1 Controllability................................................................................................................45 6.2 Pole Placement ..............................................................................................................46 6.3 State Observers ..............................................................................................................47 6.3.1 Observer design .......................................................................................................47 6.3.2 Observability ...........................................................................................................48 6.4 The Linear Quadratic Regulator Problem .....................................................................49 7 Model-following Controller .................................................................................................50 7.1 Gains calculation ...........................................................................................................50 7.1.1 Controller Gains ......................................................................................................51 7.1.2 Feed-forward Gain ..................................................................................................52 7.2 Time-discrete Controller................................................................................................54 8 Velocity Control...................................................................................................................55 8.1 MIL Simulation .............................................................................................................55 8.2 SIL Simulation ...............................................................................................................56 8.3 PIL Simulation ...............................................................................................................58 8.4 HIL Simulation ..............................................................................................................60 9 Position Control ...................................................................................................................64 9.1 MIL Simulation .............................................................................................................64 9.2 SIL Simulation ...............................................................................................................65 9.3 PIL Simulation ...............................................................................................................66 9.4 HIL Simulation ..............................................................................................................66 10 Conclusions ........................................................................................................................69 B RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 1: INTRODUCTION 1 INTRODUCTION The main goal of this project is to dig into rapid control prototyping tools that can save time, money and effort in control design. The object of study is the microcontroller STM32F4. The secondary aim is to study model-following control in dynamical systems. To achieve this goal, two applications will be performed on a DC motor: velocity and position control. To achieve these aims, the present work approaches progressively to the final goal. In the next sections of this chapter a general vision of the automatic code generation process is given, establishing the main differences between the MIL, SIL, PIL and HIL simulations. The model-following controller is introduced as well, starting from the basic control principles for readers who are not very familiar with the subject. In Chapter 2 the main hardware is reviewed to clarify several decisions made in further sections. The motor used is a QET DC Motor Control Trainer (DCMCT). It will be analysed and this will give a better perspective to understand the equations related to its performance and some design considerations such as signal adaptation or plant modelling. The STM32F4 microcontroller will also be analysed to understand its capabilities to communicate and process signals. The computer setup to perform rapid control prototyping is explained in Chapter 3. Three Simulink toolboxes can be used for this purpose and each of them is analysed highlighting its strengths and weak spots. Finally, some of the main generic operations accomplished in this project are described in detail, such as CAD and DAC conversion and communication with a computer. In Chapter 4 a mathematical model of the motor is achieved by using a grey-box estimation with MATLAB. First, the physical principles of a generic DC motor are analysed to obtain a theoretical model of the DC motor according to the values provided by the manufacturer. Then, the grey-box estimation is performed to obtain a more accurate experimental model for velocity control. Two experiments will be necessary in order to obtain a model for the motor without the belt and with the belt linked to the potentiometer. The full model for position control is finally deducted from the theoretical analysis and the motor specifications. The problem of adapting the microcontroller analog inputs and outputs to the analog motor signals is tackled in Section 5. First, some possible options are analysed to solve this problem. The adopted solution will be to use a custom signal amplification circuit. This circuit will be analysed and tested. It will be necessary to calibrate it and the followed steps will be shown. In Chapter 6 the theoretical control principles of state feedback are analysed. First, the requirements of a plant to be controllable are investigated. Then, the classic pole placement technique is introduced, which is the basis of the model-following controller. An explanation to the need of using an observer can also be found in this chapter with a brief study of its principles. Finally, an approach to optimal design is given by introducing the linear-quadratic-regulator problem. The model-following controller is finally obtained in Chapter 7 by describing its desired behaviour and deducting its equations. A diagram of the controller is given and the steps to calculate all the gains are explained. The controller is finally written in its state-space form 1 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 1: INTRODUCTION to store it in MATLAB as a state-space model class. The controller is finally discretized in order to implement it in the microcontroller. The next two chapters show the model-following controller performance with real applications. In Chapter 8 the controller will be tuned along the different simulation stages (MIL, SIL, PIL and HIL) until obtaining a satisfactory velocity response. Communication computer-microcontroller is also demonstrated by using a computer as a host that gives the reference to the microcontroller. The ultimate goal is the real plant to track the model output accurately. The script to obtain a model-following controller for a generic-order system is used in this chapter. The script can be found in the annexed document. In this chapter a firstorder model will be followed by the motor. In Chapter 9 the controller will be tested again to perform position control over the DC motor. The same steps will be followed as for velocity control. In this chapter the motor will follow a second-order system. Finally, the results observed along the development of this project are reflected in Chapter 10. This section is a breakdown of the achievements and points to improve in other possible works derived from this one. In this project, MATLAB R2014a version is used. It is recommended for the reader to use the same version in order to avoid compatibility code problems with the scripts provided. All activities have been performed under Windows 7-64 bits. The attached CD contains the Simulink models and scripts to perform all activities from Chapters 4, 8 and 9. The files should be copied into the user’s computer before executing it. This is to keep MATLAB from trying to build additional files in the CD, which would lead to error. Now, a brief introduction to rapid prototyping is made to have a more clear vision of the activities intended to do in this project. In section 1.2 the model-following controller is presented to the reader and a few ideas of control theory are given. 1.1 Introduction to Code Generation Rapid prototyping allows the user to quickly test a design, being able to make fast adjustments until the results are satisfactory [1]. It is usual to start using a tool like Simulink to simulate control algorithms for modelled systems. With rapid prototyping tools, the design can be quickly tested on the real control hardware, this is, the STM32F4. During the development of a controller there are several stages [2]. First, the plant is modelled and the controller is tested in simulation using the model; this is called model-inthe-loop (MIL) simulation. The next step would be testing the code for the controller before loading it onto a real embedded system, such as the STM32F4. This can be done in Simulink by adding a new block with the code (whether automatically generated or not) containing the algorithm and performing a new simulation; this is called software-in-the-loop (SIL) simulation. The differences between these two simulations are shown in Figure 1.1. After that, the code should be loaded onto the real embedded system and tested again; this would be the processor-in-the-loop (PIL) simulation. Finally, the designer should go one step further and try the embedded system with a physical simulator or with the real plant instead of the virtual modelled plant; this is the hardware-in-the-loop (HIL) simulation. Figure 1.2 illustrates the transition from PIL to HIL simulation. 2 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 1: INTRODUCTION REFERENCE REFERENCE CONTROLLER (BLOCKS) CONTROLLER (CODE) MODELLED PLANT MODELLED PLANT READINGS READINGS MIL simulation SIL simulation Figure 1.1: Differences between MIL and SIL simulation REFERENCE REFERENCE STM32 CONTROLLER STM32 CONTROLLER REAL PLANT MODELLED PLANT READINGS READINGS PIL simulation HIL simulation Figure 1.2: Differences between PIL and HIL simulation The tools for code generation allow for the focus on design and testing instead of programming. In fact, some tools allow directly generating C/C++ code and flashing it onto the board, skipping the SIL and PIL simulation steps. Nevertheless, it is recommendable, when feasible, to follow all the steps in order to detect possible errors. 1.2 Introduction to Model-Following Control This sub-chapter has the intention to give some control notions to the readers who have not become very familiar with the control subject yet. It is also a good reading to get used to the notation and ease understanding in next chapters. 3 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 1: INTRODUCTION 1.2.1 The Plant In control theory the term ‘plant’ is often used to name the system to command. It can be modelled as a ‘box’ that receives an input and gives an output. In Figure 1.3, it is shown a DC motor modelled by a first order system to obtain the velocity. Input voltage Input voltage M Shaft velocity 𝐾 𝑇𝑠 + 1 Shaft velocity Figure 1.3: Modelled DC motor by a first-order system In order to be able to study the control of the plant the motor must be represented with a mathematical function. This can be achieved by following two methods: - Studying the physical laws that intervene in the output. Depending on the complexity of the system, it can lead to very long and complicated equations, even making simplifications. - Observing the behaviour of the system. If a known input is given to the plant and the output is registered with a sensor, there are several techniques to obtain an approximation of the plant. 1.2.2 State-Space Representation The state of a dynamical system is the smallest combination of variables which allow fully know its response to a given input at any further instant [3]. In the case of a physical system, those state variables are physical parameters, such as voltage, speed, temperature, etc. An example of state-space representation for a first-order system will now be analysed. The results will be used in chapters ahead. Given a generic first-order transfer function 𝑌(𝑠) 𝐾 (1-1) 𝐺(𝑠) = = , 𝑈(𝑠) 𝑇𝑠 + 1 it can be expressed as 𝑇𝑦̇ + 𝑦 = 𝐾𝑢 . (1-2) 𝑦=𝑥. (1-3) Let The following system can be written: 1 𝐾 𝑇𝑥̇ = −𝑥 + 𝐾𝑢 𝑥̇ = − 𝑥 + 𝑢 { { 𝑇 𝑇 . 𝑦=𝑥 𝑦=𝑥 4 (1-4) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 1: INTRODUCTION According to the general state-space equations for a single-output system 𝒙̇ (𝑡) = 𝑨𝒙(𝑡) + 𝑩𝑢(𝑡) , 𝑦(𝑡) = 𝑪𝒙(𝑡) + 𝐷𝑢(𝑡) (1-5) the following equalities can be written: 1 𝐾 (1-6) ; 𝐵 = ; 𝐶 = 1; 𝐷 = 0 . 𝑇 𝑇 Observe that for first-order systems A, B and C are scalar values. For higher orders, they would be matrices. Also note that for single input systems the control signal is a scalar. If u(t) was a vector, then D would be a matrix as well. For the general case A is the state matrix, B is the input matrix, C is the output matrix and D is the direct transmission matrix. The previous result will be used in section 4.2.3 when programming the architecture of a first-order system. From these matrices, a general system with a single input can be represented in a block diagram as illustrated in Figure 1.4. 𝐴=− D 𝑢(𝑡) B + 𝒙̇ ∫dt + 𝒙 C + + 𝑦(𝑡) A Figure 1.4: State-space representation in blocks of a continuous time system with single input 1.2.3 The Controller: State-feedback Plants do not usually behave the desired way. The mission of the controller is to move the poles of the system so that it accomplishes the given specifications. This is done by using a state matrix gain that weights each state and modifies the control input as shown in Figure 1.5. REFERENCE + 𝑢(𝑡) PLANT -K1 -K2 ... -Kn Figure 1.5: State-space feedback 5 𝑦(𝑡) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 1: INTRODUCTION 1.2.4 The Model-Following Perspective The classic method used in state feedback control in order to adjust the output of the plant is to calculate the zeros and poles the controller needs to modify the whole system so that it accomplishes the response requirements, such as overshooting, gain, settling time, stability, etc. The new focus of the model-following controller is that given an explicit mathematical model, the real plant must ‘follow’ the model and both responses should be the same. Figure 1.6 shows that the model-following controller is compensating the actuation by using the model and state feedback. MODEL-FOLLOWING CONTROLLER 𝑟(𝑡) MODEL 𝒙m 𝑢(𝑡) -Km + 𝑦m (𝑡) -K 𝑦(𝑡) PLANT 𝒙 Figure 1.6: Basic idea of the model-following controller The theoretical basis is the same in both points of view, so in chapter 6 the classical state feedback control is analysed and in chapter 7 the analog steps are shown to get a model-following controller. 6 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 2: HARDWARE 2 HARDWARE 2.1 Motor The rapid control prototyping will be done over a DC servomotor; in this case, the QET DC Motor Control Trainer will be used. To give a more tangible idea, the real system is illustrated in Figure 2.1. Figure 2.1: Photograph of the DCMCT system (extracted from the manual) This device is designed for teaching about control fundamentals and basic controllers design [4]. The board includes an embedded PIC microcontroller, a servo drive, an encoder, a potentiometer, several outputs to read the status of each element and one input to drive the motor. The motor also has its own software, the QICii, to perform different controls via USB in conjunction with the Quanser QIC Processor Core. The supplied guide gives information about the technical characteristics of the motor and shows step by step different control fundamentals. For this project only the motor, the servo drive and its sensors will be used. In conclusion, the board will be used in open loop configuration using the STM32F4 to read and write signals. 2.1.1 Motor diagram In order to illustrate how the servo works and understand the analysis made in the next chapter of the theoretical model of the plant, Figure 2.2 is provided. The voltages of interest are summarized in Table 2.1. 7 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 2: HARDWARE Symbol Vc Vt Vp Vm Description COMMAND port input voltage TACH port output voltage POT port output voltage Motor voltage feed Range ±5 V ±5 V ±5 V ±15 V Table 2.1: Voltages of interest in the analysis of the DCMCT Note that to switch from QIC to HIL control, the J6 jumper must be configured. The right setup for the purpose of this project is the HIL configuration. This is also shown in the diagram. Linear amplifier 𝑉m M POWER COMMAND 𝑉c ENCODER ENCODER CURRENT Adapter ±5 V TACH HIL J6 POT 𝑉t 𝑉p QIC D/A POTENTIOMETER DCMCT SERIAL Figure 2.2: Motor diagram with servo drive, potentiometer and encoder The previous figure is useful to understand the difference, between the theoretical model given by the documentation and the empirical model obtained in section 4.2. 2.1.2 Ports The external connections are summarized in Table 2.2, which is the same as Table A.4 from the motor documentation. 8 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 2: HARDWARE Connector Label D/A POT TACH CURRENT ENCODER COMMAND POWER Connector Type RCA RCA RCA RCA 5-Pin DIN RCA 6-mm Jack Signal QIC D/A Output Potentiometer Output Tachometer Output Current Measurement Output Encoder Output Command To Linear Amplifier AC Power Input to DCMCT Range ±5 V ±5 V ±5 V ±5 V A, B, Index ±5 V 15VAC, 2.4A Table 2.2: DCMCT external connections The connections of interest for closed-loop control will be COMMAND, to drive the motor; TACH, to measure the velocity and POT, to read the position. The optical encoder is directly mounted to the rear of the motor, while the potentiometer must be linked with a belt to the motor shaft. 2.1.3 Sensors Specifications The sensor parameter specifications are shown in Table 2.3 and have been taken from the Table A.3 of the documentation. Description Potentiometer Potentiometer Calibration at POT RCA JACK Potentiometer Calibration at QIC A/D Input Potentiometer Resistance Potentiometer Bias Voltage Potentiometer Electrical Range Tachometer Tachometer Calibration at TACH RCA JACK Tachometer Calibration at QIC A/D Input Value Unit 39 78 10 ±4.7 350 º/V º/V kΩ V º 667 1333 RPM/V RPM/V Table 2.3: Sensor parameter specifications 2.1.4 Technical Motor Specifications The most relevant specifications of the DCMCT are given in Table 2.4. The full model parameters can be consulted in Table A.2 of the documentation. The nomenclature has been adapted to match with the notation used in this project. 9 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 2: HARDWARE Symbol Ra La Km Kt Jeq Description Motor armature resistance Motor armature inductance Electro-motive-force constant Motor torque constant Moment of inertia of rotor + load Linear Amplifier Maximum Output voltage Linear Amplifier Gain Value 10.6 0.82 Not specified 0.0502 2.21 · 10−5 15 3 Unit Ω mH V·s/rad N·m/A kg·m2 V V/V Table 2.4: System parameters 2.2 Microcontroller The STM32F4DISCOVERY board is a low-cost and easy-to-use development kit to quickly evaluate and start a development with an STM32F4 high-performance microcontroller. It is based on an STM32F407VGT6 microcontroller and includes an STLINK/V2 embedded debug tool interface, ST MEMS digital accelerometer, ST MEMS digital microphone, audio DAC with integrated class D speaker driver, LEDs, pushbuttons and a USB OTG micro-AB connector. In this text, the reader can find a brief overview of the STM32F4 features, with special focus on the peripherals used in this project. To consult the full specifications, refer to the STM32F4DISCOVERY and STM32F407VGT6 datasheets [5] [6]. A picture of this board can be found in Figure 2.3. Figure 2.3: Photograph of the actual STM32F4 microcontroller used in this project (extracted from the STM32F4DISCOVERY datasheet) 2.2.1 Getting Started In order to power the board, the JP1 jumper must be set. To program the STM32F4Discovery board, the two CN3 jumpers must be plugged as shown in Figure 2.4. The power 10 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 2: HARDWARE is supplied by the USB connection with the PC using a USB cable ‘type A to mini-B’. It can also be powered for external application with a 5 V source. Figure 2.4: JP1 jumper on and CN3 jumper configuration to allow ST-LINK/V2 programming and debugging (extracted from the STM32F4DISCOVERY datasheet) 2.2.2 Features overview The STM32F407VGT6 is based on the high-performance ARM® Cortex®-M4 32-bit RISC core operating at a frequency of up to 168 MHz. The Cortex-M4 core features a floating point unit (FPU) single precision which supports all ARM single precision dataprocessing instructions and data types. It also implements a full set of DSP instructions and a memory protection unit (MPU) which enhances application security. The STM32F407VGT6 incorporates high-speed embedded memories (1 Mbyte of Flash memory, 192 Kbytes of SRAM), and an extensive range of enhanced I/Os and peripherals connected to two APB buses, three AHB buses and a 32-bit multi-AHB bus matrix. It offers three 12-bit ADCs, two DACs, a low-power RTC, twelve general-purpose 16bit timers including two PWM timers for motor control, two general-purpose 32-bit timers and a true random number generator (RNG). They also feature standard and advanced communication interfaces: Three I2Cs. Three SPIs, two I2Ss full duplex. To achieve audio class accuracy, the I2S peripherals can be clocked via a dedicated internal audio PLL or via an external clock to allow synchronization. Four USARTs plus two UARTs. An USB OTG full-speed and a USB OTG high-speed with full-speed capability (with the ULPI). Two CANs. An SDIO/MMC interface. Ethernet and the camera interface. The STM32F407VGT6 operates in the –40 to +105 °C temperature range from a 1.8 to 3.6 V power supply. 2.2.3 ADC and DAC peripherals The STM32F4 has two 12-bit buffered DAC channels that can be used to convert two digital signals into two analog voltage signal outputs. Each channel has its own DAC with the following features: 8-bit or 12-bit mode. Left or right data alignment in 12-bit mode. 11 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 2: HARDWARE Synchronized update capability. Noise-wave generation. Triangular-wave generation. Dual DAC channel independent or simultaneous conversions. DMA capability for each channel. External triggers for conversion. Input voltage reference VREF+. Also three 12-bit analog-to-digital converters are embedded and each ADC shares up to 16 external channels (check datasheet for ports information), performing conversions in the single-shot or scan mode. In scan mode, automatic conversion is performed on a selected group of analog inputs. Additional logic functions embedded in the ADC interface allow: Simultaneous sample and hold. Interleaved sample and hold. The ADCs share the input voltage reference with the DACs: VREF+. According to the electrical schematics provided by the datasheet, the VREF+ port is connected to VDD as shown in Figure 2.5. Figure 2.5: Reference voltage ports circuit VDD is the power voltage, which is given by the 3 V reference as shown in Figure 2.6. The inductor L1 filters the continuous value of the VDD signal. The capacitors C21, C22, C34 and C25 are decoupling capacitors, which have infinite impedance to continuous voltage. According to this analysis and assuming that the VREF+ port consumes no current, the voltage in VREF+ is given by VDD. Figure 2.6 explains the need to connect the JP1 to power the board. Alternatively, the SB17 connection can be permanently closed by solder. The 3 V reference is achieved with a voltage regulator powered by the 5 V feed of the USB connection. The full scheme can be consulted in the datasheet for more details. 12 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 2: HARDWARE Figure 2.6: Circuit showing that the board is powered when the JP1 jumper is on or SB17 is bridged While testing the DAC and CAD peripherals, it has been detected that the VREF+ voltage is not exactly 3 volts, for this reason, it is recommended to measure the exact voltage reference before using the ADC or DAC peripherals. Since the VREF+ is not available for direct measurement, it must be approximated by measuring the VDD pin on the board. 2.2.4 USARTs and UARTs peripherals The STM32F407VGT6 embed four universal synchronous/asynchronous receiver transmitters (USART1, USART2, USART3 and USART6) and two universal asynchronous receiver transmitters (UART4 and UART5). These six interfaces provide asynchronous communication, IrDA SIR ENDEC support, multiprocessor communication mode, single-wire half-duplex communication mode and have LIN Master/Slave capability. The USART1 and USART6 interfaces are able to communicate at speeds of up to 10.5 Mbit/s. The other available interfaces communicate at up to 5.25 Mbit/s. 13 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION 3 CODE GENERATION 3.1 Requirements for Rapid Prototyping In this project the capability of Simulink to automatically generate C/C++ code will be used for rapid prototyping. The general idea to program the microcontroller consists of three parts: first, a toolbox is used to interact with the ports and peripherals of the board; secondly, a coder generates the C/C++ code of the Simulink model and finally, a toolchain compiles the previous code and loads it onto the microcontroller. This last operation usually can also be done in two different stages: first, generating the binary code and finally, flashing it. Each available toolbox has its own needs, but the common requirements are: MATLAB and MATLAB Coder Simulink and Simulink Coder Embedded Coder Furthermore, the STM32F4 ST-LINK must be installed in order to provide all the drivers for the STM32F4. In this project MATLAB R2014a is used. For compatibility with previous versions, check the requirements for each toolbox. 3.2 Toolboxes Overview 3.2.1 Embedded Coder Support Package for STMicroelectronics STM32F4-Discovery Board This toolbox is provided by MathWorks [7]. The package can be installed from MATLAB going to Add-Ons>> Get Hardware Support Packages. After choosing the installation method, select the package STMicroelectronics STM32F4-Discovery and continue with the installation. Some additional packages may be automatically installed or updated, such as the GNU Toolchain. At some point of the process, the installer will ask the user to provide the path of the Cortex Microcontroller Software Interface Standard (CMSIS) folder. The latest CMSIS is available for download at the official webpage [8]. The CMSIS is a third party hardware abstraction layer (HAL) for Cortex-M processors; this layer provides a standard interface for the software regardless the used hardware. After finishing these steps, the toolbox will be ready to use. Start a new Simulink model and configure its code generation parameters to use the ‘ert.tlc’ file as system target. After that, choose the STM32F4-Discovery as the target hardware. This configuration is shown in Figure 3.1. 14 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Figure 3.1: Code generation parameters for the Embedded Coder Support Package for STMicroelectronics STM32F4-Discovery Board toolbox The available blocks are shown in Figure 3.2. This toolbox is suitable for SIL and PIL simulation with different toolchains, but the lack of blocks and configuration parameters does not allow the user to take advantage of all the features available in the STM32F4. For instance, it is not possible to have full access neither to the DAC peripherals nor to the USART modules. The DACs are limited to be used for stereo audio output and the USART communication can only be used to send information to the computer during PIL simulation. Figure 3.2: Embedded Coder Support Package for STMicroelectronics STM32F4-Discovery Board blocks For PIL simulation a TTL-RS232 adapter is needed. More information and tutorials can be found by clicking the ‘[Examples]’ block. Due to the mentioned limitations, the use of this toolbox for this project will be discarded, but the STM32F4-Discovery package will be installed in order to perform SIL and PIL simulations. 3.2.2 Target Support Package – STM32F4 Adapter This toolbox is provided by STMicroelectronics. The target can be installed by executing the STM32-MAT/TARGET installer that can be found at the main page [9]. Another software is needed to obtain a preset pin configuration of the board and to generate the HAL; the STM32CubeMX. This program can also be downloaded from the main page. Once installed and executed, it is necessary to download the firmware package for the desired family board to be able to properly configure the ports. Finally, a toolchain is needed to compile the code. The toolchain will be integrated in the STM32CubeMX, and can be chosen among the following: EWARM, MDK-ARM, 15 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION TrueSTUDIO and SW4STM32F4. The MDK-ARM Lite version is available for download at the main page. The SW4STM32F4 is an integrated toolchain of the open source IDE Eclipse, but it is not yet fully supported by STM32CubeMX and the projects generated for this toolchain must be manually added to Eclipse. The MDK-ARM Lite version would be suitable for the purpose of this project. After installing all the software, the toolbox can be used. First, start a new Simulink model and configure its code generation parameters to use the ‘STM32F4.tlc’ file as system target. After that, go to Code Generation>> STM32F4 Options and check the options Download Application and STM32CubeMx Path update. Apply changes and close the window. Ignore the error message that shows up when applying changes, it is an application bug. The available block groups appear in Figure 3.3. Figure 3.3: Block groups in the Target Support Package – STM32F4 Adapter toolbox Each block group has its own blocks. The first block that must be added belongs to the MCU CONFIG group: an STM32_Config block. This block contains the port configuration of the target board. To configure it, once it has been added to the model, double click on it and go to New ioc file>> Start STM32CubeMx configuration tool. This will open a new STM32CubeMX instance. Open a new project for the desired board. A graphic pin planner will appear in the next window. Now, every pin must be configured for its purpose by clicking on it and choosing the right function, as shown in Figure 3.4. This is a very intuitive configuration method. The program even alerts the user if a pin is already in use or could cause trouble with a peripheral. More information can be found in the program documentation. Once all the necessary pins have been set, go to Project>> Generate Code>> Project and choose a valid name and path to save the project. Choose the desired toolchain and click OK. After generating the code, close the notification window and go back to the STM32_Config block parameters and click Select STM32F4 configuration file. Go to the folder where the project template has been generated and select the ‘.ioc’ file. Now the Simulink model knows what ports and peripherals are available. 16 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Figure 3.4: Example of pin assignment. PA8 is configured as a digital input while PB7 is a serial reception port The next step is assembling the diagram and building it. After building it, a new instance of the STM32CubeMX will show up. Again, generate the code for the project and click the Open Project button of the notification window. The project will be opened in an Integrated Development Environment (IDE). According to the chosen toolchain, the user will have to follow different steps to compile the C code and flash it onto the microcontroller. This toolchain has the advantage of allowing the user to take almost full control of the STM32F4 configuration. The blocks permit access to most peripherals and the STM32CubeMX enables easy configuration of pins, the clock tree, peripherals and middleware. The disadvantages are the numerous steps and software required to build and load an algorithm. Furthermore, since there are many third party applications implied in obtaining the final code, it has been noticed that some updates in the software make the STM32CubeMX project not fully supported by the toolchains and some initializations of the code must be manually made in order to get a successful compilation. For these reasons, this option will also be discarded. 3.2.3 Waijung Blockset This toolbox is provided by the STMicroelectronics’ third party member Aimagin Co., Ltd [10]. The blockset is released for evaluation purpose only, so to get technical support as well as other features such as permission for commercial use, a special license must be purchased. The toolbox can be directly downloaded from the main page. The file must be uncompressed and the resulting folder must be saved in a fixed path of the computer. To install the package, execute the install_waijung MATLAB script file that is located inside the folder. Make sure the STM32F4 ST-LINK is properly installed. Anyway, a warning message will be shown saying that the STM32F4 ST-LINK could not be found. Just continue with the installation process, that message is an application bug. The package includes the GNU toolchain from ARM Cortex-M & Cortex-R processors, but the user can install its own compiler. In this project the default GNU toolchain will be used. 17 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Once the script has been executed, the toolchain will be ready to use. There is a vast amount of available blocks, but the mainly used will be the On-chip Peripherals of the STM32F4 Target, which are shown in Figure 3.5. Figure 3.5: Main group blocks of the Waijung Blockset toolbox This toolbox has even more available peripherals than the previous one, such as CAN and I2C communication. The blocks in this toolbox can be directly configured for almost any possible need as if programming it manually. To start the algorithm design, open a new Simulink model. Configuring the target is now automatically done just by dragging a Target Setup block into the model. This block is located inside the Device Configuration group block of the STM32F4 Target. Its function is to configure settings such as the clock tree or the compiler. It can be checked that the system target file has been automatically set to ‘stm32f4.tlc’, otherwise it should be set manually. Now the algorithm can be created using the necessary blocks. Once the design is done, it can be coded, compiled and loaded just by clicking the Build Model button. The advantage of this toolbox is the high level of configuration directly from Simulink. This allows the designer to save a lot of time. The simplicity and the capability of the blockset have been the reasons to choose this toolbox for generating the code and flashing the microcontroller of this project. 3.3 Basic Operations Next, some of the common setups used in the algorithms developed in this project are described. 18 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION 3.3.1 Model Configuration for Code Generation The basic arrangement for a model that is planned to be executed on the STM32F4 consists of configuring the target and the Simulink solver. First, open a blank Simulink model and drop a Target Setup block from STM32F4 target. The parameters can be modified by double clicking on it. In this project the GNU ARM compiler will be used. Also make sure to select the correct microcontroller unit (MCU) and clock configuration. For this microcontroller, the configuration should look like Figure 3.6. Figure 3.6: Target Setup block configuration The rest of the parameters can remain as default. Finally, go to Model Configuration Parameters>> Solver>> Solver Options. Configure the solver type to ‘Fixed-step’, the Solver to ‘discrete (no continuous states)’ and set the Fixed-step size to Ts. The step size is a variable that must be declared in the console. In this project the sample time, Ts, will be set to 0.0001 seconds. From the command window, make Ts equal to 0.0001. One last thing to take into account is that the model must be saved before building and both the model’s path and the current workspace directory must be the same. 3.3.2 Analog-to-Digital Converter Configuration As seen in section 2.2.3, the reference voltage for ADCs and DACs peripherals is not exactly the nominal value of 3 volts, so it should be directly measured from the VDD pin for better accuracy. Keep in mind that in this section and the next one, the nominal value of 3 volts is used. The typical configuration used in this project for ADC reading is shown in Figure 3.7. 19 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Figure 3.7: ADC configuration to read a single ADC PORT. ADC port output is an integer value between 0 and 4095 regardless the selected data output. This range is given by the fact that the ADCs implemented in the STM32F4 have 12bits resolution. In this case, the output has been set to single, but it can be set to a fitter range data type as long as the consistency of the signals is kept along the algorithm. The ADC port output is translated into volts by multiplying it by a gain according to the equation 𝑁port 𝑉ref 𝑉𝑝𝑜𝑟𝑡 = , (3-1) 4095 where Nport is the raw reading from 0 to 4095, Vref is the reference voltage and Vport is the read voltage in volts. Apart from the data type, the ADC prescaler can be configured. It is not a critical parameter, but setting it to the lowest value will minimize the conversion time. Finally, the sample time must be set to Ts. Here, a single ADC1 port is read, but more pins can be selected from the same ADCx block. To use another ADC, say ADC2, an additional Regular ADC block must be inserted. 3.3.3 Digital-to-Analog Converter Configuration As for the ADCs, the real Vref value should be read before executing the conversion. In this the conversion can be performed either by the DAC1 (PA4) or by the DAC2 (PA5). The configuration is simple and is shown in Figure 3.8. The desired DAC is selected by checking the corresponding checkbox. The user must be careful not to let the Input Vref field as default, which is a value of 3.3 volts and would lead to wrong writings. Furthermore, it has been detected that the value entered at the Input Vref field must be a number. It is not possible to use a generic variable and change its value from the command window, since it leads to compilation error. 20 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Figure 3.8: Typical configuration for analog value writing 3.3.4 USART Communication Configuration The STM32F4 has 4 USARTs and 2 UARTs. In this project the communication with the microcontroller is always made through the USART1, which uses pins PB6 and PB7 for transmitting and receiving, respectively. The first step is configuring the USART1 as shown in Figure 3.9. Drag a USART Setup block into a configured model for code generation and select the module number 1. Simulink will ask to close the window and reopen it to go on with the configuration. The baud rate has been set to 460800 bps, which is an acceptable speed for the sample time that is being managed. The USART1 can work at up to 7.5Mbps, nevertheless, it has been observed that high rates cause the simulation to work not so fluently. The maximum speed, besides of the microcontroller, is also a matter of the other used hardware. The baud rate 460800 bps is giving good results and is fast enough for this project. The rest of the parameters are configured as shown in the picture. By default two buffers of 512 bytes each are assigned for receiving and transmitting data. 21 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Figure 3.9: USART Setup block configuration for using USART1 (Tx/Rx: B6/B7 ) The reception of the data will be accomplished by using the UART Rx block. It can be configured as ‘Non-Blocking’ if it is important to execute the algorithm when all the data has been received. In that case, the arrangement would look like Figure 3.10. Figure 3.10: Setup for non-blocking data reception If the ‘Non-Blocking’ feature is not important, the Enabled Subsystem block will be omitted, since there is no READY signal. The desired behaviour is that the microcontroller waits for available data to be received. For example, when the STM32F4 is waiting for a serial reference to drive the plant, and has an integral control incorporated, the algorithm 22 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION would make the control input to constantly increase if the plant is not connected. In order to avoid this initial error due to the integral action, a blocking UART Rx block should be used. The procedure would be: first flash the controller onto the STM32F4, connect it to the plant and finally give the reference value through the serial channel. Each quantity of data type must be specified to be received as a binary package. Other transmission formats are available. The sample time can be different from the rest of the program, but it must be a multiple of Ts. This is useful in case Ts is very small and the serial communication does not require such amount of samples. The sample time for communication between the PC and the STM32F4 has been declared as Tc and has a value of 0.001 seconds. The data transmission is analogous to the reception configuration, as shown in Figure 3.11. Figure 3.11: Setup for blocking data transmission The data is sent when it is required by the program and the receiver is responsible to read the information. The rest of the settings are similar to the reception setup. 3.3.5 PC Serial Communication Configuration The communication with the PC is done through a TTL-RS232 USB adapter. For this project, the USB to TTL adapter (PL2303 XA/HXA) by D-sun has been used. The connection is made as shown in Figure 3.12 Tx PB6 Rx PB7 USB MINIUSB STM32 TTL-RS232 GND GND Figure 3.12: Hardware connection for serial communication between PC and microcontroller The software configuration for PC communication is very similar to USART communication. The main difference is that this algorithm will be executed on the PC, so another Simulink model will be needed. This model will not be compiled onto the board, so a default blank Simulink model will be used. The used blocks are found under the block group Waijung Blockset>> Communication>> Host Serial Port. They appear listed in Figure 3.13. 23 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Figure 3.13: Blocks for PC serial communication The setup for these three blocks is analogous to the USART blocks. The only additional action is that the Host Serial Setup block must be configured to work with the corresponding port. To identify the port number of the serial adapter connected to the PC, open the device manager and look for the name of the device under PORTS (COM & LPT). The port number will appear in brackets at the end of the device as shown Figure 3.14. Figure 3.14: Device manager showing that the USB-TTL adapter has been assigned the COM4 3.3.6 SIL Simulation The differences between MIL, SIL, PIL and HIL simulations have been explained in section 1.1. SIL and PIL simulations are the intermediate steps that separate the model design from the real hardware implementation. In these two sections the configuration to perform both simulations will be described. The idea is that one part of the model, which in this case is a controller, must be built into C/C++ code and tested before real implementation. These simulations are accomplished by the Embedded Coder included in Simulink. The STMicroelectronics STM32F4Discovery package from section 3.2.1 must be installed in order to run the code on the STM32F4. To perform a SIL simulation, open the desired Simulink model. The model must be configured before being able to generate a C/C++ code block. Open the Configuration Parameters window and go to Code Generation. Choose ‘ert.tlc’ as the desired System Target File and the ARM Cortex-M3 (QEMU) as the Target Hardware. Select the Toolchain that will be used for the final code generation with the Waijung toolbox. In this project the GNU ARM toolchain will be used. The window must look as Figure 3.15. 24 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION Figure 3.15: Target and toolchain configuration for SIL simulation Go to Code Generation>> Verification and make sure that the creation block is set to PIL as shown in Figure 3.16. Figure 3.16: Block type selection for SIL and PIL simulations The SIL simulation could also be done using a specific SIL block, but in this case, the difference between performing a SIL or a PIL simulation will be given by the selected target. The target previously selected was the QEMU, which is an emulator that executes the PIL block from the computer without the need of having an STM32F4 connected. Close the configuration window. Before going on with the explanation, it is recommended at this point to set the current workspace to a specific location for this generated code. The controller can be generated from an LTI system, a subsystem or another model. In this project the controller is built form LTI blocks. The next step is to build the block. Go to the model, right click on the LTI system that contains the discretized controller and click C/C++ Code>> Build this Subsystem, as shown in Figure 3.17. Figure 3.17: Building the PIL block for a LTI System block named ‘Controller_disc’ A new window will appear, click the Build button. After the process is completed, a new model will be opened containing a PIL block. Copy it and paste it into the previous Simulink model replacing with it the discretized controller block. This block will be the simulated controller and its behaviour can be compared with the real model. Examples of this simulation are given in sections 8.2 and 9.2. 25 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 3: CODE GENERATION 3.3.7 PIL Simulation PIL simulation is the next step after SIL simulation. The microcontroller must be connected via USB and the use of the USB to TTL adapter is highly recommended. Without the serial adapter, the PIL data will be collected by the ST-LINK interface, which is much slower than the serial communication and makes it impractical. The initial configuration is identical to the SIL setup, the only difference is that now the selected target will be the ‘STM32F4-Discovery’. An additional step must be followed: in the Configuration Parameters window go to Coder Target>> PIL. Choose the serial interface and select the COM port as explained in section 3.3.5. The peripheral used for PIL is the USART2, so make sure that the transmitter terminal is connected to the PA2 pin and the receiver to the PA3 pin. Follow the same procedure as for the SIL simulation: set a specific workspace, build the PIL block, include it the Simulink project and run the simulation in normal mode. Examples of this simulation are given in sections 8.3 and 9.3. 26 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING 4 PLANT MODELLING Having an accurate model of the plant is very important to achieve a good controller design. Furthermore, in some cases the plant is not available or it is not possible to measure all the states of the system. That is why an observer based on the model might be needed to get the feedback, as it will be seen in section 6.3. In this section the transfer function that describes the plant will be obtained by two different methods. First, physical behaviour of the DC motor is described by establishing the physical laws that command the system. That is the theoretical method. Secondly, experimental techniques will be used measuring the output of the system for a known input. That is the empirical method. The experimental result will be used to design the controller. The theoretical method will justify the chosen order of the model system and will provide a comparison with the empirical result. 4.1 Theoretical Method: Analysis of a DC Motor A reliable approximation of a DC motor is given by the equivalent circuit in Figure 4.1 [11]. Some simplifications will be made regarding the described system: La is the armature inductance and it can be neglected. This is the case for most cases, in which La<<Ra. There is no friction opposing the motor shaft, only the load and rotor inertia. So the total friction will be ignored. La Ra + Jeq + E Vm - ia M - θ, ω Figure 4.1: Equivalent circuit of a DC motor. The excitation circuit has been omitted Some of the symbols appearing in Figure 4.1 are shown in Table 2.1. Symbol E ia θ ω Description Motor back electromotive force Motor armature current Angular position Angular speed Table 4.1: DC Modelling Nomenclature 27 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING The rest of the symbols used in the previous figure and in the rest of this chapter can be consulted in Table 2.1 and Table 2.4. 4.1.1 Velocity Control The motor back electromotive force can be expressed as 𝐸 = 𝐾m 𝜔 . According to Newton’s second law for rotations: 𝑑𝜔 𝜏=𝐽 . 𝑑𝑡 The torque is also given by its Kt: 𝜏 = 𝐾t 𝑖a . (4-1) (4-2) (4-3) Finally: (4-4) 𝑉m = 𝐸 + 𝑅a 𝑖a . Using the four equations above, it must be solved for Vm(t) as a function of θ for position and for ω for angular velocity. It will be solved as a function of ω and then derived: from (4-1) and (4-4): 𝑉m 𝐾m (4-5) 𝑖a = − 𝜔. 𝑅a 𝑅a From (4-2), (4-3) and (4-5): 𝐾t 𝑉m 𝐾m 𝐾t 𝑑𝜔 (4-6) 𝜏 = 𝐾t 𝑖a = − 𝜔=𝐽 . 𝑅a 𝑅a 𝑑𝑡 Taking into account that when working with SI units both Kt and Km have the same value (it just changes its physical meaning), (4-6) can be rewritten as 2 𝑑𝜔 𝐾m 𝐾m 𝑉m (4-7) 𝐽 + 𝜔= . 𝑑𝑡 𝑅a 𝑅a Taking Laplace: 2 𝐾m 𝐾m 𝑉m (𝑠) (4-8) 𝐽Ω(𝑠)𝑠 + Ω= , 𝑅a 𝑅a and expressing it as a transfer function: 1 Ω(𝑠) 𝐾m 𝐺1 [𝜔, 𝑉m ](𝑠) = = . 𝐽𝑅 𝑉(𝑠) a 𝑠 + 1 2 𝐾m (4-9) Writing the state-variable model is easy for first-order systems. Let 𝑥1 = 𝜔 . (4-10) Then, rewriting (4-7): 𝑥̇ 1 = − 2 𝐾m 𝐾m 𝑥1 + 𝑢(𝑠) , 𝐽𝑅a 𝐽𝑅a (4-11) being Vm(s) the input. That is the analytic representation of the angular velocity against the input voltage. Now, these results will be used to get the transfer function and state-variable model of the full system considering the angular position. 28 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING 4.1.2 Position Control Taking into account that 𝜃̇ = 𝜃𝑠 = 𝜔 , (4-12) (4-9) could be written as 𝐺1 [𝜔, 𝑉m ](𝑠) = 𝛩(𝑠)𝑠 , 𝑉m (𝑠) (4-13) so the new full transfer function is 1 𝛩(𝑠) 1 1 𝐾m 𝐺2 [𝜃, 𝑉m ] = = 𝐺1 = . (4-14) 𝐽𝑅 (𝑠) 𝑉m 𝑠 𝑠 a𝑠+1 2 𝐾m As it can be noticed, only the addition of an integrator to the previous model is needed to get the rotational position. The state-variable model for the full system will now be written. Let 𝑥1 = 𝜃 (4-15) 𝑥2 = 𝜃̇ . Now, from (4-7) and (4-12) 2 𝐾m 𝐾m (4-16) 𝑥̇ 2 = − 𝑥2 + 𝑉 (𝑠) . 𝐽𝑅a 𝐽𝑅a m Thus, the state equations are 0 1 0 𝑥1 𝑥̇ 1 2 𝐾 𝐾 (4-17) [ ]=[ m ] [ ] + [ m ] 𝑢(𝑠), 𝑥2 𝑥̇ 2 0 − 𝐽𝑅a 𝐽𝑅a being Vm(s) the input. 4.1.3 Results In Figure 4.2 there is a simplified full model of a DC motor with an amplifier working in open loop operation. 𝑉c 𝑉m AMPLIFIER 1 𝐾m 𝜔 𝐽𝑅a 𝑠+1 𝐾m2 1 𝑠 𝜃 MOTOR Figure 4.2: Representation of the mathematical model with the states of interest for controlling The goal of the demonstration above is to justify that a first-order model can be used if only velocity control is being performed, but a two-order model will be needed for position control. According to these considerations, a DC motor can be modelled as a second-order system, but if the armature inductance had been taken into account, the equations would have led to a third-order system. 29 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING 4.2 Empirical Method: Grey-Box Model Estimation with MATLAB Now, the real system will be given a known input and the output will be measured. This procedure is divided into two main parts: measuring the output (from Simulink) and running the script to obtain the model. 4.2.1 Introduction to Experimental Estimation The step response of a first-order system is a well-known asymptotic exponential curve [3]. The expression of the step response can be obtained for a generic first-order transfer function such as 𝐾 (4-18) 𝐻(𝑠) = . 𝑇𝑠 + 1 The output will be the system, H(s), multiplied by the input. The Laplace transform of a unit step in time is an integrator, so 𝐾 1 1 𝐾 1 𝑇 (4-19) 𝑌(𝑠) = 𝐻(𝑠) = = . 𝑠 𝑠 𝑇𝑠 + 1 𝑠 𝑠 + 1 𝑇 By calculating the residues and applying the inverse Laplace transform the final result turns out to be: 𝑌(𝑠) = 𝐴 𝐵 + 𝑠 𝑠+1 𝑇 (4-20) 𝐴 = 𝑌(𝑠)𝑠|𝑠=0 = 𝐾 1 𝐵 = 𝑌(𝑠) (𝑠 + )| 1 = −𝐾 𝑇 𝑠=− (4-21) 𝑇 𝑡 𝑦(𝑡) = ℒ −1 (𝑌(𝑠)) = 𝐾 − 𝐾𝑒 −𝑇 (4-22) This last equation describes the evolution in time of the system output. It can be seen that the first term is independent of time and that the second term does depends of time, making itself smaller and smaller over time. This proves that in steady state the final value is K. It has been demonstrated that the gain value of the system, K, can be approximated just by observing the final value a cautious time after giving a unit step to it. Now, the time constant, T, which is responsible for the speed of the system, must be obtained. Making t = T: 𝑇 1 (4-23) 𝑦(𝑡) = 𝐾 − 𝐾𝑒 −𝑇 = 𝐾 (1 − ) ≈ 𝐾 · 0.6321 . 𝑒 It means that when y(t) is equal to approximately 0.6321 times the system gain, the elapsed time since t=0, at the start of the step, will be equal to the time constant. An example of this is shown in Figure 4.3. The final value of the response clearly reaches amplitude 6. Applying Equation (4-23) it turns out that the time constant is reached when amplitude is 3.79, thus, the time constant must be around 2 seconds. The conclusion is that the simulated system in this example must have been 6 (4-24) 𝐻(𝑠) = 2𝑠 + 1 30 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING Step Response 6 5 Amplitude 4 System: H Time (seconds): 2 Amplitude: 3.79 3 2 1 0 0 2 4 6 8 10 12 14 16 18 Time (seconds) Figure 4.3: Response example of a first-order system to a step input Instead of identifying the system manually according to the previous measurements, the input, the output, and the parametrized system will be given to the ‘greyest’ function. A grey-box estimation returns the unknown parameters of the modelled plant. 4.2.2 Getting the Output The input command will be directly given from the microcontroller and one of its ADC ports will be used to measure and save the output. The required resources for this operation are: 1 ADC port 1 DAC port TTL-RS232 adapter DC motor The components are connected as shown in Figure 4.4. It is strongly recommended to read the chapters 3.3.2 and 3.3.3 about CAD and DAC configuration very carefully because the default value of the Vref parameter could lead to wrong system identification. The setup explained in section 3.3.4 for receiving serial data in the microcontroller will be used in the next procedures. Nevertheless, the reader can check most of the ports and settings used just by looking at the diagrams along the explanation. 31 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING +15 V MINI-USB M COMMAND ±5 V TACH ±5 V PA4 PB7 Tx PA0 PB6 Rx USB DRIVER STM32 TTL-RS232 GND GND GND Figure 4.4: Connections between components for model identification The Simulink setup for model identification will now be explained. First, a new blank Simulink model window must be opened and prepared for code generation as seen in section 3.3.1. Now, insert a few blocks and connect them to get the diagram shown in Figure 4.5. Figure 4.5: Algorithm executed by the STM32F4 for model identification What the upper part of the program does is to wait for the serial data to be received through the Rx pin and send the value to an analog output via a Regular DAC block. With this setup a value can be sent to the microcontroller in execution time and it will send it to the COMMAND port of the DC motor. 32 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING The lower blocks are read the value of the ADC port, convert it to voltage and then send it trough the Tx pin. This allows reading the voltage in the TACH port of the DC mottor, which is the output, and save it for further use. At this point the values for the sample time, Ts should be entered in the MATLAB console. It is recommended to click in Display>> Sample Time>> All, now all the blocks should be coloured the same colour. It means that they are discrete blocks and that they have the same sample time. This is a good habit to detect possible errors during compilation. Now the Build Model button can be clicked to generate the code and load it. Wait untill the program has been completely flashed into the memory of the microcontroller. Note that the nominal reference voltage value has been replaced by its real measured value. A single serial port is being used, so there is a master who is giving the input and reading the output. That is the next step: to programme the master. First, a new blank Simulink model window must be opened, but it will not be configured like the previous one. This diagram is not for generating code for the microcontroller, but for running in the computer. Go to Model Configuration Parameters>> Solver. In Simulation time set Stop time to ‘inf’. In Solver options set Type to ‘Fixed-step’, Solver to ‘discrete’ and the Fixed-step size to ‘Ts’. The block diagram must be built as in Figure 4.6. Figure 4.6: Simulink diagram executed in PC for model identification In this diagram the TACH reading sent by the microcontroller is read by the computer and the COMMAND value is sent to the STM32F4. The step is accomplished by manually clicking the switch. The step value and the output value are both multiplexed and sent to the Scope. The Scope is going to be configured to save the ploted data into arrays, so it will create three arrays: one with time measurements, a second one with the output data and a last one with the step data. Double click in the Scope >> Parameters>> History. Make sure 33 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING the checkbox for limiting data is unmarked. Check Save data to workspace and write a variable name for it. Once everything is connected as in Figure 4.4, make sure the switch points at the zero value and click the Start button. A progress bar should now appear at the right bottom of the window, which indicates that it is running without problems. Now switch to the step value, the motor should move and reach a steady state. Waiting around 3 seconds for it to settle is enough. Now press the Stop button. The motor can be let running or manually disconnected. The values have been saved in a matrix in the workspace with the name ‘Scope_Step’. 4.2.3 Parameters Estimation The theory previously seen is the basis for transfer function reconstruction from a given output. Even though those concepts could be directly applied for the data that has just been obtained, a MATLAB tool called Linear grey-box model estimation will be used [12]. This function is called by the keyword ‘greyest’. A grey-box estimation is based on the fact that some information can be given about the system, but still there are some unknown parameters to approximate. Looking at the input and the output of the grey box, the algorithm should return a model that fits into its behaviour but also that looks as the desired system. In other words, the function will be told that the grey-box is a first-order system and will be given three arrays with the time base, the input and the output. The first step is defining the system architecture, its ‘shape’. A new function is created in MATLAB called ‘myfunc.m’. In section 1.2.2 the generic state-equations for a first-order system can be found. According to it, the matrices A, B, C and D can be obtained. The function should look as shown in Script A from the annexed document. In this script, K is the gain, T the time constant and Ts the sample time. The function must be saved in the directory of the current workspace dedicated for plant identification. Now all the means are ready to be used. A new script must be started to execute the algorithm. The identification motor script is shown in Script B from the annexed document. The script has been commented to ease its understanding. First, the values saved in ‘Scope_Step’ are used to store the time-based data into an iddata object. After that, the architecture, the unknown parameters, and the function type are specified. With all this information a grey-box is created using the ‘idgrey’ function. The model is estimated using the ‘greyest’ command. Finally the results are shown. More information about each function can be found in MATLAB documentation. Five measurements for a 2.8 volts step have been performed. The results are summarised in Table 4.2. K [Vt/Vc] 0.776442 0.776276 0.777392 0.777333 0.777149 T [s] 0. 089989 0.078369 0.090998 0.087328 0.086350 FIT [%] 98.810256 97.943966 98.951664 98.493917 98.681353 Table 4.2: Model identification measurements for the motor (without belt) 34 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING 4.2.4 Results It is important to make clear that the considered plants in the applications put into practise in this project include both input and output amplifiers. In the case of velocity control, the plant is all the system between the COMMAND input and the TACH output. For position control, the plant is the system between the COMMAND input and the POT output. This is represented in Figure 4.7. 𝑉p POSITION CONTROL PLANT 𝑉c 𝑉m 𝐾 𝑇𝑠 + 1 𝜔 VELOCITY CONTROL PLANT 1 𝑠 𝜃 𝑉t Figure 4.7: DCMCT plant representation for velocity and position control The average parameters of the motor turned out to be K=0.776918 and T = 0.084761. The models fit nearly a 98% to the real plant, which is a very acceptable estimation for the purpose of this project. A step value of 2.8 volts has been chosen because it is close to the highest value the DAC can reach and it has been checked that the system shows better response for medium-high inputs. In next chapters an amplifier will be installed, so a second system identification can be made with a higher step and take a look at the results, but this estimation is already good enough. Equation (4-9) gives the velocity in rad/s for a given input in volts (measured at the motor terminals). In model identification, [Vt]/[Vc] transfer functions have been used, while in section 4.1 the theorical expresions obtained were [Ω]/[Vm] and [Θ]/[Vm] transfer functions. Equation (4-9) can be transformed into a [Vt]/[Vc] expresión to compare the results: rad 1 rev min · 𝑉t 60 s 3 𝑉m 60 · 3 𝑉t [ s ][ ][ ][ ][ ]= [ ]. 𝑉m 2𝜋 rad 667 rev min 1 𝑉c 2𝜋 · 667 𝑉c (4-25) Therefore, 1 60 · 3 𝐾𝑚 · 2𝜋 · 667 𝐺1 [𝑉t , 𝑉c ](𝑠) = . 𝐽𝑅𝑎 2 𝑠+1 𝐾𝑚 (4-26) Thus, 𝐾theo = 1 60 · 3 1 60 · 3 𝑉t · = · = 0.8556 [ ] , 𝐾m 2𝜋 · 667 0.502 2𝜋 · 667 𝑉c 35 (4-27) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING 𝑇theo = 𝐽𝑅a 0.0000221 · 10.6 = = 0.0929 [s] . 2 𝐾m 0.05022 (4-28) The values for the parameters in (4-27) and (4-28) have been taken from the table A.2 DCMCT Model Parameter Specifications from the DCMCT motor documentation. As it can be noticed above, both theoretical and experimental results are of the same order. The theoretical gain is an 11% bigger than the experimental gain, whereas the theoretical time constant is nearly a 10% bigger. The simplifications made are not so insignificant, so it is much more accurate to work with the experimental model. The transfer function that will be used to design the velocity controller is 𝐺v [𝑉t , 𝑉c ](𝑠) = 0.776918 . 0.084761s + 1 (4-29) A graphical response comparison of the last measure of Table 4.2, the final model and the theoretical model is given in Figure 4.8. Both real and model responses are very similar, while the theoretical response has greater amplitude. This is logical, due to the friction and other simplifications made. 2 Real output Model output Theoretical Output 1.5 1 0.5 0 1 1.1 1.2 1.3 1.4 1.5 1.6 Figure 4.8: Visual responses comparison For position control, the plant will change its dynamics because an external potentiometer must be connected with a belt and it adds more load. Thus, the experiment has been repeated for the motor with the potentiometer. The results appear in Table 4.3. 36 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 4: PLANT MODELLING K [Vt/Vc] 0.750745 0.750147 0.753007 0.751658 0.752822 T [s] 0.093776 0.085073 0.093018 0.091294 0.092688 FIT [%] 99.137308 98.689054 99.122953 98.982729 98.761368 Table 4.3: Model identification measurements for the motor (with belt) The average values have been K=0.7516758 and T=0.0911698 with a high fitting as in the previous estimation without the belt. The transfer function for position control is obtained by adding an integrator to the firstorder system as seen in Equation (4-12). With the previous results, undoing the TACH port amplification gain, as in Equation (4-25), and including the POT port amplification gain, the modelled plant that will be used for position control is: 𝐺p [𝑉p , 𝑉c ] = 0.7516758 2𝜋667 180 77.133501 · · ≈ 𝑠(0.0911698𝑠 + 1) 60 𝜋39 𝑠(0.0911698𝑠 + 1) All voltage equivalences are taken from Table 2.3 and Table 2.4. 37 (4-30) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 5: SIGNAL ADAPTATION 5 SIGNAL ADAPTATION As seen in section 2.2.3 the STM32F4 has two DACs and three ADCs with a common VREF+ which is connected to VDD. It has been checked that the measured VDD pin voltage is around 3 volts; this restricts the STM32F4 to directly read or provide analog signals up to this voltage. Nevertheless, it is desirable that it can reach the full scale of ±5 V of the servo signals COMMAND, TACH and POT. This requires two operations: amplifying the signals, so that the full scale of the microcontroller matches with the full scale of the motor and inverting the signal, so that the motor can run both clockwise and counterclockwise. Next, some of the possible solutions to solve this problem will be examined. 5.1 Analog Output It must be decided how the microcontroller will generate the analog output according to the desired velocity regardless the rotation sense. 5.1.1 PWM This technique consists in varying the duty cycle of a periodic square wave whose amplitude alternates between zero and the maximum drive voltage of the motor as shown in Figure 5.1. The optimum frequency must be selected according to the application and the load, but the motor roll-off frequency is a good reference. The microcontroller only needs a digital output to control a switch that commutes allowing a source of the maximum voltage close the circuit. ON FULL CYCLE V 15 0 t OFF Figure 5.1: Two PWM signal cycles. The average value is proportional to the duty cycle (Ton/T) This is a very commonly used method because it is simple to do in digital control and working always with the maximum voltage allows the shaft to rotate with a constant torque near the maximum even at low speed rate. Even though the motor, due to its inductance, sees the input voltage as an average continuous value, the fact that its torque is greater at low speed than with variable voltage control, makes the motor follow a transfer function different from the calculated in section 4.2.3 that transforms a given duty cycle into velocity and position. 38 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 5: SIGNAL ADAPTATION 5.1.2 DAC The other option is to directly use one of the two digital-to-analog converter of the STM32F4. An amplifier is still needed from the range 0-3 volts to 0-5 volts. Since the servo used in this project has been designed to be controlled with a variable analog voltage, this will be the selected solution. Furthermore, generating an analog output is a more general purpose than DC motor control and the department has shown interest in this matter. 5.2 Inverting Rotation Sense 5.2.1 H Bridge Using the H bridge arrangement needs just a control bit for rotation sense selection, the connection is shown in Figure 5.2. The bit makes commutate two mutual transistors that close the circuit polarizing the motor positively or negatively. +V M CONTROL CONTROL CONTROL CONTROL Figure 5.2: H bridge connection. The bit CONTROL or its opposite value closes the circuit allowing one polarization or another. 5.2.2 Custom Circuit This is a customized solution that solves both the problem of amplifying and inverting the rotation sense. The idea is to get a lineal amplifier that transforms a COMMAND input of 0 – 3 V to ±5 V. With an ideal behaviour it would follow the equation 10 (5-1) 𝑉 −5, 3 in1 is the value at the COMMAND port and Vin1 is the output from the 𝑉out1 = where here Vout1 microcontroller. For reading values from the servo, another amplifier is needed to do the opposite operation: 39 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 5: SIGNAL ADAPTATION 3 (5-2) . 10 For this one, Vout2 is the analog value read at the microcontroller and Vin2 the real measure at the servo port. In Figure 5.3 all external connections are shown. The ports have been named and coloured following the circuit diagram attached in the annexed document for easier understanding. This will be the chosen solution. 𝑉out2 = (𝑉in2 + 5) +15 V SIGNAL ADAPTER ± 15 V OUTPUT AMPLIFIER COMMAND ±5 V M Vout1 X3 X1 Vin1 X5 Vout2 +3.3 V PA4 INPUT AMPLIFIER TACH ±5 V Vin2 X7 POT ±5 V PA0 STM32 GNDs (X2 & X8) GND GND Figure 5.3: Connections of the signal adapter. The full circuits can be found in the annexed document. The theoretical equations of each amplifier will be now analysed according to its schematic. 5.3 Custom Circuit analysis The input and output voltages of the signal adapter are into the ranges shown in Table 5.1. Symbol Vin1 Vout1 Vin2 Vout2 Description Output amplifier in Output amplifier out Input amplifier in Input amplifier out Range 0-3 V ±5 V ±5 V 0-3 V Table 5.1: Voltages of the signal adapter The output amplifier, corresponding to Equation (5-1), is shown in Figure 5.4. 40 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 5: SIGNAL ADAPTATION i4 33.2K Vin1 1K i1 OA1 + V1 i2 OA2 + 10K Follower V2 1K Amplifier i3 OA3 + Vout1 Adder 1K +5V Figure 5.4: Output amplifier. Vin1 (0÷3 V) is the STM32F4 output. Vout1 (±5 V) is the servo COMMAND The first operational amplifier, OA1, is just a voltage follower to uncouple impedances; its negative and positive terminals must be at the same potential (a small virtual ground is written at its negative terminal), so 𝑉1 = 𝑉in1 . (5-3) The topology of the OA2 is an amplifier with a negative gain. This behaviour is described by the next equations: 𝑖1 = 𝑉2 = 0 − 𝑖1 · 33.2K 𝑉1 , 10K 33.2K V2 = −𝑉1 = −𝑉1 · 3.32 10K (5-4) Finally, AO3 works as a voltage adder: it adds the voltages coming to the negative terminal, but it also changes its sign. The output can be deducted as follows: 𝑖2 = 𝑉2 ; 1K 𝑖3 = 5 ; 1K 𝑖4 = 𝑖2 + 𝑖3 ; 𝑉out1 = 0 − 𝑖4 · 1K = −(𝑉2 + 5) = 𝑉1 · 3.32 − 5 (5-5) Equation (5-5) is the theoretical equation of the output amplifier, which is very close to (5-1), which is the ideal equation. The exact gain could not be accomplished due to the standard resistance values. For the input amplifier, the same procedure is followed as before. Its schematic is shown in Figure 5.5. 41 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 5: SIGNAL ADAPTATION i7 1K Vin2 i5 OA4 + V3 Follower 1K i6 OA5 + Adder V4 3.5K i8 1K +5V 3.5K V5 i9 20K 3K 20K OA6 + Inverter V6 OA7 + Follower Vout2 Figure 5.5: Input amplifier. Vin2 (±5 V) is a servo output. Vout2 (0÷3 V) is an STM32F4 analog input A voltage follower is placed after Vin2 and another one before Vout2. According to the analysis of the output amplifier, 𝑉3 = 𝑉in2 (5-6) 𝑉6 = 𝑉out2 . (5-7) and The OA5 works as an adder, so as seen in (5-5) 𝑉4 = −(𝑉in2 + 5). (5-8) The OA6 works as an inverter. It can be proved as follows: 𝑉5 , 20K 𝑉6 = 0 − 𝑖9 · 20K = −𝑉5 . 𝑖9 = (5-9) So, according to (5-9) and (5-7), V5 can be expressed as 𝑉5 = −𝑉out2 . (5-10) The problem reduces to solve the voltage divider between V4 and V5: 𝑉5 = 𝑉4 · 3𝐾 −𝑉in2 − 5 = = −𝑉out2 . 7K + (3K ∥ 20K) 3.2029 (5-11) Thus, the theoretical equation for the input amplifier is 𝑉in + 5 . 3.2029 Again, it is an approximation to the ideal equation, (5-2), for this amplifier. 𝑉out2 = 42 (5-12) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 5: SIGNAL ADAPTATION 5.4 Amplifier Calibration The importance of having a good equation that accurately calculates the output of each amplifier is that this conversion must be undone in Simulink, so the mathematical expression should be as exact as possible. After testing the signal adapter, it has been observed that the output amplifier is showing good results, whereas the input amplifier has important errors and does not perform as its theoretical equation. In order to obtain the best results, both amplifiers will be tested to find its real equation. The basis of the calibration will be that the amplifiers are operating linearly, as is has been theoretically deducted previously, but the mismatch between the nominal value and the real value of the resistors is making them amplify with different gains. For this reason, the models will still be linear equations and they will be calculated experimentally. The input in this calibration will be given by a variable source voltage and both input and output will be measured with a multimeter. 5.4.1 Output Amplifier Calibration The transfer function of this amplifier should look like the graph shown in Figure 5.6, where the ideal maximum should be at (3, 5) and the minimum at (0, -5). The points of interest for the calibration are A, B and P. A and B are two arbitrary points taken near the maximum and minimum but within the operation range. The more separate the points, the better the gain will be measured. P will estimate the offset and it corresponds with the value of the input that returns zero output. Vin1 Max B P A Min Figure 5.6: Operation range of the output amplifier During the calibration, the results have been: 𝐴 = (0.1522, −4.58) , 𝐵 = (2.948, 4.66) , 𝑃x = 1.539 . The gain is the slope of the function 43 Vout1 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 5: SIGNAL ADAPTATION 𝑚= 4.66 + 4.58 ≅ 3.3050 . 2.948 − 0.1522 (5-13) And the offset is 0 = 3.305 · 1.539 + 𝑛 𝑛 = −5.0863 . Hence, the real equation of the output amplifier will be taken as (5-14) 𝑉out1 = 3.305𝑉in1 − 5.0863 . (5-15) It does not show big difference with Equation (5-5), what confirms the good behaviour previously observed. 5.4.1 Input Amplifier Calibration This amplifier does need an adjustment. Its transfer function is shown in Figure 5.7, where the ideal maximum should be at (5, 3) and the minimum at (-5, 0). Vout2 Max B n A Min Vin2 Figure 5.7: Operation range of the input amplifier The gain is estimated analogously to the previous case. Now, instead of P, the offset can be directly read by giving a zero input to the amplifier. The measures for this calibration have been: 𝐴 = (−4.83, 0.0753) 𝐵 = (4.83, 2.701) 𝑛 = 1.388 Thus, 𝑚= 2.701 − 0.0753 ≅ 0.2718 4.83 + 4.83 (5-16) Therefore, the real equation of the input amplifier will be taken as 𝑈out2 = 0.2718 · 𝑈in2 + 1.388 = which quite differs from (5-12). 44 𝑈in2 + 5.1067 , 3.6792 (5-17) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 6: CLASSIC STATE FEEDBACK 6 CLASSIC STATE FEEDBACK The design technique presented in this chapter is commonly known as ‘pole placement’. First, all the system states will be supposed controllable and available for measurement and feedback, and then system observers will be explained. 6.1 Controllability A system is controllable in time t=t0 if there exists a control signal u(t) capable to move the system from the initial state x(t0) to any final state x(tf) in a finite time tf. If all the states are controllable, then it is said that the system is fully controllable [3]. The conditions for a system to be fully controllable will now be analysed. Let the singleinput system: 𝒙̇ = 𝑨𝒙 + 𝑩𝑢 . The solution for the equation above is (6-1) 𝑡 𝑨𝑡 𝑥(𝑡) = 𝑒 𝑥(0) + ∫ 𝑒 𝑨(𝑡−𝜏) 𝑩𝑢(𝜏)𝑑𝜏 . (6-2) 0 Now, without loss of generality, suppose the final state is the state-space origin and make t0=0: 𝑡f 𝑥(𝑡f ) = 0 = 𝑒 𝑨𝑡f 𝑥(0) + ∫ 𝑒 𝑨(𝑡f −𝜏) 𝑩𝑢(𝜏)𝑑𝜏 . (6-3) 0 Solving for x(0): 𝑥(0) = − ∫ −𝑡f 𝑒 𝑨𝜏 𝑩𝑢(𝜏)𝑑𝜏 . (6-4) 0 According to Sylvester’s formula, 𝑒 𝑨𝜏 can be written as follows: 𝑛−1 𝑒 𝑨𝜏 = ∑ 𝛼𝑘 (𝜏)𝑨𝑘 . (6-5) 𝑘=0 Replacing equation (6-5) in equation (6-4): 𝑛−1 𝑘 𝑥(0) = − ∑ 𝑨 𝑩 ∫ 𝑘=0 −𝑡f 0 𝛼𝑘 (𝜏)𝑢(𝜏)𝑑𝜏 . (6-6) Calling ∫ −𝑡f 0 𝛼𝑘 (𝜏)𝑢(𝜏)𝑑𝜏 = 𝛽𝑘 , (6-7) Equation (6-6) can be written as 𝑛−1 𝑥(0) = − ∑ 𝑨𝑘 𝑩𝛽𝑘 = 𝑘=0 = −[𝑩 𝛽0 𝛽1 𝑨𝑩 … 𝑨𝑛−1 𝑩] [ ⋮ ] . 𝛽𝑛−1 45 (6-8) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 6: CLASSIC STATE FEEDBACK Thus, if the system is fully controllable, for whatever initial state x(t0) Equation (6-8) must be satisfied. This means that the matrix (6-9) 𝓒 = [𝑩 𝑨𝑩 … 𝑨𝑛−1 𝑩] must have full rank. The system described by equation (6-1) is fully controllable if, and only if, 𝓒nxn has rank n. This matrix is called controllability matrix. 6.2 Pole Placement Pole placement is a technique that consists in moving the closed-loop poles of a system to the desired location in order to modify its response characteristics. To explain it, a singleinput system for which all the states are available and measurable will be again used. The idea is that the control signal depends of the state vector at every moment [3]. Let the system to control be 𝒙̇ (𝑡) = 𝑨𝒙(𝑡) + 𝑩𝑢(𝑡) y(𝑡) = 𝑪𝒙(𝑡) . The desired input control is (6-10) (6-11) 𝑢(𝑡) = −𝑲𝒙(𝑡) . The equation (6-11) is known as the state-feedback control law. The matrix K1xn is called state feedback gain matrix, and it weighs every state at every instant to calculate the input control. The new regulator system is shown in Figure 6.1. In this case there is no reference, r(t), to follow, so the regulator has to keep the output to zero in case of perturbations. For the tracker case, where the system should follow the reference, the input control will be calculated as the difference between the reference and –Kx. u(t) B + + 𝒙̇ ∫dt 𝒙 B 𝑦(t) A -K Figure 6.1: Regulator based on full-state feedback Replacing (6-11) into (6-10) it results that: 𝒙̇ (𝑡) = (𝑨 − 𝑩𝑲)𝒙(𝑡) . The solution for this equation is (6-12) (6-13) 𝒙(𝑡) = 𝑒 (𝑨−𝑩𝑲)𝑡 𝒙(0) , where x(0) is the initial state. The stability of the system and the dynamic characteristics are given by the matrix A-BK. The matrix K must be chosen such a way that A-BK becomes asymptotically stable, this means that whatever the value for x(0) is, x(t) tends to zero over time. For this to happen, the eigenvalues of A-BK must be negative. This is logical because the eigenvalues of the matrix A-BK are the closed-loop poles of the system. This can be expressed as 46 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 6: CLASSIC STATE FEEDBACK (6-14) 𝑝cl = |𝑠𝑰 − 𝑨 + 𝑩𝑲| = (𝑠 − 𝜇1 )(𝑠 − 𝜇2 ) … (𝑠 − 𝜇𝑛 ) , where 𝜇𝑛 are the eigenvalues of A-BK. There are several ways to calculate the feedback gain matrix. Trying to directly solve Equation (6-13) is not always easy, but applying Ackermann’s formula gives a direct result: 𝑲 = [𝟎 𝟎 … 𝟎 𝟏][𝑩 −1 𝑨𝑩 … 𝑨𝒏−𝟏 𝑩] 𝑝cl . (6-15) It can be proved that arbitrary pole assignment is possible if and only if the system is fully controllable. When the reference is not zero, the control signal should be 𝑢(𝑡) = 𝑟(𝑡) − 𝑲𝒙(𝑡) , so, (6-12) would now look like (6-16) (6-17) 𝒙̇ (𝑡) = (𝑨 − 𝑩𝑲)𝒙(𝑡) − 𝑩𝑟(𝑡) . Thus, in steady state, the first term should be zero, according to the previous reasoning: (6-18) 𝒙̇ (∞) = (𝑨 − 𝑩𝑲)𝒙(∞) − 𝑩𝑟(∞) = −𝑩𝑟(∞) . This matches with the desired behaviour of a regulator: the poles only affect to the transient state and the dynamical characteristics while the steady state only depends on the reference. 6.3 State Observers Until now it has been assumed that all the states of the system were available for measure, but in real systems it is not always that easy. One or more variables, such as voltage or speed, may not be measurable or may require a high cost. For those cases, an observer is used. An observer estimates the estate vector according to the measures of the output and the control signal. When the observer can estimate all the states it is called a fullorder observer, otherwise it is a reduced-order observer [3]. 6.3.1 Observer design The basic idea of an observer matches with a clone of the plant that receives the same control signal and gives an estimate output. But a duplicate of the modelled system is not enough, because the imprecisions in matrices A and B would lead to bigger and bigger errors over time. For this reason, the difference between the real and the estimated output must be taken into account. According to this description, the mathematical model of an observer for the system described by (6-10) is defined as ̂̇ = 𝑨𝒙 ̂ + 𝑩𝑢 + 𝑳(𝑦 − 𝑦̂) 𝒙 ̂ + 𝑩𝑢 + 𝑳(𝑦 − 𝑪𝒙 ̂) = 𝑨𝒙 ̂ + 𝑩𝑢 + 𝑳𝑦, = (𝑨 − 𝑳𝑪)𝒙 (6-19) ̂ is the estimated estate vector and 𝑦̂ is the estimated output. L is the observer matrix where 𝒙 gain; it weights the error of the estimated output at every instant and continuously improves the observer. This is represented in Figure 6.2. 47 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 6: CLASSIC STATE FEEDBACK B + 𝒙̇ + ∫dt 𝒙 𝑦(𝑡) C A 𝑢(𝑡) L B + + + OBSERVER ̂̇ 𝒙 ∫dt A C 𝑒 𝑦̂(𝑡) + - ̂ 𝒙 Figure 6.2: Diagram block of a generic system and its full-order state observer To obtain the equation that gives the error, (6-19) is subtracted from (6-10): ̂̇ = 𝑨𝒙 − 𝑨𝒙 ̂ − 𝑳(𝑪𝒙 − 𝑪𝒙 ̂) 𝒙̇ − 𝒙 ̂). = (𝑨 − 𝑳𝑪)(𝒙 − 𝒙 ̂ is the error vector, e: The difference between 𝒙 and 𝒙 ̂. 𝒆=𝒙−𝒙 According to this, (6-20) can be rewritten as (6-20) (6-21) (6-22) 𝒆̇ = (𝑨 − 𝑳𝑪)𝒆 . Following the same reasoning as with (6-12), the error of the estimation would tend to zero as long as A-LC is asymptotically stable. The poles of the observer must be faster than the closed-loop system poles so that the error converges to zero faster than the system evolves. Many sources suggest placing the observer poles around 5 or 10 times further to the left. This is a design parameter that may require some iterations to get a good response. Determining the value of L can be done by using the same techniques seen for K, but Ackermann cannot be directly applied because L is a column vector while K is a row vector. According to the fact that a matrix, M, has the same eigenvalues as his transposed, M*, it can be written as follows: (6-23) det((𝑨 − 𝑳𝑪)∗ − 𝑠𝑰) = det((𝑨∗ − 𝑪∗ 𝑳∗ ) − 𝑠𝑰) . * Therefore, to calculate L the same methods seen for pole placement to determine K can be applied. 6.3.2 Observability A system is fully observable if the current state vector x(t0) can be determined in a finite time tf just by observing the output. The observability matrix is 𝑪 𝑪𝑨 (6-24) 𝓞=[ ] ⋮ 𝑪𝑨n−𝟏 48 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 6: CLASSIC STATE FEEDBACK and the system is observable if and only if this matrix has full rank. The demonstration is similar to the controllability analysis and can it be found in the references. 6.4 The Linear Quadratic Regulator Problem One big issue in control theory is choosing the optimal gains for state feedback or state observation [3] [13]. The technique seen so far consisted in placing the poles in arbitrary locations using Ackerman’s formula. In this section, an approach to optimal control is introduced. Consider the linear system 𝒙̇ (𝑡) = 𝑨𝒙(𝑡) + 𝑩𝒖(𝑡) y(𝑡) = 𝑪𝒙(𝑡) and the quadratic objective function (or cost function): 1 𝑇 𝐽 = ∫ (𝒙∗ 𝑸𝒙 + 𝒖∗ 𝑹𝒖)d𝑡 . 2 0 For the control input 𝒖 = −𝑲𝒙 . (6-25) (6-26) (6-27) Equation (6-26) becomes 1 𝑇 ∗ (6-28) 𝐽 = ∫ (𝒙 𝑸𝒙 + 𝑲∗ 𝒙∗ 𝑹𝑲𝒙)d𝑡 . 2 0 In this equation, J represents the weighted sum of energy of the state and control. The problem is to minimize J with respect to the control input, u. This is known as the linear quadratic regulator (LQR) problem. The design parameters are Q and R, and they weight the state energy and the control energy, respectively. In general, several design iterations are needed to get a good response. The LQR method gives an optimal K that minimizes the cost function. This minimum may not be global or may not give the expected results, that is why some iterations are generally necessary before achieving good results. J is minimized when the Riccati equation 𝑨∗ 𝑷 + 𝑷𝑨 − 𝑷𝑩𝑹−𝟏 𝑩∗ 𝑷 + 𝑸 = 𝟎 , (6-29) which is associated with Equation (6-26), is satisfied. Note that Q must be symmetric positive semidefinite and R symmetric positive definite. 49 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 7: MODEL-FOLLOWING CONTROLLER 7 MODEL-FOLLOWING CONTROLLER Consider the idea of having a mathematical model with the desirable behaviour for the plant desired to control. The prescribed model accomplishes the speed, robustness, overshoot and other response requirements. In explicit model-following design, the model appears as a feed-forward compensator as it was described in Figure 1.6. In this structure the model is exhibited and the gains can be calculated methodologically as it will be shown in the next section [13] [14] [15] [16]. This is a very comfortable way of control design where only the desired model must be provided. 7.1 Gains calculation Given the system 𝒙̇ = 𝑨𝒙 + 𝑩𝑢 𝑦 = 𝑪𝒙 (7-1) it is desired that it behaves as the model 𝒙̇ m = 𝑨m 𝐱 m + 𝑩m 𝑟 𝑦m = 𝑪m 𝒙m . (7-2) The augmented system can be written as follows: 𝒙 𝑨 0 0 𝒙̇ 𝑩 [ ]=[ ][ ] + [ ]𝑢 + [ ]𝑟 . 0 𝑨m 𝒙m 𝑩 𝒙̇ m 0 m (7-3) This is a tracker that follows the r signal. Without a reference signal, the system would become a regulator and its objective would be to keep the output equal to zero. For the regulator case, the problem would be figured out just by solving it as a regular LQR. Since there exists a reference signal, directly applying the LQR will not give an exact track control. In order to address this problem, the tracker can be analysed separately as a regulator and an integral filter can be added to perform a better tracking. Many sources handle this problem by using the command generator tracker (CGT) approach that basically gives the same solution. Using both techniques requires adding the output error as an extra state, which leads to using an integral filter in either case. The regulator could be directly used as a tracker, in a similar way as it was done in section 6.2 with the pole placement technique. Nevertheless, in order to improve the tracking performance, a feed-forward gain and an integral filter will be added. The mathematical demonstration in next section will show that the integral action is necessary in order to achieve good tracking. In fact, this will reduce the value of the feedforward gain almost to zero, making it dispensable for the studied cases in this project. It has been decided to keep this gain with the aim of building a more general controller to be implemented in other systems that may require it. 50 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 7: MODEL-FOLLOWING CONTROLLER 7.1.1 Controller Gains In order to reduce the tracking control to a LQR problem, the CGT is applied. First, Equation (7-3) can be written as ̅𝑟 , ̅ 𝒙′ + 𝑩 ̅𝑢 + 𝑮 (7-4) ̅̇ = 𝑨 𝒙 where the overlined symbols stand for the augmented matrices. Deriving the previous expression and assuming that 𝑟̇ = 0, the result is ̅𝝃 + 𝑩 ̅𝜇 𝝃̇ = 𝑨 (7-5) The aim of the tracker is to make the real output value equal to the model output. In other words, defining the error as 𝒙 ̅𝒙 (7-6) ̅, 𝑒 = 𝑦m − 𝑦 = 𝑪m 𝒙m − 𝑪𝒙 = [−𝑪 𝑪m ] [𝒙 ] = 𝑪 m the tracker must accomplish that 𝑒 = 0. Deriving the error: ̅𝒙 ̅𝝃 . (7-7) ̅̇ = 𝑪 𝑒̇ = 𝑪 Collecting all the dynamics from (7-5) and (7-7): 𝑒̇ ̅ 𝑒 0 [ ̇ ] = [0 𝑪] [𝝃] + [ ̅ ] 𝜇 . ̅ 𝝃 𝑩 0 𝑨 Defining the derivative of the error as the output: 𝑒 ̅ 𝝃 = 𝑒̇ . ̅ ] [𝝃] = 𝑪 𝑦 = [0 𝑪 The final augmented system would look as follows: ̿ 𝝃̅ + 𝑩 ̿𝜇 𝝃̅̇ = 𝑨 ̅ 𝝃̅ . 𝑦=𝑪 Expressed in its full form: 0 𝑒̈ [ 𝒙̈ ] = [0 𝒙̈ m 0 (7-8) (7-9) (7-10) −𝑪 𝑪m 𝑒̇ 0 𝑨 0 ] [ 𝒙̇ ] + [𝑩] 𝑢̇ 0 𝑨m 𝒙̇ m 0 (7-11) 𝑒̇ 𝑪m ] [ 𝒙̇ ] . 𝒙̇ m The error has been forced to appear as an additional state in order to obtain an extra gain for the filter. The objective will be to minimize the error and its integral value. Since the previous reasoning is made using the derivative of the final system, the cost function of interest is 𝑦 = [0 −𝑪 1 𝑇 ∗ 𝐽 = ∫ (𝑒 𝑄𝑒 + 𝑒̇ ∗ 𝑄𝑒̇ + 𝜇 ∗ 𝑅𝜇)d𝑡 , 2 0 (7-12) where Q weights the error and its derivative and R weights the control input. To achieve the previous equation, QLQR must be defined as 𝑄 0 (7-13) 𝑸LQR = [ ]. ∗ ̅ 0 𝐶 𝑄𝐶̅ To see this more clearly, consider the cost function 51 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 7: MODEL-FOLLOWING CONTROLLER 1 𝑇 ∗ 𝐽 = ∫ (𝝃̅ 𝑸LQR 𝝃̅ + 𝜇 ∗ 𝑅𝜇)d𝑡 . 2 0 (7-14) This is the objective function for the system described by Equation (7-8), which after substituting Equation (7-13) and multiplying gives the desired cost function shown in Equation (7-12). The resulting gain vector is partitioned as follows: 𝑲 𝑲m ] . 𝑲t = [𝐾i (7-15) To sum up this process, the MATLAB function that gives the corresponding LQR algorithm is now shown: ̿, 𝑩 ̿ , 𝑸LQR , 𝑅) . 𝑲t = 𝑙𝑞𝑟(𝑨 (7-16) The control input in Equation (7-8) is 𝑒 𝒙̇ 𝑲 𝑲m ] [ ] 𝒙̇ m = −𝑲i 𝒆 − 𝑲𝒙̇ − 𝑲m 𝒙̇ m . 𝜇 = −𝑲t 𝝃̅ = −[𝐾i (7-17) Since 𝜇 is the derivative of the control input in Equation (7-4), 𝑢 can be written as 𝑇 𝑇 𝑢 = ∫ 𝜇 𝑑𝑡 = − 𝐾i ∫ 𝑒 𝑑𝑡 − 𝑲𝒙 − 𝑲m 𝒙m , 0 (7-18) 0 which, as it has been anticipated, incorporates an integral filter. 7.1.2 Feed-forward Gain Even though including an integral filter already corrects the steady error, a feed-forward gain can be added with the same aim. According to Figure 7.1, the control law is: 𝑢 = −𝑲𝒙 − 𝑲m 𝒙m − 𝑲i 𝑒 + 𝑢ff . Let 𝜌̇ = 𝑒. Including the error in the state representation: 𝜌 𝜌̇ 0 −𝑪 𝑪m 0 0 𝒙 −𝑩𝑲 𝑨 − 𝑩𝑲 −𝑩𝑲 𝑩 [ 𝒙̇ ] = [ ] [𝒙 ] + [ 0 ] 𝑟 . i m 𝑩m 0 0 𝑨m 0 𝑢m 𝒙̇ m ff The desired behaviour is that the error is zero: 𝑒 = 𝑦m∞ − 𝑦∞ = 𝑪m 𝒙m∞ − 𝑪𝒙∞ = 0 . When time tends to infinite: 0 0 [0] = [−𝑩𝑲i 0 0 −𝑪 𝑨 − 𝑩𝑲 0 𝑪m −𝑩𝑲m 𝑨m 𝜌∞ 0 0 𝒙∞ 𝑩] [𝒙 ] + [ 0 ] 𝑟∞ . 𝑩m 0 𝑢m∞ ff∞ Rewriting Equation (7-22): 52 (7-19) (7-20) (7-21) (7-22) RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 7: MODEL-FOLLOWING CONTROLLER 0 [−𝑩𝑲i 0 −𝑪 𝑨 − 𝑩𝑲 0 𝑪m −𝑩𝑲m 𝑨m 𝜌∞ 0 0 𝒙∞ 𝑩] [𝒙 ] = [ 0 ] 𝑟∞ . −𝑩m 0 𝑢m∞ (7-23) ff∞ It can be solved for the state vector multiplying by the pseudoinverse: 𝜌∞ 0 𝒙∞ −𝑩𝑲 [𝒙 ] = [ i m∞ 0 𝑢ff∞ −𝑪 𝑨 − 𝑩𝑲 0 𝑪m −𝑩𝑲m 𝑨m 0 −1 0 𝑩] [ 0 ] 𝑟∞ . −𝑩m 0 (7-24) The feed-forward gain can be obtained from this last equation according to the next equality: 𝐾ff = 𝑢ff∞ . 𝑟∞ (7-25) PLANT 𝑟 Kff 𝑢ff + 𝑢 B + 𝒙 ∫dt 𝒙̇ C 𝑦 A -K -Ki 𝜌 ∫dt 𝑒=𝜌̇ + - -Km Bm + 𝒙m ∫dt 𝒙̇ m Cm 𝑦m Am MODEL Figure 7.1: Model-following controller with feed-forward gain and integral control 53 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 7: MODEL-FOLLOWING CONTROLLER 7.2 Time-discrete Controller Until now, all the control design has been developed for continuous time simulation. The diagram described in Figure 7.1 can be directly be translated into a continuous Simulink model, but before implementing it on the STM32F4, it should be discretized. In this chapter the state-space equations of the controller described in the previous section will be deducted and then the controller will be directly discretized it using MATLAB. The controller is the whole group of elements corresponding to the observer and the model. Its inputs are the reference, r, and the system output, y. The output of the controller is the control signal of the system, u. This is shown in Figure 7.2. CONTROLLER 𝑢 OBSERVER z 𝑟 MODEL 𝑦 PLANT Figure 7.2: Simplified representation of the system Replacing the real plant from Figure 7.1 with the observer from Figure 6.2 the modelfollowing controller can be described as 𝜌̇ = 𝑪m 𝒙m − 𝑦 ̂̇ = 𝑨𝒙 ̂ + 𝑳(𝑦 − 𝑪𝒙 ̂) + 𝑩(𝑟𝐾ff − 𝒙m 𝑲m − 𝑲i 𝜌 − 𝒙 ̂𝑲) 𝒙 𝒙̇ m = 𝑩m 𝑟 + 𝑨m 𝒙m . (7-26) In state-space form: 𝜌̇ 0 [ 𝐱̂̇ ] = [−𝑩𝑲i 0 𝐱̇ m 0 𝑨 − 𝑳𝑪 − 𝑩𝑲 0 𝜌 𝑪m 0 −𝑩𝑲m ] [ 𝐱̂ ] + [𝑩𝐾ff 𝐱m 𝑩m 𝐀m −1 𝑟 𝑳 ] [𝑦] . 0 (7-27) Establishing the control signal as the output: 𝑢 = [−𝐾i 𝜌 −𝑲 −𝑲m ] [ 𝐱̂ ] + [𝐾ff 𝐱m 𝑟 0] [𝑦] . (7-28) The controller can be saved as a state-space model class by declaring the previous A, B, C and D matrices of its state-pace form. The resulting system can be directly discretized with MATLAB using the ‘c2d’ function. 54 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL 8 VELOCITY CONTROL After having analysed all the means used in this project, velocity control will be now performed over the DCMCT in open loop configuration. The TACH port will be used to measure the velocity of the motor. First, using the modelled plant, the controller will be obtained and discretized with MATLAB to store it into a state-space model. Then, the MIL, SIL, PIL and HIL simulations will be performed and the controller will be modified until achieving a satisfactory result. The MATLAB script to obtain the model-following controller for velocity is Script C from the annexed document. 8.1 MIL Simulation The MIL simulation is very important because it is the first time the designed controller is running. This gives a first impression of the global response in terms of stability and fitting to the desired model. It is useful because tuning parameters and performing a new simulation takes no time. The chosen model for velocity control will be the first-order system 1 (8-1) . 𝑠+1 The plant is controllable and observable, so the system should be reachable. At this stage, the simulated control input for a given reference can be checked. This is also an important design matter, because the control input must be within the actuation range of the system. In this case, the control input, which is the COMMAND port voltage (Vc), must be within ±5 volts. In fact, the signal adaptation circuit cannot reach the COMMAND range limits, so the control input range should be reduced to about ±4.5 volts to avoid not reachable references. The MIL simulation has been performed using the following Simulink model given in Figure 8.1. 𝐺m = Figure 8.1: Block diagram for MIL simulation in velocity control Some gains must be added in order to adjust the equivalence between volts and speed according to Table 2.3. The response is shown in Figure 8.2. 55 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL The model and the controller response are virtually equal and would not be distinguishable if the simulated output had not been formatted to a dotted line. The simulated control input for this simulation is within the reachable range. A simulated control input will be shown in PIL simulation to compare it with the real values in HIL. As seen in the next section, the controller is going to need some tuning, so the control input will change. 2200 2000 1800 1600 Velocity (rpm) 1400 1200 Simulated output Model output Step reference 1000 800 600 400 200 0 0 1 2 3 4 5 Time (s) 6 7 8 9 Figure 8.2: Results for MIL simulation in velocity control 8.2 SIL Simulation Configuring the Simulink model as explained in section 3.3.6, and adding the gains as it was done for the MIL simulation in Figure 8.1, the first results for this first SIL simulation are shown in Figure 8.3. The tracking is not as good as in the MIL simulation, but it still follows the model output. 56 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL 2200 2000 1800 1600 Velocity (rpm) 1400 1200 Simulated output Model output Step reference 1000 800 600 400 200 0 0 1 2 3 4 5 Time (s) 6 7 8 9 Figure 8.3: First results of the SIL simulation in velocity control The Q and R weights of the LQR and the position of the observer poles should now be tuned in order to improve tracking. In this case the new values will be 𝑄 = 1010 , 𝑅 = 1 and the observer poles will remain five times faster than the closed-loop system poles. The new response is shown in Figure 8.4. Now the tracker is performing again with almost no error. In the first simulation, the error had been weighted too heavily and the poles were too fast. 57 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL 2200 2000 1800 1600 Velocity (rpm) 1400 1200 1000 Simulated output Model output Step reference 800 600 400 200 0 0 1 2 3 4 5 Time (s) 6 7 8 9 Figure 8.4: Second results of the SIL simulation in velocity control 8.3 PIL Simulation Now the PIL block will be running on the STM32F4 as explained in section 3.3.7. The results are shown in Figure 8.5. The visual response is very similar for both SIL and PIL simulation. This means that the emulator reproduces the behaviour of the real microcontroller very accurately. The next step will be HIL simulation. The simulated control input has also been plotted in Figure 8.6 in order to compare it with the real values. Even though a simulated control input shows that the reference can be reached, it may not occur with the real system, because there are mismatches between the modelled plant and the real one. For this reason, a higher control input value might be needed to correct the error. For this case, the simulated control input maximum value is about one volt below the actual range limit, so it should not be a problem for the real system to follow the same step. 58 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL 2200 2000 1800 1600 Velocity (rpm) 1400 1200 1000 Simulated output Model output Step reference 800 600 400 200 0 0 1 2 3 4 5 Time (s) 6 7 8 9 9 10 Figure 8.5: Results of the PIL simulation in velocity control 4 3.5 Control input (V) 3 2.5 2 1.5 1 0.5 0 0 1 2 3 4 5 Time (s) 6 7 8 Figure 8.6: Control input for PIL simulation in velocity control for a unitary step 59 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL 8.4 HIL Simulation The STM32F4 will be running with the real DCMCT board in HIL configuration. The connections are shown in Figure 8.7. ± 15 V +15 V MINI-USB M COMMAND ±5 V X3 TACH ±5 V X7 X1 PA4 PB7 Tx USB X5 PA0 PB6 Rx DRIVER SIGNAL ADAPTER STM32 TTL-RS232 GND GNDs (X2 & X8) GND GND Figure 8.7: Physical connections for HIL simulation in velocity control The Simulink model to load the program onto the STM32F4 board is shown in Figure 8.8. The control input and the reading of the system output have been converted to read the real values provided by the signal adapter. Equation (5-15) must be undone at the output of the ‘controller_disc’ block so that the Vout1 pin gives the desired control input. The same happens with the read value at the A0 pin of the ADC port, where Equation (5-17) gives the right reading to the controller block. After the code has been loaded onto the STM32F4, the reference will be given by the host PC, following the steps explained in section 3.3.5. The executed model in the PC is shown in Figure 8.9. The gains here convert the reference value into volts as in the previous simulations. 60 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL Figure 8.8: Simulink block model to load the algorithm onto the STM32F4 for HIL simulation Figure 8.9: Algorithm executed continuously on the host PC to send a reference value and plot the results. The reference here is zero. 61 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL The response to a 2000 rpm step is shown in the Figure 8.10. 2000 1800 1600 Position (º) 1400 1200 1000 800 Real output Model output Step reference 600 400 200 0 1 2 3 4 Time (s) 5 6 7 Figure 8.10: Comparison between the model and the real plant response to a 2000 rpm step input The final results are very satisfactory. The model output is over the real output and can barely be distinguished. The only problem with the response is that there is much of noise in the signal. This is mainly caused by the DAC and ADC ports of the STM32F4. The real control input can also be registered sending it with the output value. For the response shown in the previous figure, the real control input calculated by the controller is shown in Figure 8.11. Comparing this control input with the previously simulated in Figure 8.6, both are very similar. This means that the plant identification is a good approximation to the real hardware. 62 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 8: VELOCITY CONTROL 3.5 Control input(V) 3 2.5 2 1.5 1 0.5 0 1 2 3 4 Time (s) 5 Figure 8.11: Real control input in the HIL simulation for a 2000 rpm step input 63 6 7 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 9: POSITION CONTROL 9 POSITION CONTROL In this section position control of the motor shaft will be demonstrated. The plant will be given now by Equation (4-30). The desired model to follow will be the underdamped second-order system: 𝐺m = 1 𝑠2 𝜔𝑜2 + 𝜁𝜔𝑜 𝑠 + 1 , 𝜔𝑜 = 3, 𝜁 = 0.3. (9-1) The MATLAB script to obtain the model-following controller for position is Script D from the annexed document. The code is basically the same. The controller has been written in a generic format, so the script is valid for systems of any order as long as they have a single output. Only the plant, the model and the iteration parameters (Q, R and the observer poles) have been modified. The same steps as in velocity control will be followed next. 9.1 MIL Simulation The gains from Figure 8.1 must be replaced with the equivalence between volts and degrees as it has been done in Figure 9.1. Figure 9.1: Simulink diagram for MIL simulation in position control The electrical range of the potentiometer is of 350º. This means that the maximum overshoot peak must be within the ±175º range. Otherwise, the controller would enter in the nonlinear working area. The first parameters of the simulation process will be 𝑄 = 106 , 𝑅 = 1 and the observer poles will be two times faster than the closed-loop system. A step of 100 degrees has been simulated. The results are shown in Figure 9.2. 64 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 9: POSITION CONTROL 150 Position (º) 100 50 0 Simulated output Model output Step reference 0 0.5 1 1.5 2 Time (s) 2.5 3 3.5 4 Figure 9.2: Results for MIL simulation in position control The model is perfectly tracked by the motor and the overshoot is in the reachable range. 9.2 SIL Simulation For the SIL Simulation the results can be found in Figure 9.3 150 Position (º) 100 50 Simulated output Model output Step reference 0 0 0.5 1 1.5 2 Time (s) Figure 9.3: Results for SIL simulation in position control 65 2.5 3 3.5 4 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 9: POSITION CONTROL The response is virtually the same. 9.3 PIL Simulation For the PIL simulation the results are shown in Figure 9.4. 150 Position (º) 100 Simulated output Model output Step reference 50 0 0 0.5 1 1.5 2 Time (s) 2.5 3 3.5 4 Figure 9.4: Results for PIL simulation in position control This result is identical to the previous simulations. The HIL simulation may not be as good as the first attempt because the real plant is not as the estimated one and the states are given by an observer. 9.4 HIL Simulation Now connect the Vin2 of the signal adapter to the POT port and link the potentiometer to the motor using the belt. The rest of the procedure is the same as for velocity control. The first results are not as good as with the previous simulations where the plant was a software simulation. This response comparison is shown in Figure 9.5. The system tries to follow the model but is unable to correct the error. After several iterations, the parameters have been tuned to 𝑄 = 104 , 𝑅 = 1 and the observer poles have been set ten times faster than the closed-loop system. The new results are shown in Figure 9.6. Now the system accurately follows the shape of the model and corrects the error in steady state. The problem with the first simulation was that the observer was too slow to 66 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 9: POSITION CONTROL follow the model. The error has been weighted a bit less heavily, because the actuation was too big even when the error in steady state was practically zero. 150 Position (º) 100 50 Real output Model output Step reference 0 4.5 5 5.5 6 Time (s) Figure 9.5: First HIL response comparison to a 100º step input 67 6.5 7 7.5 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 9: POSITION CONTROL 140 120 Position (º) 100 80 60 Real output Model output Step reference 40 20 0 2 2.5 3 3.5 Time (s) 4 4.5 Figure 9.6: HIL response comparison to a 100º step input after parameter tuning 68 5 5.5 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 10: CONCLUSIONS 10 CONCLUSIONS This section is a summary of the results obtained along the development of the project. The initial objectives have been achieved, nevertheless the way is open to improve some points as it will be analysed next. The first task has been to become familiar with the STM32F4 and the development of simple algorithms using Simulink so that it can interact with a computer. It has been possible to use the microcontroller as a data acquisition card using a TTL-RS232 adapter to communicate with the computer through a serial data channel and read the STM32F4 pins in execution time. It is also possible to modify the value of its analog and digital ports from the computer. Three toolboxes by different firms have been analysed to achieve the previous aim and have access to other peripherals without programming the microcontroller by hand. The toolbox provided by MATLAB is easy to use, but it has very limited features. In this project the target package associated to this toolbox has been used to perform SIL and PIL simulations with the GNU toolchain. STM provides another Simulink toolbox much more complete. The trouble is that its use is not that simple and several intermediate steps are necessary to code, compile and flash a Simulink model onto the microcontroller. Furthermore, it has been observed that new updates of the software involved in this rapid prototyping method are still being released frequently and the STM32CubeMX seems not to fully support the compilers such as Keil and some code initializations must be added manually. This might be a better option in future releases. The Waijung toolbox has been the chosen software due to its extreme integration with Simulink and the ease to directly build and load the program onto the STM32 from a block model. Besides, this is the toolbox that allows more access to the peripherals configuration. The STM32F4 has a fast processor that can work with 32-bit single precision registers. Even though in the Simulink models of this project the algorithms use double-precision values, a data conversion is automatically performed during encoding. The high-performance of this MCU allows working with small sampling rates for discrete controllers. Here the controller has been designed in continuous time and then discretized using MATLAB. The focus of this project is the rapid prototyping, so the sample time has been chosen in a way that the results are satisfactory. Nevertheless, some criteria can be applied to determine a proper sampling. One criterion when applying discretization is to allow the margin phase to deteriorate 5 to 15 degrees compared to the continuous design [17]. Whereas the performance of the STM32F4 is very high, the built-in DACs and CADs peripherals resulted very disappointing for three reasons. The main reason is the noise in the measurements. The voltage reference for conversion is around 3 volts and the peripherals work with 12-bit data, so the resolution should be smaller than a millivolt. Nevertheless, the noise makes its accuracy much worse. The second reason is the voltage reference itself. It is not as steady as desired because it has been observed that its value may vary some millivolts with temperature. Not much information is provided about the DAC and CAD processes in the datasheets. The last negative point is that during the tests it has been observed that the DACs are unable to provide a voltage lower than approximately 50 millivolts. 69 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER CHAPTER 10: CONCLUSIONS In spite of these facts, both DAC and CAD peripherals can be used taking into account the results in these tests if the application does not have requirements too demanding. For example, rapid control prototyping demonstration has been successfully accomplished in this project using these peripherals. The controller used in these demonstrations is an explicit model-following controller with feed-forward gain and integral action. It has been observed that, for the actual implemented controllers, when using an integral control, the feed-forward gain is virtually zero because the error is already corrected. The implementation and debugging processes of the controller has been guided through the MIL, SIL, PIL and finally HIL simulations. In fact, when some acceptable parameters are achieved after SIL and PIL simulations, new parameters can be directly tested on the real plant or using a simulator. According to the tuning tests performed in this project, using an observer with too fast poles introduces noise into the control input even when the steady error is practically zero. An observer too slow makes the motor not to track the model. The main gains of the controller have been calculated by solving a linear quadratic regulator problem that minimizes the tracking error and its integral value. Penalizing the error too slightly causes the motor to be unable to track the model. On the other hand, penalizing it too heavily causes undesired effects as well. Several iterations are necessary to get good response results since there are various elements involved in the system behaviour. An introduction to optimal control was made using the LQR to calculate the main gains. The next step could be the study of optimal observers instead of placing its poles manually according to the closed-loop system poles. Identifying the real plant (in this case, the motor) is also an important matter to get a good controller design. To estimate a mathematical model of the motor, several simplifications have been made. The velocity response to a voltage input has been approximated as a first-order system response after analysing the physical laws of its behaviour. According to this, a grey-box estimation has been performed using MATLAB and the STM32F4 as a data acquisition card. The result has been a transfer function of the desired order that fits in a high percentage to the real measurements. The motor does not behave like the estimated model for very low voltages. This is because for small input values the braking torque is bigger than the driving torque and the motor has trouble to spin. If this was a problem it could be minimized by using PWM. PWM is more suitable for applications were the DC motor rotates at low frequencies. Both velocity control and position control could be much more accurate reading the digital outputs of the DCMCT board. The encoder has 12-bit resolution and that means that the motor can detect rotations smaller than 0.1 degrees without uncertainty. The final conclusion of this project is that rapid control prototyping using the STM32F4-Discovery board and the studied tools can save time, money and effort by automatizing coding, compilation and flashing. 70 RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER REFERENCES References [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] MathWorks, “Rapid Prototyping for Embedded Control Systems,” [Online]. Available: http://es.mathworks.com/solutions/rapid-prototyping/embedded-control-systems.html. [Accessed 2015]. A. S. Basem S. El-Haik, Software Design for Six Sigma: A Roadmap for Excellence, John Wiley & Sons, 2011. K. Ogata, Modern Control Engineering, Prentice Hall, 2010. H. L. Karl Johan Åström & Jacob Akparian, “USB QICii Laboratory Workbook. Instructor Workbook,” Revision: 01. STMicroelectronics, “UM1472 User Manual. Discovery kit for STM32F407/417 lines,” 2014. STMicroelectronics, “STM32F405xx STM32F407xx,” 2015. MathWorks, “Embedded Coder Support Package for STMicroelectronics STM32F4Discovery Board,” [Online]. Available: http://www.mathworks.com/matlabcentral/fileexchange/43093-embedded-coder-supportpackage-for-stmicroelectronics-stm32f4-discovery-board. ARM, “CMSIS,” [Online]. Available: http://www.arm.com/products/processors/cortexm/cortex-microcontroller-software-interface-standard.php. STMicroelectronics, “Code Generation for STM32 MCUs using MATLAB® and Simulink®,” [Online]. Available: http://www.st.com/st-webui/static/active/en/resource/sales_and_marketing/presentation/product_presentation/stm32matlab.pdf. [Accessed 2015]. Aimagin, “Waijung Blockset,” [Online]. Available: http://waijung.aimagin.com/. [Accessed 2015]. H. T. N. Charles L. Phillips, Digital control system analysis and design, Prentice-Hall, 1984. MathWorks, “Estimating Linear Grey-Box Models,” [Online]. Available: http://es.mathworks.com/help/ident/ug/estimating-linear-grey-box-models.html. [Accessed 2015]. J. J. S. Tyler, “The Characteristics of Model-Following Systems as Synthesized by Optimal Control,” Cornell Aeronautical Laboratory, Inc., Buffalo, N. Y., 1964. V. L. S. Frank L. Lewis, Optimal Control, John Wiley & Sons, 1995. G.-R. Yu, “Explicit Model-Following Design of Propulsion Control Aircraft,” in Systems, Man, and Cybernetics, Taipei, 2006. R. F. Stengel, Optimal Control and Estimation, Dover Publications, Inc., 1994. B. W. Karl J Åström, Computer-Controlled Systems: Theory and Design, Third Edition, Courier Corporation, 2013. 71 ANNEXES RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES CONTENTS 1 Signal Adapter: Electrical Circuit .....................................................................................1 2 Signal Adapter: Printed Circuit .........................................................................................2 3 Script A: Architecture of the Model to Estimate ..............................................................3 4 Script B: Model Estimation Using a Grey Box ................................................................4 5 Script C: Velocity Controller ............................................................................................5 6 Script D: Position Controller ............................................................................................7 A RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES 1 SIGNAL ADAPTER: ELECTRICAL CIRCUIT 1 Annexes RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES 2 SIGNAL ADAPTER: PRINTED CIRCUIT 2 Annexes RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES 3 SCRIPT A: ARCHITECTURE OF THE MODEL TO ESTIMATE function [A,B,C,D] = myfunc( K, T, Ts ) A B C D = = = = -1/T; K/T; eye(1); zeros(1); End 3 Annexes RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES 4 SCRIPT B: MODEL ESTIMATION USING A GREY BOX s=tf('s'); %frecuency domain s %Reminder: previous declaration of Ts is assumed y=Scope_Step(:,2); %Output vector u=Scope_Step(:,3); %Input vector data= iddata(y, u, Ts); %Time-domain data odefun = 'myfunc'; %system architecture %--Creation of an array for parameters to estimate-K=1; %Initial values must be set for K and T T=1; parameters = {'gain', K; 'speed', T}; fcn_type = 'c'; %continuous function %Creation of the grey-box model sys = idgrey(odefun,parameters,fcn_type); %Parameter estimation according to data m_est = greyest(data,sys); %Show results Param=m_est.Structure.Parameters; fprintf('%s: %f\n',Param(1,1).Name,Param(1,1).Value); fprintf('%s: %f\n',Param(1,2).Name,Param(1,2).Value); fprintf('fit: %f percent \n',m_est.Report.Fit.FitPercent); 4 Annexes RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES 5 SCRIPT C: VELOCITY CONTROLLER s=tf('s'); Ts=0.0001; %sample time Tc=0.001; %communication time (for HIL simulation) %Modelled plant K=0.776918; T=0.084761; G=K/(T*s+1); %-------------G=ss(G); %to state-space form A=G.a; B=G.b; C=G.c; D=G.d; Gm=1/(1*s+1); %model to follow p_lc=roots(Gm.den{1}); %closed-loop system poles Gm=ss(Gm); %to state-space form Am=Gm.a; Bm=Gm.b; Cm=Gm.c; Dm=Gm.d; L=acker(A',C',p_lc*5); %observer poles x5 faster than p_lc L=L'; Q=1e15; %the error is penalized heavily R=1; %in comparison with the control input %Augmented system including the model and the error----Anew=[0,-C,Cm; zeros(size(A,1),1),A,zeros(size(A,1),size(Am,2)); zeros(size(Am,1),1),zeros(size(Am,1),size(A,2)),Am]; Bnew=[0;B;zeros(size(Am,1),1)]; Cnew=[0,-C,Cm]; %------------------------------------------------------%Qlqr must minimize the error and its accumulated value-----Qlqr=[-C,Cm]'*Q*[-C,Cm]; Qlqr=[Q,zeros(1,size(Qlqr,2));zeros(size(Qlqr,1),1),Qlqr,]; %----------------------------------------------------------Kt= lqr(Anew, Bnew,Qlqr,R); %gains calculation Ki=Kt(1); %integral gain K=Kt(2:size(A,2)+1); %observer gain Km=Kt(size(A,2)+2:size(Kt,2)); %model gain %(Continues)==> 5 Annexes RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES %Feed-forward gain calculation-------------------------------M=[0,-C,Cm,0; -B*Ki,A-B*K, -B*Km,B; zeros(size(Am,1),size(B,2)),zeros(size(Am,1),size(A,2)),... Am, zeros(size(Am,1),1)]; M_inv=pinv(M); B_aux=[0;zeros(size(A,2),1);Bm]; Kff=-M_inv(size(M_inv,1),:)*B_aux; %------------------------------------------------------------%Controller in continuous time to state-space form------------------Controller_cont= ss([zeros(1,size(B,2)),zeros(1,size(A,2)),Cm; -B*Ki,A-L*C-B*K,-B*Km; zeros(size(Am,1),size(B,2)),zeros(size(Am,2),size(A,2)),Am],... [zeros(1,size(B,2)),-1;B*Kff,L; Bm,zeros(size(Bm,1),1)],[-Ki,-K,-Km],[Kff 0]); %------------------------------------------------------------------Controller_disc= c2d(Controller_cont,Ts); %to discrete time Model_disc=c2d(Gm,Ts); %to discrete time (for MIL, SIL and PIL simulations) Plant_disc=c2d(G,Ts); %to discrete time (for MIL, SIL and PIL simulations) 6 Annexes RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES 6 SCRIPT D: POSITION CONTROLLER s=tf('s'); Ts=0.0001; %sample time Tc=0.001; %communication time (for HIL simulation) %Modelled plant. Now the estimation is a second-order system K=77.133501; T=0.0911698; G=K/(T*s+1); G=G/s; %-----------------------------------------------------------G=ss(G); %to state-space form A=G.a; B=G.b; C=G.c; D=G.d; Gm=1/(s^2/3^2+0.3*3*s+1); %second-order model to follow p_lc=roots(Gm.den{1}); %closed-loop system poles Gm=ss(Gm); %to state-space form Am=Gm.a; Bm=Gm.b; Cm=Gm.c; Dm=Gm.d; L=acker(A',C',p_lc*2); %observer poles x2 faster than p_lc L=L'; Q=1e6; R=1; %the error is penalized heavily %in comparison with the control input %Augmented system including the model and the error----Anew=[0,-C,Cm; zeros(size(A,1),1),A,zeros(size(A,1),size(Am,2)); zeros(size(Am,1),1),zeros(size(Am,1),size(A,2)),Am]; Bnew=[0;B;zeros(size(Am,1),1)]; Cnew=[0,-C,Cm]; %------------------------------------------------------%Qlqr must minimize the error and its accumulated value-----Qlqr=[-C,Cm]'*Q*[-C,Cm]; Qlqr=[Q,zeros(1,size(Qlqr,2));zeros(size(Qlqr,1),1),Qlqr,]; %----------------------------------------------------------Kt= lqr(Anew, Bnew,Qlqr,R); %gains calculation Ki=Kt(1); %integral gain K=Kt(2:size(A,2)+1); %observer gain Km=Kt(size(A,2)+2:size(Kt,2)); %model gain %(Continues)==> 7 Annexes RAPID CONTROL PROTOTYPING USING AN STM32 MICROCONTROLLER ANNEXES %Feed-forward gain calculation-------------------------------M=[0,-C,Cm,0; -B*Ki,A-B*K, -B*Km,B; zeros(size(Am,1),size(B,2)),zeros(size(Am,1),size(A,2)),... Am, zeros(size(Am,1),1)]; M_inv=pinv(M); B_aux=[0;zeros(size(A,2),1);Bm]; Kff=-M_inv(size(M_inv,1),:)*B_aux; %------------------------------------------------------------%Controller in continuous time to state-space form------------------Controller_cont= ss([zeros(1,size(B,2)),zeros(1,size(A,2)),Cm; -B*Ki,A-L*C-B*K,-B*Km; zeros(size(Am,1),size(B,2)),zeros(size(Am,2),size(A,2)),Am],... [zeros(1,size(B,2)),-1;B*Kff,L; Bm,zeros(size(Bm,1),1)],[-Ki,-K,-Km],[Kff 0]); %------------------------------------------------------------------Controller_disc= c2d(Controller_cont,Ts); %to discrete time Model_disc=c2d(Gm,Ts); %to discrete time (for MIL, SIL and PIL simulations) Plant_disc=c2d(G,Ts); %to discrete time (for MIL, SIL and PIL simulations) 8 Annexes