Advanced control with PLC -code generator for aMPC controller implementation and cooperation with external computational server for dealing with multidimensionality, constraints and LMI based robustness

The manufacturers of Programmable Logic Controllers (PLC) usually equip their products with extremely simple control algorithms, such as PID and on-off regulators. However, modern PLCs have much more efficient processors and extensive memory, which enables implementing more sophisticated controllers. The paper discusses issues related to the implementation of matrix operations, time limitations for code execution within one PLC cycle, and memory requirements. The adaptive Model Predictive Controller (aMPC) algorithm is selected for predictive control with on-line adaptation of model parameters. The combination of predictive and adaptive properties in the regulator enables control of many industrial objects for which PID control is ineffective, e.g. nonstationary plants with time-varying delays. The presented generic approach consists in developing a C++ application for desktop PC that generates, based on user provided parameters -such as MPC horizons, the code in Structured Text (ST) language compliant with the IEC-61131 standard for PLCs. Despite the enhanced capabilities of programmable controllers, there are limitations to this platform that cannot be overcome. The implementation of optimization-based control algorithms requires cooperation with an external computing server. In the article, the PLC/external computer cooperation is used to implement the control with constraints taken into account. The robust control using the Linear Matrix Inequalities (LMI) for a multivariable plant is also presented. A number of tests were carried out to verify the correctness of implementation of this control in software-in-the-loop and hardware-in-the-loop structures.


I. INTRODUCTION
Programmable Logic Controllers are a popular industrial platform for the implementation of control algorithms . Du e to their numerous advantages, such as high reliability, preparation for operation in industrial conditions, wide range of I/O modules providing the possibility of connectin g any control object, large communication possibilit ies ensurin g integration with SCADA systems and other elements o f t h e control system, high scalability, and easy programming, it is difficult to find better equipment to act as a d irect cont rol layer. To apply advanced control (AC) methods with a PLC, we have two main approaches: implement a complex algorithm in the PLC, or use an external computing machine. Both these approaches are discussed in the article.
In order to implement advanced control alg orit hms o n a given platform, its possibilities and limitations should be analyzed beforehand. A detailed analysis of CPU performance and memory limitations of selected PLCs is presented. Algorithms described by d iffe rence equ atio ns written in the form of relations between values in the present and past times are especially predestined for implementation in a PLC. Due to the loop-based manner of PLC operation, it is relatively easy to write a program that realizes d ynamic with input to output or input and state t o o ut put relat ions. This opens the space for the implementation of discrete control algorithms, estimation, filtration, etc. A separate chapter presents the implementation of the algorithms described by difference equations in a loop environment such as PLC.
Natural limitations of the PLC platform refer to much lower computing power and memory area comp ared t o PC computers. Also, the real-time operating system en fo rces a finite computation time within one PLC work cycle. Moreover, programming libraries that are available fo r PCs are not available on the PLC. Most of the advanced cont rol algorithms use matrix notation. PLCs offer matrix data storage but do not have native arithmetic operations on matrices. In the article, attention is paid to the implementation of basic mathematical operations using matrices such as addition, multiplication an d in v ersion in terms of their memory requirements, execution time and accuracy. In addition to the PLC limits, it is not p o ssib le t o create dynamic matrix sizes on the PLC platform, which makes it difficult to implement algorithms in which the matrix sizes depend on parameters set by the user. Hence the idea that the program for the PLC should be p repared by a specially created generator for a standard PC. The assumption is that the user enters the controller parameters , and then the code generator working on PC prepares the program in the form of a text file in ST language for the PLC. This approach is very flexible, it additionally p ro vides t h e information on the amount of memory used and the time needed to execute such a code in the PLC. All this allows the user to define the scope of applicability of a g iv en code in relation to a specific PLC CPU.
There are situations where the computation time necessary to complete the entire control algorithm exceeds the allowable cycle time. For these situatio ns, an ap proach is presented in which the computations are s hared b et ween successive PLC cycles. This obviously increases the s tep at which the controller can work to the sum of times of all cycles taking part in the calculation of all steps of the algorithm.
However, not everything can be calculated directly within the PLC. When we need to use external libraries or an optimizer, or simply when the dimensions o f t h e mat rix o r the computation time exceed the capabilities of the PLC, t h e only solution is to use PLC cooperation with an external computing server.
Advanced adaptive-predictive control alg orit hms were selected for implementation. These are MPC and DMC algorithms with on-line updating of informatio n ab out t h e object model. These algorithms use different fo rms o f t he model, but are functionally similar to each other. They preserve all advantages of predictive control related to: extension of the horizon, entering the parameters as trajectories, taking into account multidimensionality, the ability to control non-minimal phase objects, and natural handling of delays, including time-varying delays. In addition, due to the adaptive part, they h ave t h e ab ilit y t o control objects in which the occurring parameter changes are sufficiently slow to be captured by the estimation mechanism. To present the potential of the structure employing an external computing server, control algorit hms were prepared taking into account constraints, such as QDMC and LMI-based robust control. Non-stationary SISO and MIMO objects were used for verification. The correctness of implementation of the prepared alg o rithms was verified by simulation only within the PLC, or wit h t h e acquisition card and the control object simulated outside.
The article is a significant extension of the work presented in publications [1] and [2]. A large part of the present achievements comes from master's theses [3] and [4].

II. STATE OF THE ART
This section presents, based on literature and Internet references, the most important aspects of the article, including: what we call advanced control, wh at in dustrial equipment enables the implementation of advanced co ntrol algorithms, and which algorithms are implemented in t h eir devices by leading manufacturers. The next section will giv e brief descriptions of the IEC-61131 standard defining programming languages for PLC and of the PLCopen organization dealing with the maintenance and development of the PLC programming standard and its close relatio nship with the issues of data exchange in the aut omatio n syst em using the OPC standard. Another important element direct ly related to the content of the article is the PLC Coder t o ol as part of the Matlab package. Finally, a few literature examples of advanced control algorithms implemented in PLCs in various industrial applications are presented.

A. DEFINITIONS OF ADVANCED CONTROL
Since there is no strict definition of the term "advanced control", an attempt was made to find its clarification in t h e industry literature. In [5], we can read "Classical control techniques are mainly represented by the proportionalintegral-derivative (PID) controller which has been employed in a broad range of applications. PID controllers are applied mostly to the processes which are characterized b y lin ear, low-order dynamics. Advanced control techniques migh t b e classified into the following three main categories: mo d elbased control, fuzzy logic control, and artificial neural network-based control".
In [6], it is written "Typically, advanced control met h ods involve more complex calculations than t h e co nvent ional PID controller algorithm. Advanced control has the following features: Process modelling and parameter identification (off line or on line), Prediction of process behavior using process model, Evaluation o f p erformance criterion, subject to process constraints, Optimisation of 3 performance criterion, Matrix calculations (multivariable control) and feedback control".
A different approach is proposed in [7]. Instead of simp le division into simple and advanced control algorithms, a multi-layer (direct, constraint/set-point, optimization, management) control structure is proposed, with three g oals identified as: safety of the control system, keep ing p roduct quality, and, at the third place, consideration o f economic issues. The least complicated layer located next to the object is the direct layer. In [7] we can read "Algorithms o f d irect control should be safe, robust and relatively easy, that is why classic PID algorithms are still dominant". The author names algorithms that can be applied in the direct layer derived from or cooperating with PID, but also algorithms of unconstrained adaptive and predictive control and concludes: "However, it should be strongly emphasized that the generic feature distinguishing all direct control algorithms is the direct access to the controlled process (the process manipulated inputs are outputs of the direct (basic) controllers) and high frequency of intervention (small sampling period)not the kind of control algorithm employed". Later in the book, the algorithms of model based fuzzy and predictive control and set-point optimizat io n are presented as advanced. A similar approach related to ensuring security in the direct/basic layer is presented in [8]. The advanced algorithms listed in this book include PID tuning methods, linear estimation issues, artificial neural networks, and model-based predictive control.
The latest and very important trend in industrial co ntrol systems is ensuring security against network attacks with the application of sophisticated machine learning technology [9,10].

B. INDUSTRIAL PLATFORM S FOR ADVANCED CONTROL IM PLEMENTATION
There are two main options of advanced control system implementation with industrial hardware and software platform: the DCS system, and the PLC + SCADA s y stem. In chapter IX.B less popular alternatives are presented.
Leading DCS manufacturers , such as Emmerson, Yokogawa, Honeywell, Rockwell, ABB and Siemens, h ave equipped their products with advanced control alg o rithms .
Let us see what DCS manufacturers consider advanced control and what advanced algorithms are available in t h eir products.
Emerson [11] introduces its advanced control s ect ion as follows "We recognize that control systems are mo re t h an just a collection of PID-algorithm control loops. A dv anced control can help your plant optimize its performance by increasing throughput, increasing conversion, increasing o n spec product, and reducing by-product. So me o f t h e o t her plant improvements to maximize profit include: Helping site management and engineering focus on optimizin g p ro cess operations 100% of the time, Determine economic optimum, Determine optimal setpoints, Process issues such as complex multi-input, multi-output relationships, operating constraints, nonlinear dynamics, and frequently changing targets." Emerson tools and solutions in AC are: -Aspen DMC3 -enables rapid deployment an d sust ains optimal performance with patented adaptive process co ntrol technology that enables simultaneous process opt imizat io n and testing.
-DeltaV EnTech Toolkitoffers Advanced analysis and tuning technology to improve the performance for d ifficu lt control loops, along with easy plant test data collect ion an d model identification, and Optimal tuning to improve the performance. Advanced performance provides in sig ht in t o the characteristics of loop variability and int eract ions , and possible root causes of poor performance.
-SmartProcess Optimization Softwareoptimizes control processes using turnkey, off-the-shelf advanced control an d monitoring applications from Emerson -Model-Predictive / Multivariable Control (MVC) -DeltaV Predict/Pro -enables the user to o btain g reater throughput, reduced variability, and increased safety for his/her model predictive control strategies. DeltaV Predict/Pro is fully embedded in the DeltaV s y stem wh ich makes it easy to configure, validate, test and deploy.
State-Based Control -automated procedures for safer an d faster startup.
On Yokogawa's website pages and brochures [12] it can be read: "Advanced Process Control brings benefits by reducing energy consumption and imp ro vin g t he y ields. Honeywell [13] claims that "Advanced Pro cess Co ntro l (APC) products address all as pects o f ad vanced p ro cess control and optimization from improving regulatory loop control to globally optimizing the entire process using a unique layered approach. This model allows new technologies to be easily added at an y t ime t o a co mmo n platform that meets optimization objectives without compromising on future opportunities to impro ve b usiness performance. Delivered through the unified Experion Process Knowledge System (PKS) architecture, Honeywell's A PC products improve profitability by in creasing t h roughpu t, reducing costs, increasing yields and improving product quality.
Solutions tackle complex problems through a unique outcome-based consulting approach t hat s upports b ett er process design, process history and analytics, o peratio ns excellence, production management and enterprise collaboration. These solutions allow users to make faster and smarter decisions to improve safety, reliabilit y , efficiency and sustainability".
Some selected Honeywell modules of advanced software are listed below.
Honeywell Forge for Industrial enables Enterprise Performance Management by using real-time accurate models and visual analytics to deliver intelligent actio nable recommendations for sustained peak performance.
Profit -Software for Advanced Control, Optimization and Monitoring. From blending, movements and advanced process control to plant-wide optimizatio n and co ndit ionbased monitoring, Profit Technologies enable facilit ies t o achieve and maintain excellent operations.
Software for Oil and Gas Production. Honeywell's software for oil and gas users includes Product ion Co n trol Center, which automates time consuming tasks and makes information available across the organization, and Well Performance Monitor, which enables users t o p roactiv ely assess the performance of oil and gas production fields using real-time key performance indicators (KPI).
Software for Operations Excellence. From the control room to off-sites material movement, Operations Excellen ce runs the gamut to eliminate events caused b y s ub-opt imal control performance, increase production and energy efficiency, enable accurate operations mo n it oring, an d s o much more.
UniSim -Software for Process Design and Simulation. Honeywell's UniSim software family substantially improves simulation of online and off-line process unit design and optimization applications and helps determine the workflow, equipment needs and implementation requirements for a particular process.
DCS systems are designed for the largest industrial installations in areas such as oil&gas, chemistry, power plants, pharmaceuticals, pulp and paper mills, etc. Wherever the highest reliability is needed, no downtime of the industrial process which may result in the loss of raw material and blocking of the installation is accept able , an d therefore the DCS system should be considered as base infrastructure. A characteristic feature of DCS is the ability to change hardware configuration and cont rol lo g ic o n -lin e, during operations. DCS is more configurable than programmable, and it usually contains libraries of advanced continuous control algorithms, as these systems are d erived from the control of chemical processes, wh ich mo re o ft en require continuous control algorithms than discrete cont rol. DCS scope of operation is usually the whole installation an d the philosophy of action can be d escrib ed as a t o p-down fashion.
PLCs have gone a different way to the present state. They come from the automotive industry, from assembly lines where it was necessary to replace control systems with contactor and relay diagrams. Hence, the domain of PLCs for years has been discrete control, timers, counters, comparators and triggers. PLC scope of operation is often part of the process.
These systems also differ in the structure. The DCS system consists of layers: controllers at the process level, and usually redundant computing servers with a proprietary o peratin g system on the system layer wh ere s ubsequent advanced control modules are run. DCS has central database where all system variables are stored. That is why it is so scalable an d manageable even for a huge plant. On the contrary, each PLC has its own data storage space, so there is a n eed t o d esig n custom information exchange between individual controllers and other elements of the control system.
Although the differences between modern DCS and PLC + SCADA based solutions are diminishing and b lurrin g, t he approach presented in this article does not mean replacin g DCS with a PLC, but rather implementing some of the advanced control DCS functionality in the PLC cooperating with a computational server.

C. IEC 61131 STANDARD FOR PLC PROGRAM MING
The IEC 61131 standard [14] defines basic concepts, general principles, software, and the communication model (data exchange between software components), as well as b asic data types and structures for PLC prog rammin g . It n ames two groups of programming languages: text an d g raphics . The LD graphic language was intended to enable quick and trouble-free programming for electricians who know the principles of the construction of contactor-relay schemes. It is a very transparent language for discrete control applications, but too long-winded and therefore not well readable for the implementation of advanced control algorithms. A similar situation takes place for the FBD language, where the graphic form resembles logic gate diagrams. The text languages, composing the other group o f programming languages, can be divided in to lo w-level IL and high-level ST. For the implementation of advanced This work is licensed under a Creative Commons Attribution 4.0 License. For more information, see https://creativecommons.org/licenses/by/4.0/ This article has been accepted for publication in a future issue of this journal, but has not been fully edited. Content may change prior to final publication. Citation information: DOI 10.1109/ACCESS.2022.3142054, IEEE Access 5 control algorithms, the ST language (resembling the PASCAL, BASIC, or C languages known from PCs ) is t h e most suitable. Since 2003, when the object-oriented and namespace aspects appeared in the IEC 61131 standard, t h is language can be said to be similar to object-oriented languages such as C ++, JAVA, Python, etc. Cert ain ly, t h e similarity applies to the syntax, but the specific loop-like manner of PLC operation, with a watchdog system that supervises the end of all PLC cycle operations , causes a different programming approach for PLC than for classic PC.

D. PLCopen ASSOCIATION
PLCopen [15] is a vendor and product independent association, whose members come from all fields of the industry to deal with topics concernin g in dust rial co n trol software. The areas of PLCopen operatio n in clude : fast er application development, faster commis sion ing t ime , an d reduced software life cycle costs. According to [15], curren t PLCopen topics are: "Motion Control and Safety functionality, XML data exchange format standardizin g t h e base data of IEC projects in software systems, and map p ing to the OPC Unified Architecture for transparent Communication". The association has undertaken the development of technical specifications related to IEC 61131-3, which resulted in "standardized libraries for various application fields, harmonized language compatibility levels, and engineering interfaces for interchange and clear communication". This organization also deals with train ing , publishing, and certification activities. On t heir p ages y ou can find a large number of documents that allow you to improve your qualifications and quality, as well as the portability of the produced code for PLC and related industries. Noteworthy is also establishing close cooperation with the OPC UA organization that replicates the communication standards between PLC, DCS, SCADA, industrial databases, measuring devices, actuators, and oth er elements of automation. Noteworthy is the standard XM Lbased Exchange Format developed by PLCopen fo r exp o rt and import of IEC 61131-3 projects. Being part of the 61131-10 standard, it can be considered the next step towards a joint description of projects for PLCs irrespective of their manufacturers. Summarizing the PLCopen topic, wh en t he issue of implementing advanced control algorit hms o n t he PLC platform is considered, it is helpful to become familiar with the achievements of this organization.

E. PLC CODER M ATLAB TOOLBOX
An important tool for the implementation of advanced control algorithms in PLCs is undoubtedly the Matlab toolbox called PLC Coder [16]. This software is designed t o automatically generate the logic developed in the three main Matlab design tools, i.e. Simulink, Stateflow, or Matlab, an d save it as m-files in LD and ST PLC languages. The big advantage of PLC Coder is targeting logic to popular platforms for PLC programming such as: CODESYS, Rockwell Automation Studio, Siemens TIA Portal, and OMRON Sysmac Studio. When some hardware platform is not directly supported, you can u se t he g eneric p ath an d adapt the received code to your hardware and software. Fo r example, adjusting the code for the PAC GeFanuc controller (which is not originally supported by PLC Co d er) u s ed in this article comes down to defining the variables by yourself and dividing the logical part of the program into the initialization part and the rest of the code. The obvious advantage of PLC Coder in Matlab is the ability to use ot her toolboxes and their contents to generate a code for th e PLC. The joint use of the MPC toolbox and PLC Coder allows you to quickly obtain the code of an advanced controller, wh ich can be comprehensively tested in simulat ed s cenarios and environment, and then quickly implemen ted o n t h e t arget industrial equipment. It can be called a typical example of the idea of rapid prototyping.

F. SELECTED PAPERS WITH ADVANCED CONTROL IM PLEM ENTED IN PLCs
The subject of the implementation of advanced control algorithms in PLC is discussed in scientific and industry articles. The article [17] presents the implementation of a Generalized Predictive Controller (GPC) on Allen Bradley PLC -SCL500 using Function Block Diagram and Structured Text. As the authors claim: "The resu lts o f t h is work encourage to keep working in developing simple predictive algorithms to be programmed in industrial standard hardware." An example used to illustrate the correctness of the implementation was a h eatin g p rocess having the features of a first-order inertial object with delay. The same object was used in [18] to illustrate the o perat ion of a predictive controller with auto-tuning and constraints o n control signals. The comparison of the control qualit y wit h the PID controller clearly shows why it is worth makin g t he effort to implement the MPC controller. The third in a series of articles describes MPC implementation with co nst rain ts [19], and its authors propose an original approach to "parameterization of the parametric regions which allows efficiency of definition, effective spannin g o f t h e feasible region, and also highly efficient search algorithms". The whole series of these articles shows that the PLC is an appropriate industrial hardware platform on which both classic and novel advanced control algorithms can be implemented. Another paper worth mentioning is [20], which describ es the implementation of MPC with constraints on input signals using the Nesterov's fast gradient method using [21] approach. The authors successfully implement the MPC algorithm in the Modicon M340 controller fro m Sch neider Electric and test it in a loop with a simulated ob ject h aving the form of connected tanks. The authors raise the problem of limitations in the available memory and computing power o f PLC. The MPC program for the PLC was executed in ST language.
This work is licensed under a Creative Commons Attribution 4.0 License. For more information, see https://creativecommons.org/licenses/by/4.0/ This article has been accepted for publication in a future issue of this journal, but has not been fully edited. Content may change prior to final publication. Citation information: DOI 10.1109/ACCESS.2022.3142054, IEEE Access 6 An interesting implementation of an advanced alg orit hm in PLC is described in [22]. The model predictive control was applied with a projected gradient algorithm designed fo r controlling nonlinear input constrained systems. The implemented nonlinear MPC was used for a laboratory crane with sampling resolution of 2 ms. A spectacular video documenting successful implementation and handling constraints is provided. In that case, the FESTO PLC was a host platform for implementation, and PLC Coder was u sed to export the algorithm from Matlab/Simu lin k t o Co d esys engineering software.

G. SUM M ARY OF THE LITERATURE REVIEW AND GUIDELINES FOR THE ARTICLE
As a result of the query on the literature resources an d t he largest manufacturers of DCS systems, an approach emerged that advanced algorithms on industrial control platforms are adaptive, predictive, and of fuzzy control type, and they make use of neural networks and broadly understood optimization. The term "advanced" also refers to taking in t o account limitations, multidimensionality, as well as the use of models, self-tuning, and safe control at the limits of the constraints.
Hence, the implementation of predictive cont rol o n t he PLC platform with on-line adaptation of model p aramet ers was chosen as the main challenge of the paper. The cooperation of PLC with an external solver (of DCS-type) for building the system with optimization was also consid ered . Two control systems were implemented as an example: constrained multivariable MPC control, and LMI-based robust control.
The article makes use of an idea from the PLC Coder toolkit, i.e. instead of writing programs for PLC directly, it is more convenient and more developmental to create an external application for generating a parametric program fo r the PLC. The ST language according to IEC 61131 standard and PLCopen materials were used for this purpose.

III. SPECIFICS OF PLC AND OVERCOMING ITS LIMITATIONS
The specificity of the PLC is the use of a simplified real-time operating system implemented as a loop consisting of several operations: reading inputs, executing program logic, s ett ing outputs, diagnostics, and possibly communication wit h t he programmer. All these activities must be complet ed wit h in the set time, supervised by the watchdog system. Typically , the PLC cycle time without program is several milliseconds, while the maximum time set in the watchdog is of the o rder of seconds. This means that the time allowed for one iteration of the program cannot exceed seconds. In a natural way, this eliminates the PLC from a certain class of applications, su ch as solving complex optimization problems. Another limitation is the use of significantly slower CPUs in the PLC than those used in the PC, and limited amount o f memo ry . An important limitation is also the method of PLC programming, in particular the lack of native support for algebraic matrix operations while allowing data saving in the form of a matrix. The specifics of PLC operation are not only limitations -due to the loop-oriented way of operation , it is relatively easy to implement algorithms given by difference equations. This section describes how to overcome the limitations of the PLC and use its properties. It shows how to measure the computing power of the PLC, how to implement algorithms given by difference equations, and how to effectively implement the matrix algebra and divide the algorithm into a number of cycles.

A. PERFORM ANCE ANALYSIS -PLC BENCHM ARKING
GE Fanuc RX3i was the controller used for testing and implementing advanced control algorithms. Two d ifferent CPUs (CPU310 and CPE305) were used for performance testing. The faster of them was then used for further research. 32,640 logical (16-bit) variables can be stored in the available memory, which allows the use of 16320 real variables when operating on real 32-bit numbers [23].
The In addition, the impact of high-level ST instruct ions o n t h e execution time is not described, as the execution times given in the manual apply to the LD language [23]. Th erefore, it was decided to test also the performance of the programmable controller in practice.
The most common unit for determining processor performance is FLOPS. The simplest operations such as addition, subtraction, and multiplication were used to evaluate the performance. Performing one of these operations is considered to be equal to one operation on a floating-point number. The processor performance is often determined using Fused Multiply-add (FMA) and its variations, such as Multiply-accumulate (MAC), which take the form (1) [24]: The controller performance evaluation was carried out fo r two PLC CPUs using 3 programs with different designs, implementing MAC operations. The tests were p erformed using the ST language, as the use of a high-level lan guage allows for better overall performance measurements than th e tests based on low-level languages [25]. The met ho ds u sed for determining the controller performance are described in Table I, while the results are given in Table II.  Program that uses only high-level instructions 3 Program that uses high-level and simple instructions 4 Program that uses only simple instructions For three different programs, three different execution times and three different determined computing capacities of the controller were obtained. This is due to the fact t h at b y testing the computational performance with a p rog ram, we determine the effectiveness of a given program [26]. Therefore, it can be concluded that the least effective implementation of calculations is the use of high-level instructions, while the most effective is the complete absence of them. A good alternative is to carry out part of operatio ns with loops and part with basic operations. This will significantly reduce the program execution time an d , at t h e same time, keep the code transparent.
It can be concluded that the performance o f b ot h CPUs obtained after executing the program using basic operatio ns is the value closest to the actual performance of the controller and close to the maximum possible efficiency that t he u ser program can achieve.
Having the information about the PLC performance, t he user can estimate whether his algorithm can be implemented on this platform, and/or eventually what the maximum values of the algorithm's parameters may be.

B. PLC IM PLEM ENTATION M ETHODS OF ALGORITHM S GIVEN WITH DIFFERENCE EQUATIONS
Due to the loop/cyclic operation, PLCs are naturally predisposed to the implementation of estimation, filt rat io n, and control algorithms defined by difference equations. Th e notation in the form of difference equations is recursiv e an d given by the relations of appropriate quantities at the present time with past times. Three phases: initialization, u p dat ing, and saving are sufficient for complete implementation of t h e algorithm given by a differential equation. Th e co ntext o f their use adapted to the cyclical operation of PLC is shown in Fig. 1. In the initialization phase, which is usually called only once with the first PLC cycle, the initial conditions are given to all quantities. The updating phase includes correct description of the algorithm based on the g iven d ifference equation. In the saving phase, usually at the end of the co de, the current data is saved in relevant variables, which will b e then treated as variables delayed by one step in the next controller cycle. The first example of 3-stage implementation is the dynamics of a 2nd order oscillation model with delay g iv en by (2): This work is licensed under a Creative Commons Attribution 4.0 License. For more information, see https://creativecommons.org/licenses/by/4.0/ This article has been accepted for publication in a future issue of this journal, but has not been fully edited. Content may change prior to final publication. Citation information: DOI 10.1109/ACCESS.2022.3142054, IEEE Access 8 and finally: (6) In order to preserve the dynamics of the object modeled in this way, it is necessary to keep the intervals between particular cycles equal to the sampling period. This effect can be achieved programmatically by using timer blocks , o r b y forcing a fixed PLC cycle time in the CPU. The 3-stage implementation scheme is presented in Table III. Note the specific reverse order of assigning v ariables in the save stage.
The time series for (2), (3) and (6) with initial con d itio ns from Table III   Another example of 3-stage implementation is the normalized gradient estimation method from [27]. The algorithm described in matrix (vector) form is:  In order to illustrate the implementation and performance of the estimation algorithm, it was used to determine the parameters of the model from the first example. It was assumed and stated in (10) that the initial values of the estimated parameters are zero, the parameter kappa = 0.1, and the gamma matrix is unitary.
Based on the algorithm described by formulas (7)-(9) an d the 3-stage implementation method from Table IV, the program for PLC was developed as shown in Fig. 3. Several ST-specific features can be seen: each line ends with a semicolon, the assignment operator is:=, as well as the hig hlevel language construct if..then..end_if; and distinguish ing INT types from REAL in that the latter must b e writ t en in full dotted form even if the numbers are zeros. The initialization phase is based on the #FST_SCN syst em variable, which is on high state only in the firs t cy cle aft er PLC start. The input signal is realized as the sum of the constant value 1 and a pseudoran dom n u mber g en erat ed based on system timers available in the PLC. Fig . 4 s h o ws the trajectories of parameter estimates. The speed of convergence of the estimat es d epends o n parameters kappa and gamma, but also on the noise lev el at the input of the simulated object. Fig. 4 shows the ±1 waveform of noise, and a much faster convergence can b e obtained by significantly increasing the noise. A s it can b e seen, the estimates are heading towards t h e id eal v alu es, which indicates the correctness of the implementation.
For the purposes of the illustration, simple and clear examples were chosen, but many different, more adv anced algorithms for control, estimation, and filtering of models o f dynamic objects defined by differential eq uations can b e implemented in the PLC using the presented three-stage method.
As can be seen in the presented example, matrix operations were performed in a scalar manner due to the lack of n ativ e support for matrix operations in the PLC. Proper programming of matrix operations in PLC seems to be crucial, due to the memory management and t h e s peed o f execution of algorithms with large matrix sizes.

C. DATA STORAGE IN M ATRICES AND M ATRIX OPERATIONS
The IEC 61131 standard specifies structures such as matrices, but the manufacturers usually allow workin g wit h matrices by referring to individual elements. There are also restrictions on matrix size, for instance the maximum amount of data in the matrix in the GE Fanuc RX3i controller is 9999. In addition, the PLCs do not have built-in instructio ns for matrix operations, so all the necessary operations need t o be implemented. That is why the efficiency analysis of various methods of performing matrix operations was undertaken.
One of the most important features of the computer program is its efficiency, which describes the use of computer hardware resources : computing power and memory n O which is a significant reduction compared to traditio nal met h ods o f matrix multiplication. However, for present implementat ion of the multiplication operation in predictive cont rol, it was decided to use the conventional matrix multiplication methods because:  In the implemented predictive control algorithm, the multiplied matrices (with assumed dimensions n n ) are smaller than the point for which the Strassen algorithm becomes more efficient [29] [30], so the multiplication making use of a traditional method will be more efficient.  The Strassen algorithm uses more memory than traditional methods [31] [32].  The matrices on which the operations will be performed are not square matrices, therefore, in order to use the Strassen algorithm, the given matrices should be supplemented with zeros, which additionally increases both memory use and computational complexity [27]  In part of the operation, the matrix elements can b e non-negative and filled with small values . Therefore, in order to be able to u se t h e St rassen algorithm, an error analysis should be additio nally performed, because this algorithm does not guarantee the accuracy comparable with that of traditional methods [28]. During the analysis, it was decided to carry out matrix multiplication using several methods with different way s o f accessing the data and different numb er o f h ig h-level ST language instructions. The applied methods and the obtained results are presented in Table V.  The analysis was performed for several mat rix s izes , t h e results given in Table V are for the   50  50 matrix. The best method under consideration is method 2, because it is 2.6 times faster than method 1, without significantly increasing the size of the program. If the fastest execution o f the program is needed, method 3 is 5.8 times faster than method 2. The cost of using this method is a very large co de size, which makes the program unreadable. For examp le, t o perform matrix multiplication, the code had to be divided into 14 ST blocks, due to the ST block size limitation of 0.131072 megabytes.
Method 2 was used during the implementation of predictive control on the programmable controller.
Matrix inversion can be considered a problem when solving linear equations. The methods for solving linear equations can be divided into two categories, which are:  Finite methods of solving systems of linear equations,  Iterative methods. The iterative methods are used for matrix sizes n of 3 10 or greater. The disadvantage of iterative methods is that for two different matrices of the same size, the method may require a different number of steps, compared to the constant n umb er of steps executed in a classical method. Moreover, the number of steps and the execution time of the algorithm itself significantly depend on the conditions o f t h e s ystem [33]. Therefore, when selecting the algorithm for implement at ion of matrix inversion in the MPC control, the analysis of finit e methods for solving systems of linear equations was performed.
The first method considered was the determinant met h od using the following ways to calculate the determinant o f t h e matrix and the append matrix:  Laplace's minor expansion method alo ng a ro w o r column for which the order of the algorithm is ! n It is therefore impractical [34].  More efficient Gaussian elimination method for which the determinant method has the order of computational complexity of .

5 n
The implementations of the Gauss-Jordan elimin at io n o r LU decomposition methods were considered, they h ave t he same computational complexity order of 3 2n [35] The method with lower computational complexit y is t h e Cholesky decomposition method, which uses only the L or U matrix. The cost of the algorithm's execution is h alf t h at o f the LU algorithm and its order is 3 n [35], Howev er, fo r an adaptive algorithm, it should be proved that the inverted matrix will be positively determined for each parameter value that can be derived during the estimation. Applying the Cholesky decomposition to the matrix that is not p osit iv ely defined makes that the algorithm is not numerically correct, which means that the error value can be arbitrarily large. This article has been accepted for publication in a future issue of this journal, but has not been fully edited. Content may change prior to final publication. The implemented predictive control algorithm uses RHC, therefore only the first row of the inverted matrix can be calculated. This approach is the most efficient of all described, it can be implemented using both the determin ant method and the Gauss-Jordan elimination method.
The Gauss-Jordan elimination method is more efficient , and for larger sizes of the inverted matrix, 25  n , it enables two-fold time reduction compared to full matrix inversion.
Due to the small size of the inverted matrix, the Gauss-Jordan elimination method was used with full matrix inversion, but the modification transforming t h e alg orit hm for single-row inversion is very simple. Both metho ds were built on the basis of [36].
The implementation of single-line inversio n is ju stified when we need to additionally reduce the time and/or len gth of the control horizon.

D. SHARING CALCULATIONS AM ONG CYCLES
The implementation of the predictive cont rol alg orit hm is associated with the need to perform complex calculations, the execution time of which can be long when implemented on a programmable controller.
In some cases, the computation time may exceed the maximum PLC cycle time and the control system s amp lin g time may be longer than the computation time. In th is case, we can divide the math operations into several function blocks and execute them sequentially in successive PLC cycles. Fig. 5 presents the program for dividing mathematical operations into successive cycles of controller operat ion. In this program, the calculation execution time for each function block was 1.4842 s, which means that the execution of all calculations takes 5.9368 s. This time is twice as long as t he maximum allowable cycle duration in the GE Fanuc Rx3i controller. The program ladder with set and reset coils causes that one function block is calculated in one controller cycle, so that the entire algorithm does not lead to controller crash. This solution is used for systems where the sampling p eriod is longer than the maximum cycle duration.

VII. CODE GENERATOR FOR aMPC CONTROLLER
To illustrate the implementation of the advanced control algorithm on the PLC hardware platform, the MPC [37] an d DMC [38] algorithms, and their versions with adaptatio n o f model parameters, i.e. aMPC and aDMC, were selected.
The regular approach is to create and enter the code in t h e environment for configuring and programming PLC 12 controllers. However, it was decided instead t o d evelop an individual, independent, external application in C++ that will generate a text file in ST language for the PLC with the MPC algorithm included, taking into account algorithm parameters set by the user, such as sampling, pre dictio n, and co nt rol horizons.
This section presents the MPC algorithm and the parameter adaptation procedure using the least squares met ho d. The implementation is divided into steps. The t ask o f t h e co de generator application is to fill the program content using scalar algebraic operations so as to obtain the result o f t he matrix operation intended to be implemented in a given step.
In the implemented predictive control systems, the controller was created on the basis of a non-parametric object model and had the form of a step response (DMC) or impulse response (MPC). The main feature of the discussed systems is the assumption that the process is asymp totically s table [38]. Despite this assumption, algorithms based on nonparametric models are often used because limiting only to stable processes is rarely justified [39]. Therefore, a g eneral approach is adopted in which the object is assumed t o b e one-dimensional and asymptotically stable. On the b asis o f this assumption, it was possible to develop a p ro gram t h at, based on the impulse or step response and the given prediction and control horizon lengths, would g enerat e t h e algorithm code in ST language.

A. aM PC ALGORITHM DESCRIPTION
The MPC algorithm was created on the basis of th e co ntro l object dynamics model having the form of a non-paramet ric impulse response model. A feature of the MPC algorit hm is the assumption of object stability, which in the case of impulse response allows assuming that the values of the ignored response parameters are equal to zero. The algorithm was developed on the basis of [37].
For MPC regulation, the model takes the form (11): The used model is of the moving average t ype in wh ich the coefficients of the polynomial V are the parameters of the impulse response and is therefore called the co nvolu tion al model. The model assumes that the discret e d elay t ime is equal to 1. Therefore, it is assumed that the first coefficient s of the V polynomial may be equal to 0. During the synthesis of the MPC controller, the discrete delay time was not u sed, so that in the adaptive form the controller is not very sensitive to changes in delay time. The used incremental predictor had the following form (12): where m K is the model transmittance. When applied to (11), Equation (12) takes the form (13): (13) where: Since Equation (13) uses future control values, V transforms to the form (15): (15) where: After substituting (15) into (13) we get Equation (17): It follows from Equations (16) and (17) The vector of control increments is denoted as (19): Based on (16), (17), and (18), the prediction vector can b e written as (20): where:  (23) where the value of the variable u  minimizing Eq u atio n (23) can be calculated analytically with formula (24): (24) where: o w is the reference trajectory vector o y is the prediction vector of the control ob ject o u tput.
Assuming zero increments of the control signal, the con trol signal is constantly equal to ).

(  k u
The DMC algorithm was developed on the basis of [38]. For the two examined predictive control algorithms it was assumed that the model used for approximation wo uld b e a discrete model of finite impulse response, havin g t he fo rm (25): The following relationships were used to change the fo rm of the impulse response model into the step response mo d el (26): (26) where i v are the impulse response coefficients, and j h are the step response coefficients. The purpose of the recursive algorithm based on the normalized least s quares method is to minimize the cost function consisting of the sum of squared errors with a penalty for the initial estimate where: ) (t  is the unknown vector of estimated parameters, ) (t  is the vector of previous control input values. The equations defining the algorithm of t h e n ormalized least squares method are (28) [27]:  To facilitate the implemen tation and co ntrol tests, it was decided to generate the code through application in C++. The developed application uses method 2 o f mat rix operations (described in previous section), which is a compromise between the performance and size of the program for matrix implementation and vector multiplication. The application user specifies t he len gt h o f the prediction and control horizon and the object step response vector on the basis of which the regulat or code is generated.
The algorithm of the normalized least squares method divided into individual steps is shown in Fig. 8.

C. CODE GENERATOR C++ APPLICATION
The main purpose of the developed application for generating the code for the programmable co ntroller is t o write the code in ST language based on the given step response and the given length of the control and p redictio n horizon. The developed program saves the generated code in properly titled text files. The files generated by the p rogram include: 1. The file "Initialization", containing initial values o f t h e predictive algorithm and the variables t hat s hould b e initialized in the controller, 2. The file "DMC" (or "MPC") containing the user-selected prediction algorithm, 3. The file "RLS" that contains the least squares algorithm.
The code generator program has been extended with functions in which regulator parameters are selected automatically, based on given process p aramet ers o r s tep response. The standardized least squares method, mo d ified according to [40], is used to determine o bject p arameters, assuming inertia with delay dynamics of the object. The scheme of program's operation is shown in Fig. 9.  Fig. 10 shows the graphic interface of the p ro gram. Th e type of algorithm is selected as one of "DMC, MPC, aDMC, aMPC" buttons. After selecting the algorithm, t h e u ser can enter the controller parameters, or select one of the available automatic parameter selection methods.
Step response, or the response to variable signal and set signal need to be given in text files and can be directly copied from the Matlab environment. The developed interface checks t he ent ered parameters and warns the user in case incorrect data is provided. Then, after entering the correct p arameters, t h e button "Generate code" should be pressed to save the generated code in appropriate files. The program will als o determine the expected cycle duration and t h e amo un t o f memory required. The estimated time applies to the Rx3i controller with CPE305 central unit. In order to facilitate t he use of the developed applications, programs have been b uilt that install the code generation applications along with appropriate libraries.

Software-in-the-loop
Before testing the operation of the system in a hardware loop, a discrete version of the object can be programmed o n t h e PLC and the control system can be tested using the PLC only. In the Proficy Machine Edition Logic Developer PLC environment, the data monitor window allo ws t o v iew t h e values of variables on a graph.
Figs. 11-14 show the tracking of the set trajectories.

Hardware-in-the-loop
The system located in the Computer Controlled Systems laboratory at the Gdansk University of Technology, Facult y of Electrical and Control Engineering, was used to implement the predictive control in the Hardware-in-the-loop (HIL) system. The diagram of the hardware structure o f t he system is shown in Fig. 15. This article has been accepted for publication in a future issue of this journal, but has not been fully edited. Content may change prior to final publication.  All test scenarios ended with accurate tracking of the reference trajectory. For the version with parameter adaptation, more extensive research was carried o ut aft er introducing non-stationarity in simulation model parameters. If the parameters changed slowly enough for the est imatio n procedure to capture them, and the M PC mech anis m was able to take these changes into account (the predictio n and control horizons were appropriate), the regulation was stable and qualitatively correct for all changes of gain, time constant, and delay. This proves the correctness of the structure of the code generation tool.
Along with natural advantages, such as the p ossibilit y t o synthesize the algorithm for arbitrary parameters specified by the user, the applied approach has very useful features, s uch as calculating the memory demand and the execution time o f one cycle of the controller program by the co de g enerato r application. This means that the user can conclude o n t he applicability of the controller with given parameters and t h e specific PLC CPU. Another huge advantage of the presented approach is potential code portability.

IX. COOPERATION WITH EXTERNAL COMPUTATIONAL SERVER
It is assumed in this section that due to PLC drawbacks an d limitations, the algorithm used in the control system can not be implemented in the PLC, even using the guidelines giv en in the previous section. These may be the cases which require significant computing power or, for instance, the availabilit y of libraries or specialized toolkits.

A. ALTERNATIVE CONTROL DEVICES
The article basically concerns the implementation of advanced control algorithms in a PLC hardware platform, but some of the described algorithms can also be imp lemen ted with other devices. A brief comparison is shown in Table VI.

17
A comparison of the control devices characteristics can b e found in [45]. The table has been updated and supplemented on the basis of information gathered in [46,47,48]. A detailed comparison of FPGA and DSP platforms can be found in [49]. The following categories of comparison were presented: single cycle duration, preparation for operation in industrial conditions, flexibility, scalability, predisposition to advanced control algorithms implementation and cost. Industrial applications mean not only the DIN rail mounting, power redundancy, operation in harsh industrial condit io ns, but also features related to the so-called main t enance, i.e. hot-swap and on-line redundancy and high availability guarantee. Flexibility is understood as configurability and the possibility of wide application to various purposes and industries. Scalability is the possibility of unrestricted development of the control infrastructure with growing requirements, based on the possibilit y o f s up plemen ting , expansion, without having to replace t he main p art o f t h e equipment and change the whole concept . The advanced control section addresses the ability and ease of implementing advanced control algorithms.
It should be noted that the three-scale assessments present ed in Table VI are evaluative and are the result of averaging features and opinions. For example, the price o f a PLC can range from $100 to several thousand. It should be noted t h at the target versions of a given device were taken into account, and not rapid development environmentals. For examp le, a great solution for the implementation of ad vanced cont rol algorithms can be the National Instruments cRIO s yst em, SpeedGoat or dSpace hardware platforms with Lab View o r Matlab rapid prototyping software. However, these are n ot the mainstream target industrial hardware platforms but rather laboratory R&D equipment. There has been a significant technological pro gress in t h e single board computer hardware class (also called IoT -Internet of Things platforms) due to budget Raspberry Pi o r Intel Galileo solutions. While DSP and FPGA provid e h ig h time resolution and the implementation of specialized control algorithms, it is difficult to use them to solve o ptimizat io n problems or use C/C++/Python libraries with advanced control algorithms. Basically all-purpose computers are suitable for these tasks, and recently also single-board computers. In the following chapter of the article, a solu tion based on a PLC (as the basic platform for industrial contro l) and a computing server is considered. The role of the server, depending on the computational requirements, can be performed by an industrial PC or a single-board co mp uter. The PLC and computing server set has all the advantages o f Table 6 while respecting the price and industrial co ndit ions regime. It is worth emphasizing once again that this is not t he o nly solution, but the one that is considered in the art icle wh ere PLC is the main control device.

B. PLC-PC CONTROL STRUCTURE AND REAL-TIM E OPERATION
The solution to the problem of communication bet ween t he PLC and the computing server with the provision of real-time operation is described below, while the next section presents the verification of the proposed con trol s t ructu re u sing a multidimensional non-linear object and two control methods: QDMC and robust control based on LMI.
The structure of the system with external computation server is presented in Fig. 20. A properly built control system is expected t o wo rk in t h e real-time regime. This means that after receiving the current information about the state of the object from the measurement, the control system is able to develop and provide to the object a control signal b efore t he samplin g time expires. The implementation is relatively simp le wh en performed inside the PLC, due to real-time nature of the PLC operating system. However, when the control signal is calculated outside the PLC, the round-trip communication (to and from the computing server) and the calculation t ime in the computing server must be taken into account. There are different approaches to implementing the real-time postulat e [41]. The implementation of hard real-time regime means a full guarantee of control signal calculation in a preset t ime. This is achieved by a fully deterministic approach t o b oth communication and computing. There is also a soft real-time approach, in which incidental overruns of computation times may occur. Soft real-time systems are usually no t b ased o n guarantees, but on practical approach and analyses of regular performance of individual elements composing t he co ntro l system. The specificity of simulation with real-time mo d els is also presented in [42]. The soft real-t ime ap proach was used as a prototype solution in this article. Th e co mp utin g server was a computer with OS Windows 10 wit h M at lab Optimization Toolbox software and YALMIP library [43]. The communication ma de use of the Modbus TCP p ro t ocol and the PLC built-in communication mechanism asynchronous to the cycle based on the Direct Memory Access.
After receiving the new measurement information from the object, the PLC sets a flag in the form of a discrete v ariable about the availability of new data. The external co mput ing server scans frequently whether this flag is set. If so, the new data is downloaded from the PLC to the server, t he flag is cleared, and the data is used to calculate the co ntrol s ig nal which is then sent to the PLC after the calculation. A not her flag is used to mark a new control signal. A reasonable supplement to the above solution is to develop a strategy for situations in which an ext ernally g enerated control signal does not come. This may have a form of maintaining the previous control signal, or a lo o k-up t able solution, or using a simpler algorithm executed in the PLC to ensure suboptimal but object-safe control.
For presentation purposes it was assumed that the controlled plant operates with the step of 1 s. The conclusions from the performance analysis of individual system components are as follows: the one-way communication usually takes less than 1 ms, while the calculations in the external server do not exceed 200 ms, an d their time duration depends on the control algorithm used. In this way, a real-time working effect is achieved, wit h out a guarantee but with practical confirmation resulting from hours of real tests.
For industrial applications, the above-presented id ea is fully applicable, but the hardware and software parts s hou ld be replaced with hard-real time solutions. That means t ha t a real-time network should be used, Profinet for instance, t h e computing server should work with a real-time system, e .g . RT Linux or QNX, and the calculation software should guarantee finite and predictable computation time.

C. THE CONTROL OBJECT -CSTR
A continuous stirred-tank reactor (CSTR) was selected as an example of control object. This plant is non-linear an d h as two inputs: flow rates F1 and F2 of the liquid with concentrations c1 and c2, respectively, and two ou tputs: t h e volume V of the liquid in the tank and the concentration c o f the liquid flowing out of the tank through free outflow. Fig .  21 presents a schematic of the plant.

D. QDM C REGULATOR FOR M ULTIVARIABLE CONTROL WITH CONSTRAINTS
The optimization problem in the predictive control algorithm with constraints on inputs, outputs, and input increments fo r the cost function J cannot be solved directly in PLC. However, the problem can be turned into a quadratic programming problem that will be solved on an external computing server. The constrained optimization problem after transformation is presented as (30): given by (31): (31) Matrix H in (30) is called the Hessian, while T c is the gradient, and u  is the control increment.
The above predictive control algorithm with co nstraint s performs the task of tracking the reference trajectory [38].

E. LM I BASED REGULATOR FOR M ULTIVARIABLE ROBUST CONTROL
Classic predictive control algorithms use models with constant parameters and structure, which d o n ot t ake in to account the influence of disturbances an d u ncert aint y o f parameters. The solution to this problem is robust predictiv e control. In [44], the authors present an approach t o ro bust predictive control using linear matrix inequalities (LMI).
The uncertain system is the system whose parameters change over time, which can be described as (32):  (33) where Co refers to a convex shell and L is the number o f it s vertices.
The robust predictive control algorithm wit h an in fin ite prediction horizon uses the cost function in the form (34): The optimization problem is defined as (35): The min-max approach consists in determining the controls on the control horizon m as a result o f min imizin g the cost of the worst case.
The given problem, although convex for a finite m, is computationally insolvable [44]. However, it can b e s olved by specifying the upper limit of the objective function.
After transformation, the optimization problem can be written as the minimization problem with linear matrix inequalities LMI in the form (36): (36) and constraints (37) and (38): where the matrix F is determined as (39): The robust control algorithm with input and output constraints determines the control by solving the optimization problem (40): with constraints (41), (42), (43) and (44): The aim of the presented algorithm of rob ust p redictiv e control using linear matrix inequalities is to bring the s tat es to the zero state, and thus bring the o b ject t o t he s elected operating point.

F. VERIFICATION RESULTS
The performance of predictive control with constraints was tested using HIL. The optimization problem was resolved o n a PC in the Matlab environment. The calculated controls were sent to the programmable controller, which then controlled the object in the form of a model in the Matlab/Simulink environment on a PC. Figs. 22 and 23 show the results of tracking the set trajectories for the output volume V and concentration c. Similarly, the robust predictive control algorithm with constraints was tested in the HIL loop. The optimization task was performed o n a PC in the Matlab environment with YALIMP. The designated control signals were sent to the programmable controller, and then to the object in the form of a model in ano ther Matlab/Simulink. Figs. 24 and 25 show the effects of forcing the outputs to the values appropriate for the selected operating point for the volume V and concentration c, at t h e base value of concentration c2=0.1.     The use of the external computing server allowed the implementation of complex predictive control algorithms that could not be implemented on the programmable cont roller. The two presented algorithms worked in soft real-time regime and allowed for controlling a nonlinear and multidimensional object with constraints, as well as ro bust control. The time of calculating the control signals and communication with the controller was shorter than the sampling time of the object. The algorithms enabled tracking the reference values of object states, as well as the fulfillment of certain constraints on inputs and outputs.

X. CONCLUSIONS
PLCs usually work with implemented simplest control algorithms or as part of a hierarchical control system, wh ere the PLC receives from another device a setpoint to be maintained. This article shows that with some p rep arat ion effort, it is possible to implement advanced control algorithms on the PLC platform.
PLC limitations concerning cycle times, memory sizes, and the lack of support for matrix arithmetic operat ions are widely discussed. A general method of implementing algorithms described by difference equations is p resent ed. The properties of individual methods of multiplicat ion an d subtraction of key matrices for the implementation of advanced control algorithms in the presence of strong limitations of the PLC platform are carefully considered.
The implementation of aMPC and aDMC algorithms was developed, which allowed for regulation of non-station ary objects with large and time-varying delay. The d ev elop ed application produces the code for the PLC, but aft er min o r changes it can also do it for microcontrollers, s in gle -board computers, or industrial computers. If more complex algorithms need to be used, the concept of dividing calculations between PLC cycles is presented, as a consequence of which the time of one cy cle is n ot a fin al limitation anymore. The most advanced control methods can be implemented using the presented concept of PLC cooperation with an external computing server. Th e mu lt idimensional predictive control with input and output constraints for a CSTR plant was presented. In order to prove wide possibilities of the proposed solution, the concep t o f a robust control based on an external solver and lib raries fo r LMI was included. The verification using the hardware -inthe-loop structure as close as p ossib le t o real co ndit ions confirmed the correctness of implementation and the usefulness of the presented methods.