PLC Programming Based On Applied Games
PLC Programming Based On Applied Games
PLC Programming Based On Applied Games
Supervisor
Examination Committee
November 2019
Declaration
I declare that this document is an original work of my own authorship and that it fulfills all the
requirements of the Code of Conduct and Good Practices of the Universidade de Lisboa.
ii
Resumo
Most common tasks in automation, as sorting, batching, palletizing, or pick and place, are im-
plemented based on Programmable Logic Controllers (PLCs). Programming PLCs requires
skilled developers and implies careful debugging, due to using standard PLC programming
tools which lack e.g. warning against simultaneous access to non-shareable outputs. Resorting
to Discrete Event Systems (DESs) theory that enables designing novel programming method-
ologies. DESs in the vein of Petri nets or, more specifically, Interpreted Petri nets (IPNs), allow
representing many industrial systems. We consider supervised IPNs to approach the objective
of controlling the usage of non-shareable resources.
Programming PLCs usually requires access to the industrial systems, hardware, to be super-
vised. Having to pause industrial processes, or creating hardware prototypes, for programming
and debugging is often too expensive. A nowadays alternative is using virtual systems. Virtual
systems are graphical computer simulations that can bring the industrial plants realism to the
programming environment. They give more safety and cost efficiency to the PLC programming
works.
In this thesis we create a toolchain for PLC programming. We consider a DES graphical
editing interface, in a specific class of Petri nets (PN) containing signal inputs and outputs,
namely the IOPT tools by UNINOVA. We propose a software toolbox, working on the IOPT
representation, converting Petri nets to a PLC programming language, Structured Text (ST).
The conversion tool includes automatic code generation to detect and handle PLC outputs used
simultaneously or at multiple points of the code possibly running in parallel.
We demonstrate our toolchain automatically supervising shareable or mutually exclusive
resources, considering a industrial PLC programming environment, Unity Pro from Schneider,
and a 3D environment simulator, Factory IO from Real Games company.
Keywords: Discrete Event Systems, Programmable Logic Controllers, Petri nets, Virtual Games,
PLC Software, Structured Text.
vi
Contents
Declaration i
Resumo iii
Abstract v
1 Introduction 1
1.1 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Objectives and Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Thesis Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Background 5
2.1 Discrete Event Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Petri nets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.1 Petri net Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.2 Incidence Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.3 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.4 Supervisor based on Linear Constraints . . . . . . . . . . . . . . . . . 12
2.2.5 Mutual Exclusion Problem . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2.6 Readers-writers Problem . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.7 Generalized Linear Constraints . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Interpreted Petri nets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Input-Output Place-Transition Petri nets . . . . . . . . . . . . . . . . . . . . . 19
D Structured Text Program for Factory IO: Alarm and Keypad System 85
List of Figures
4.1 Flowchart of pnml.m function. Produces a .mat file containing all information
regarding the Petri net subclass to be used by the ST generator . . . . . . . . . 30
4.2 Example of shared output conflicts in GRAFCET. Steps 2 and 3 run in parallel
making undefined the output A. . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.3 Example of shared output conflicts in SFC, Unity Pro by Schneider. Step S_1_1
runs in parallel with S_1_18 and S_1_5 in parallel with S_1_8. Both cases of
parallel steps have conflicting instructions for the output. Higher numbered
steps decide the output in this example. . . . . . . . . . . . . . . . . . . . . . 36
x LIST OF FIGURES
4.4 Algorithm to implement mutual exclusion on places actuating the same output.
The input and output of this algorithm are both IOPT nets. The resulting IOPT
net has outputs actuated by single places added as supervisors. . . . . . . . . . 37
4.5 Algorithm to implement limited user of resources. The input and output are
both IOPT nets. The resulting Petri net has places actuated by single places
computed as supervisors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.6 IOPT Petri net model without and with supervision for limited resources of
simultaneous processes, respectively (a) and (b). . . . . . . . . . . . . . . . . . 39
4.7 Algorithm to handle shared outputs. The input and output are both IOPT nets.
The resulting Petri net has shared outputs actuated by single places computed
as supervisors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.8 Application of the proposed algorithm to solve a conflict in a IOPT net. . . . . 41
C.1 Concrete Mixer Representation(a) and IOPT Tools Concrete Mixer Petri net (b) 84
List of Tables
C.1 Sensors for the IOPT Tools Concrete Mixer Petri net . . . . . . . . . . . . . . 84
C.2 Actuators for the IOPT Tools Concrete Mixer Petri net . . . . . . . . . . . . . 84
xii LIST OF TABLES
Chapter 1
Introduction
Professionals developing and installing industrial processes foresee Programmable Logic Con-
trollers (PLCs) to remain the central processors for manufacturing processes and production
lines. Therefore, will continue the interest of creating tools to assist PLC programming learners
and developers. One way to create novel programming tools is reverting to the theory of Dis-
crete Event Systems (DESs), as these systems effectively represent many of the real systems
created with PLCs.
Current Industrial Automation courses already teach solving automation projects using DES
and Supervisory Control theory. These courses involve modeling techniques such as Petri nets
(PN) and GRAFCET, supported by advanced integrated development environments (IDEs).
IDEs are limited mostly in aspects of system analysis and mathematical approaches. In this
thesis we introduce more interactive and immersive way of implementing supervised DES. We
consider a particular Petri class that can be categorized by how it evolves state to state, which
is named Input-Output Place Transition Petri nets (IOPT Petri nets). Our approach is based on
using a virtual manufacturing environment complemented by Discrete Event Systems theory.
Virtual systems are graphical computer simulations that can bring the industrial plants re-
alism to the programming environment of PLCs. Easily controlled by simulated or hardware
devices, they give undoubtedly cost and safety efficiency to control programmers. Virtual game-
based systems can not only motivate teachers and students, but also can significantly improve
the situation awareness of the learner while providing them training for the most common tasks
in automation (i.e sorting, batching, palletizing, pick and place).
In this thesis, is used a software package from Real Games Company and is created a set of
software development tools (toolchain) for PLC programming allowing to implement automat-
ically solutions for occurrences of multiple, simultaneous, outputs.
2 Introduction
Background
In this chapter Discrete Event Systems (DES) are introduced. In order to study and control
DESs we briefly present Petri Nets. More specifically, Petri nets will be used in the thesis
for designing supervisors for DESs. Then we introduce Interpreted Petri Nets (IPN) and IOPT
Petri Nets, as ways to include inputs and outputs directly in the models. Representing inputs and
outputs is necessary for the thesis as information guiding the design of the supervisors. This
introduction uses content from the course Industrial Processes Automation 1 and from other
references locally referred.
it but this representation can sometimes be a difficult task when studying complex systems.
Therefore, the DES theory provides several modeling tools for that purpose. These tools in-
clude analysis, performance, control and scheduling applications. DES also include requisite
properties to help achieve the desired and controlled behavior of these systems. In this thesis,
we ensure to give more significance to the proprieties that help prevent the most frequent PLC
programming mistakes.
Nowadays, modern industry heavily relies on automation engineering which can be well
represented by DES, mostly because many technologies are indeed discrete-state systems and
the diverse machinery can be implicit as states between On and Off or Busy, Idle or Down. In
manufacturing systems for example, an event can be the input of a part into a conveyor belt or
an arrival of that part to the end of the conveyor belt. Figure X below describes the arrangement
of manufacturing system composed by two industrial machines and three conveyor belts.
The initial state of the layout can be named State "‘0"’. Inserting a new part on conveyor
belt C1 is an event, that is associated to a change of state. State "‘0"’ turns into State "‘1"’
characterized by the transportation of a part on C1 until the stopper, where a photo-sensor is
positioned to detect the part’s arrival. The system then evolves to, and stays in another State,
"‘2"’ while the machine M1 is handling the part. Similar behavior is extended to the rest of the
production line. Obviously, the conveyor belts, usually named buffers, which act as an abstract
identity in a DES, have a restricted capacity and a limit to the transporting rate of parts to be
manufactured or delivered, therefore, the remaining production line ahead can be in an idle
mode, waiting for parts, and this fact gives birth to a characteristic typical of queueing systems.
Consequently, synchronicity problems might emerge in more complex systems where there
is parallel production of different parts, like it is showed in the Figure Y below, where the
2.2 Petri nets 7
parts are brought by the conveyor belts C1 and C2, manufactured by machines M1 and M2 to
be assembled together by a robot arm R, that will be waiting at the end of the conveyor belts
and then grab a part at a time and do the assembly. These circumstances demand that a more
restricted system is modeled and controlled.
One finds various tools helpful for the study and development of DESs. The parallel working
nature of the components of a DES usually leads to a difficult overall understanding of the
system. Graphics tools in many cases allow the overall understanding of the system. Examples
of DES graphical modeling tools are : state-transition diagrams or finite-automata, reactive
(real-time) flow diagrams, statecharts, Petri nets, etc.
Combined with algebraic tools and the remaining tools of DES, further specifications will
lay the foundations to the implementation of PLC programming languages. Even though, the
study of DES and these specifications is not necessarily needed to program PLCs, it is in most
cases an advised procedure to ensure the proper behavior of the system being modeled.
Definition 1.1: From [22], a Petri net is a quintuplet, that is represented by (P, T, I, O, µ0 ),
where:
2. T = {t1 , t2 , t3 , ..., tm }, m > 0, T is a set of transitions, that represents events that can or
not happen.
Based on Petri net example represented in the Figure , according to the Definition 1.1 the
quintuplet (P, T, I, O, x) is given by:
P = {p1 , p2 , p3 }
T = {t1 , t2 }
I(t1 ) = {p1 , p2 }, I(t2 ) = {p3 }, I(ti ) = {I(t1 ), I(t2 )} = {p1 , p2 , p3 }
2.2 Petri nets 9
Definition 1.2 (alternative definition of Petri net): From [4], a Petri net is a quintuplet, that
is represented by (P, T, A, w, x), where:
2. T = {t1 , t2 , t3 , ..., tm }, m > 0, T is a finite set of transitions, that represents events that
can or not happen.
4. w : A → {1, 2, 3, ...}, w is a weight function, that stores the weight of each arc. Graph-
ically, the weight of each arc (w(tj , pi ) or w(pi , tj )) is represented by one arrow and a
subscript with the weight.
5. x = x(p1 ), x(p2 ), x(p3 ), ..., x(pn ) ∈ N n , x are the markings of places.
It is considered the Petri net is composed by a single graph and all the nodes, Places or
Transitions are connected between each other.
Based on Petri net example represented in the Figure , according to the Definition 1.2 the
quintuplet (P, T, A, w, x) is similar to before except for:
In a Petri Net, a transition tj ∈ T is enabled if x(pi ) ≥ w(pi , tj ), which means when the marking
of place p1 is at least greater than the weight arc that connects the place pi .
10 Background
Considering the Petri net in Figure 2.3, we obtain the following incidence matrix,
−1 1
D = −1 1 (2.2)
1 −1
where the places are related to the rows and the transitions are related to the columns of D.
If a transition tj , is reached from place pi , the value of entry (i, j) on D is −1. In the same
sense, if a place pi , is reached from transition ti , the value of entry (i, j) on D is 1.
The Petri net’s dynamics can be described in equations. The state’s evolution of the Petri
net in function of the current marking µ; the marking to be reached µ(k + 1), the firing vector
q and the incidence matrix D is given by:
This incidence matrix D balances the number of tokens. It can be separated in two matrices
D+ and D− :
[D = D+ + D− ] (2.4)
The transitions are enabled to fire as a form of inequality formally presented below:
2.2.3 Properties
Property 1. Reachability: The result of firing a transition is a new state or a new marking.
We say that this state is reachable from the previous state and we can define a Reachable set of
a Petri net, R(N ), to be all marking reachable from a initial marking x0 . In the Figure 2.4 is
shown, for the same Petri net example, the reachability tree, a graphical representation of all of
its reachable states.
Property 2. Boundedness: Modeling for example a simple queueing system, it is undesir-
able to allow a queue to grow too much because it means customers will have to wait too lng.
2.2 Petri nets 11
Boundedness is a propriety that checks if the number of tokens for all the places are limited by a
given positive integer. Unbounded growth of a Petri net marking can lead to instability. A petri
net isn’t bounded if a number of tokens in a place can become indefinitely large. A place pi ∈ P
is said to be k−bounded or k−safe if, for all possible markings x0 = (x01 , ..., x0i , ..., x0N ) ∈ R(N )
if
x0i ≤ k
Property 3. Safeness: A place pi ∈ P is safe if for all reachable states x0 ∈ R(N ) of the
Petri net, from a specific initial state x0 , if the number of tokens in that place is equal or lower
than one:
x0i ≤ 1
A Petri net is safe if all the places in the net are safe. While modeling an example with tran-
sitions without input places, we can make the Petri net safe, preventing these transitions from
being always enabled.
Property 2. Coverability: A state of a Petri net is covered by a previous state if it
belongs to the reachable set of the previous state’s respective marking. Given a Petri Net
N = (P, T, I, O, x0 ) with initial marking x0 , and x0 , x00 ∈ R(N ), if
number of tokens for all states with respect to the weights of the transitions that assign each
state ensuring that resources are not lost or gained. If for every marking, the number of marks
remains the same, a Petri Net is strictly conservative. In a formal representation, a PN N =
(P, T, I, O, x) is strictly conservative if for every marking x0 ∈ R(N ),
X X
x0 (pi ) = x(pi )
Property 6. Liveness: A Petri net with a certain initial state x0 , is live if there is a possible
firing path that will enable any transition reached from that initial state. A transition in a Petri
net can be:
1. L1-live, if there is some firing sequence from the initial state such that the transition can
fire at least once;
3. L3-live, if there exists some infinite firing sequence in ehich the transition appears in-
finitely often;
4. L4-live or Live, if the transition is L1-live for every possible state reached from the initial
state.
be computed using matrices. The supervisor is to prevent the system from reaching markings,
which do not satisfy a set of a number of linear constraints, a matrix since we want a number of
restraints for each place of the Petri net. This can be represented by a condition using algebra
Lµp ≤ b (2.6)
where L is an integer nc × n matrix (nc is the number of constraints, n is the number of places
of the given Petri net), b is an integer column vector, and µ is the Petri net marking.
The supervisor initial marking is
when b − Lµ0 = 0 otherwise the supervisor cannot be designed using this formalism.
The supervisor incidence matrix is
Dc = −LDp . (2.8)
µ2 + µ4 6 1 (2.10)
(a) (b)
Figure 2.5: Mutual Exclusion problem, markings of p2 and p4 denote number of parallel pro-
cesses. Without supervision, they are allowed to work simultaneously. (a) Petri net with a
mutual exclusion problem (b) Same Petri net with supervision
With these results we can obtain the incidence matrix and initial marking for the new super-
vised Petri net:
−1 1 0 0 1
1 −1 0 0 0
D=
0 0 −1 1
µ0 =
1
(2.11)
0 0 1 −1 0
−1 1 −1 1 1
Figure 2.5(b) shows the Mutual Exclusion solution. It prevents that the critical sections of
the different processes operate simultaneously. The critical sections of the two processes are
composed by place p2 and p4 . The additional place pC makes sure that each process can only
execute its critical section if the other process does not. Simply because when the transition t1
is fired, the place pC loses its token and the transition t3 will no longer be enabled to fire until
transition t2 is fired allowing place pC to recover a token.
2.2 Petri nets 15
(a) (b)
Figure 2.6: Readers-writers problem, markings of p2 and p4 denote number of active readers
and writers. Without supervision, readers and writers are allowed to work simultaneously (a).
With supervision, one active writer implies no other writers and no readers (b).
The solution is not allowing reader processes to modify the shared resource while a writer
process is modifying it and also to make writer processes mutually excluded from each other.
This operation is controlled designing a way to permit multiple reader processes accessing the
shared resource simultaneously while the writer process is idle. This is done with a place that
tracks when a writer process finishes and how many reader processes can take place, and also
works as a counter that needs to be zero for a writer to begin writing.
The incidence matrix and initial marking are the same as before (2.9). The linear constraint
can be written as:
µ2 + nµ4 6 1 (2.12)
Therefore, L = [0 1 0 n] and b = 1. Given the constraint we can obtain the incidence matrix
and initial marking for the new supervised Petri net DC = −LDP = [−1 1 − n n] and
µC0 = b − LµP0 = n. The supervised system is characterized by the incidence matrix and
16 Background
−1 1 0 0 s
1 −1 0 0 0
D=
0 0 −1 1
µ0 =
t
(2.13)
0 0 1 −1 0
−1 1 −n n n
This solution, supervised system, is shown in Figure 2.6(b) where the additional place pC
forbids transition t1 while a writer process is occurring and forbids transition t3 to prevent more
writer processes and t1 . The place pC also prevents the firing of t1 if the maximum allowed
number of reader process is reached.
More classes of constraints are found in supervisory control theory to approach problems as
deadlock prevention, liveness or fairness enforcement. To handle the wider variety of cases, the
constraints are grouped in a more general inequality, the so called generalized linear constraints:
where qp is the firing vector and describes the transitions that can occur at a certain instance, qpi
is set to 1 if the transition ti is to be fired next, or else qpi = 0. νp is the Parikh vector, a state
variable that indicates how many times each transition has been fired since the initial marking
µ0 . µp is the marking vector for system. This classes of constraints are enforced by monitors.
µ1 q1 v1
µ2 q2 v2
µ= .. q = .. v= .. (2.15)
. . .
µp qp vp
As proven by Iordache and Antsaklis [12], a generalized linear constraint 2.14, is enforced
by a optimal supervisor with incidence matrices,
The Parikh vector v and the integer matrix C can be interpreted as a dynamic state-feedback
which enforce: Cv 6 b This is useful in systems that can be modeled multiple asynchronous
processes, where the resources are shared and there is a need to is for allocation of resources
and to limit to a number.
and
F u k ≤ xk , (2.20)
that describes a Petri net marking development, can be successfully used for modelling DES
when all the places are measurable and all transitions are controllable.
Definition 1.2: An IPN system is a 10-tuple,
X
Q = (P, T, A, w, x, , Φ, λ, Ψ, φ) (2.21)
where:
P
• = {α1 , α2 , α3 , ..., αr },, is the input alphabet with αi , i = 1, ...r being the input sym-
bols.
18 Background
• Φ = {δ1 , δ2 , δ3 , ..., δS },, is the output alphabet with δi , i = 1, ...S, being the output sym-
bols;
P
• λ:T → ∪{ε} is a function that labels the transitions. Either an input symbol αi ∈
P
or the ε is assigned to each PN transition by this function, ε represents a system
internal event externally uncontrollable. If λ 6= ε then transition ti is said to be controlled,
otherwise uncontrolled. Tc and Tu are the sets of controllable and uncontrolled transitions.
Of course, T = Tc ∪ Tu ;
• Ψ : P → Φ ∪ {ε} labels the places. Either an output symbol δi ∈ Φ or the null event ε
is assigned to each PN place by Ψ. P = Pm ∪ Pnm where Pm and Pnm are the sets of
the measurable and unmeasurable places. Ψ(pi ) = δk if pi represents an output signal,
otherwise Ψ(pi ) = ε which assigns a null event ε;
• φ is the output function assigning the output vector yk = φxk to the Petri net state vector
xk . The entries of the output vector yk represent the states of measurable places.
Figure 2.7 illustrates differences between a Petri net without and with interpretation. For
example, see in figure 2.7(b) that transitions t1 and t5 are controlled by the inputs a and b, and
that places p1 , p5 and p6 are measured, i.e. generate outputs δ1 , δ2 and δ3 , respectively.
N = (P, T, A, w, IS, OS, IE, OE, ov, ie, oe, sig, soa, M ) (2.22)
20 Background
where:
2. T is a set of transitions.
11. isg is an input signal guard partial function applying transitions to boolean expressions
(where all variables are input signals): isg : T → BE, where ∀eb ∈ isg(T ), V ar(eb) ⊆
IS.
12. ie is an input event partial function applying transitions to input events: ee : T → IE.
13. oe is an output event partial function applying transitions to output events: ee : T → OE.
14. osc is an output signal condition function from places into sets of rules: osc : P →
℘(RU LES), where RULES ⊆ (BES × OS × N ), BES ⊆ BE and ∀ e ∈ BES,
V ar(e) ⊆ M L with M L the set of identifiers for each place marking after a given execu-
tion step.
Table 2.1 briefly compares Interpreted Petri nets (IPNs) and IOPT nets. While the structure
(graph) definition is equal, some differences are found in the definition of inputs and outputs,
where IPNs have a more formal representation while IOPT nets have a more computational
form of representation.
2.4 Input-Output Place-Transition Petri nets 21
N = (P, T, B) N = (P, T, A)
P is a finite set of n places P is a finite set of places
T is a finite set of m transitions T is a finite set of transitions
B represents the edges A is a set of arcs
M0 M is the marking function
Virtual systems are graphical computer simulations that can bring the industrial plants realism
to the learning environment of classrooms. Easily controlled by simulated or hardware devices,
they give undoubtedly cost and safety efficiency to the training of control programmers. Virtual
game-based system can not only motivate teachers and students, but also can significantly im-
prove the situation awareness of the learner while providing them training for the most common
tasks in automation (i.e sorting, batching, palletizing, pick and place).
In this chapter is introduced software Factory IO, by Real Games Company, and a way of
using that software as a educational toolchain for PLC programming training. In this chapter
we describe the software setup vital to reach our goal of assigning input and output signals of
a Programmable Logic Controller (PLC), virtually simulated by Unity Pro, to control a virtual
game-based environment named Factory IO.
documentation, programming and communication, and develops International Standards for all
electrical, electronic and related technologies. On this thesis, we will be using the IEC Standard
61131-3 like the one used on the course of Industrial Processes Automation. The Part 3 of IEC
61131 deals with basic software architecture and programming languages (LD, FBD, ST, IL
and SFC) of the control program within PLC.
in this software, we have at our disposal a generic configuration of in its coordination can be
achieved with four Actuators and three sensor connections. Factory IO provides an interface to
effectively manipulate the robotic arm, the conveyor belt and in real-time or externally automate
its behavior with programmed logic using with active input and output connections.
To build a system in Factory IO, one finds several types of sensors, namely Capacitive,
Diffuse, Inductive, Retroflective, Vision, Light Arrays and others sensors (see Figure 3.3). Ac-
tuators can be found integrated in stations like the Machining Center, Elevator, Pick & Place,
Stacker Crane, Rack, Palletizer and Tank. With this software is unnecessary to connect the
machinery, conveyor belts, panels to a power source, motor drives, robot controllers or power
electronics of any kind providing a clean and simplified cable free environment.
To fulfill this thesis we aim to use a PLC programming language compiler and since Struc-
tured Text’s syntax as pure text, it is easier to translate from the modeled system as DES to the
PLC integrated development environment. To implement projects in programming language
Structured Text, we will be using Schneider Unity Pro in simulation mode, and simulate an
M340 PLC, represented in Figure 3.1, with a Modbus server connected to Factory IO running
as a Modbus TCP/IP client as we illustrate below in Figure 3.4.
26 Real and Virtual Industrial Setups
Figure 3.4: Software setup: connection between Unity Pro and Factory IO
Markup Language (PNML) in XML-based interchange format for modeling. The toolchain in-
cludes software, described in next chapter 4, to retrieve the information from the IOPT Petri net
model created by the user in that environment and then redefines the model with characteristics
of the Petri net extensions studied in chapter 2. After that, there is a phase of potential con-
flicts identification to which our toolchain proposes to the user a list of solutions of Supervisory
Control based on DES.
According to the user’s options, a Structured Text code is generated and prepared to run
in the PLC programming software Unity Pro, a compiler equipped with a PLC simulator that
will be connected to virtual DES simulator Factory IO (section 3.2). Observing the simulation’s
behavior, the user can verify if the model meets specifications interacting and testing the virtual
scene.
28 Real and Virtual Industrial Setups
Chapter 4
In this chapter is described the central component of the toolchain, the Structured Text generator,
how it is organized and how it is designed for PLC programming.
Usually, PLC programming is done with Ladder Logic and or GRAFCET which allow the
development of programs layered by several subroutines or files. However, it becomes a difficult
task to predict the consequences of uncertain inputs due to damaged input switches or sensors.
In this thesis we will be using Structured Text for its familiarity to high programming languages
and for its non-graphical characteristic facilitating the development of our toolchain.
The next sections detail the program functions and the different steps involved in converting
a DES to a PLC Program format. It is also taken into account output conflicts while modeling a
system with Petri nets and how to handle those conflicts.
The PN subclass definition is done thanks to the function ’pnml.m’. The function reads the
pnml extension file that contains information about the IOPT Petri net: (i) Petri net 5-tuple; (ii)
30 PLC Control of Discrete Event Systems
Input-Output signals and Events; (iii) type of transitions and their respective priorities. Finally
the function stores in a mat extension file all the necessary information regarding a Petri net
subclass.
Figure 4.1: Flowchart of pnml.m function. Produces a .mat file containing all information
regarding the Petri net subclass to be used by the ST generator
Function pnml(’IOPT_Petri_net.pnml’)
Several routines are applied while reading from the file containing spec-
ifications of the IOPT Petri net model. The program extracts content
Description and accordingly produces lists of related information about the Petri net
places, transitions, arcs, input signals, output signals, and determines
the incidence matrix and initial marking matrix.
ST construction is done thanks to the function ’ST.m’ (see Appendix A). This function re-
ceives a Petri net subclass definition and generates PLC code. The .mat extension file produced
by the function ’pnml.m’ contains cell arrays with transition and place lists, respective informa-
tion related to the set of input signals and output signals and other relevant information about
the Petri net that the ST generator uses to produce the PLC code.
As it was studied in chapter 2.2, according to the Petri net dynamics equation 2.3, the mark-
ing of the net reached depends which transitions become enabled to fire. In IOPT Petri nets
defined in section 2.4, transitions become ready to fire by conjugating conditions of multiple
signals states, or by events (a signal turning ON/OFF) consequently producing output signal
bits associated to the marking of the net reached. In IPN nets defined in section 2.3 there can be
system internal events externally uncontrollable which in the Petri net subclass used by the ST
generator are associated to the transitions without IO signals information attached.
The Petri net subclass definition used by the ST generator incorporates the properties just
described of Petri net classes and also includes a characteristic from T-timed Petri nets [5]
which is the possibility of associating transitions to time units. This allows the transitions to
32 PLC Control of Discrete Event Systems
only fire a specific interval of time after they become enabled and ready. This set of transitions is
named timed transitions. We make restricted use of IOPT Tools and only consider input related
transitions and output related places in the Petri net subclass used by the toolchain in order to
generate PLC programs resembling the functionality of a Moore machine, whose output values
depend only on its current state.
The ST construction starts with memory mapping used to save the Petri net places marking,
purposely saving the memory %M0 to be used by the virtual simulator to initialize the Petri net
when running the 3D simulation.
The program uses memory positions to represent each place’s current marking starting from
’%MW101’ (corresponding to the first place of the net p1 ). Initially, these memory positions
hold no values and are set values corresponding to the initial marking of the net when starting
the virtual simulation.
The memory mapping for the inputs signals and outputs signals of the system was done
accordingly in order to synchronize the Structured Text’s variables with the virtual simulator
variables. The mappings begin with the input listing between %M1 and %M(m), m being the
total number of inputs, followed by the mapping is completed with the output listing using n
more memories between %M(m) and %M(m+n).
The ST construction continues by determining the conditions that enable each transition to
fire, the conditions that each transition needs to be ready, and output signal bits each place pro-
duces. In the code generated, each transition is associated to an IF, THEN routine in Structured
Text language given as:
The strings ’Fireable conditions’, ’Consume marking’ and ’Produce marking’ are created
from information regarding how the net evolves and are determined using the Petri net dynamic
equation 2.4. The ’Enabling conditions’ strings, written according to the definition in 2.22,
verify the Guard Condition and Input Event of each transition. The ’Produce Output Bits’
strings are written according to the set of output signals of each place according to the same
definition.
Timed transitions are associated to an alternative routine in Structured Text to consider the
elapsed time since the transition was enabled. The program translates the each timed transi-
tions to timer functions ’MY_TON’ in Structured Text. A timer starts when a timed transition
becomes enabled and the transition fires when the counting reaches the value of time units
specified in Petri net subclass model.
Structured Text ready to run in Schneider’s Unity Pro freeing the user from repetitive rewritings
of the programming language code in the software despite still being needed configurations of
the software’s Data Editor in order to define the necessary variables.
Figure 4.2: Example of shared output conflicts in GRAFCET. Steps 2 and 3 run in parallel
making undefined the output A.
GRAFCET does not function with scanning cycles of inputs but SFC in Unity Pro and
other PLC programming softwares, by definition, run accordingly to a PLC scan cycle creating
necessarily an instruction sequence which, ensures the SFC model to be deterministic when
preditcting an output in a shared output conflict. In SFC there is a sequence of actions therefore
the output is not random.
Analysing the figure 4.3 it is illustrated this situation and we can see that mutual exclusive
events, in this case, the lastly performed event is the winner. However, it is not so obvious to
determine how an output behaves if it is shared by parallel steps simultaneously active. There
can be less evident examples if a shared output will be 0 or 1 if only the programmer dismisses
the step numeration.
Figure 4.3: Example of shared output conflicts in SFC, Unity Pro by Schneider. Step S_1_1
runs in parallel with S_1_18 and S_1_5 in parallel with S_1_8. Both cases of parallel steps
have conflicting instructions for the output. Higher numbered steps decide the output in this
example.
We propose detecting automatically that a program has an output set at multiple coding
points. After identifying a possibly conflicting situation, we flag the situation to the programmer
and suggest alternative ways to handle the conflict: (i) setting mutual exclusion on the access to
the output, (ii) allowing a limited number of places accessing simultaneously the output or (iii)
allowing an arbitrary number of places accessing the output while defining, e.g. the output is
ON if at least one place imposes that. Cases (ii) and (iii) will be considered in the next sections.
In the next paragraphs we consider way (i).
Having detected an output that can be actuated at different places, possible simultaneously,
here we detail a solution based on DES Supervisory control for mutual exclusion of that output.
This solution is based on examining the (Interpreted) Petri net and finding critical sections
where multiple places actuate the same output.
The synthesis of this method, shown as pseudo-code in figure 4.5, is divided in two main
parts: the first is detection of critical sections in the Petri net; the second part is the formulation
of the constraints based on the supervisor theory studied in section 2.
The algorithm searches for sets of places Pi actuating on the same output qi along with their
respective sets of transitions Tj and Tk connected to them. And adds an extension to the net
while also modifying the net’s places pi outputs and the transitions tj and tk . For each set of
places Pi actuating on an output qi , a supervisor DCi is computed using (2.6), (2.7), (2.8) which
becomes an extension to the initial net. In the end we update the control action of the added
unmeasurable place invariant with the f lags output in order to turn ON the flag variable when
the system is using a mutual exclusive output.
When transitions any tj ∈ Tj fire, the f lags is turned ON meaning the mutual exclusion
output qi is being used by a process. When transitions tk ∈ Tk fire, the f lags is turned OFF
meaning the mutual exclusion output qi is not being used by any process. Transitions tj only
fire if f lags is OFF.
% algorithm
find Pi = set of places turning on/off an output qi
if cardinality of Pi is 1 then do nothing, continue with the next output
% supervision
Set b = 1
if the condition b − Lµ0 > 0 is true then compute the supervisor DCi which implies a new place pCi
Dc = −LDp ;
µc0 = b − Lµ0 ;
Given Pi , Tj and Tk :
add f lags turn ON in the new place pCi
add condition f lags is OFF to fire transition tk
add condition f lags is ON to fire transition tk
Figure 4.4: Algorithm to implement mutual exclusion on places actuating the same output. The
input and output of this algorithm are both IOPT nets. The resulting IOPT net has outputs
actuated by single places added as supervisors.
is named here as a limited resource. We start giving an example built with the IOPT Tools.
In the IOPT Tools, limited accessing and writing of a variable or resource can be done by
editing the Bound section in the Place properties. It is important to be aware of the simultaneous
processes in the system needing supervision and specify this in the model limiting the number
of resources in each process. This is done editing the IOPT Petri net place’s Bound in the DES
design environment IOPT Tools.
The algorithm identifies reading processes or writing processes of the net. The input and out-
put of this algorithm are both IOPT nets. The resulting IOPT net has a place invariant added as a
supervisor DC computed using (2.6), (2.7), (2.8). The supervisor restricts the number of places
accessing simultaneously the output signals Reading or Writing and only allow the processes
accessing or writing are under the limit specified. The ’Supervisor_Limited_Resource.m’ Mat-
LAB script, see figure 4.5, part of our toolchain supervision tools, is designed to detect this
problem and create a supervisor for the DES model to avoid a simultaneous reading and writing
operations.
% algorithm
find Pi = set of places that use limited resource
if Bound of every place pi in the set Pi == default
Exit Program
% supervision
Set b=1
if b − Lµ0 > 0 is true then compute the supervisor DCi which implies a new place
Dc = −LDp
µc0 = b − Lµ0
Figure 4.5: Algorithm to implement limited user of resources. The input and output are both
IOPT nets. The resulting Petri net has places actuated by single places computed as supervisors.
In the model illustrated in Figure 4.6, there are two readers and one writer. The initial
marking of the place p1 is 2 therefore, this place’s bound was set to 2 and place p2 ’s bound to 2
as well, which means that the limit to the number of simultaneous reading processes specified
in the model is 2. The remaining places p3 and p4 bound were set to 1, purposely configured in
the DES design environment to be different from other writers processes that share a resource.
4.3 Handling Output Conflicts 39
Figure 4.6: IOPT Petri net model without and with supervision for limited resources of simul-
taneous processes, respectively (a) and (b).
The determined the linear constraint based in place invariants obtained and the resulting
matrices are the following:
h i
L= 0 1 0 1 (4.1)
40 PLC Control of Discrete Event Systems
−1 1 0 0
2
1 −1 0 0
0
Dc = 0 0 −1 1 µ0 = (4.2)
1
0 0 1 −1
0
−1 1 −2 2
where transitions tj ∈ Tj turn off that output signal, transitions tk ∈ Tk turn on that output signal,
places pi ∈ Pi are the places initially activating shared output. In the end we update the control
4.3 Handling Output Conflicts 41
Figure 4.7: Algorithm to handle shared outputs. The input and output are both IOPT nets. The
resulting Petri net has shared outputs actuated by single places computed as supervisors.
(a) Shared Output Conflict in IOPT Tools (b) Shared Output Conflict Solved
Figure 4.8: Application of the proposed algorithm to solve a conflict in a IOPT net.
action of the added unmeasurable place invariant with the shared output in order to produce the
desired code when using the Structured text generator.
Enforcing the constraint in equation 4.3 to a net with this conflict, it is expected to obtain
the equivalent IOPT Petri net model result represented in Figure 4.8.
In this chapter we covered all the theoretical considerations to design the toolchain. In
the next chapter we apply the proposed toolchain from the initial Petri net design in the IOPT
42 PLC Control of Discrete Event Systems
tools, passing by automatic redesign by handling output conflicts, then compiling within the
PLC development environment - Unity Pro by Schneider, and finally testing with the virtual
environment - Factory IO by the Real Games company.
Chapter 5
In this chapter we validate our PLC programming methodology introduced in the previous chap-
ters. We use virtual environments and DES Control as tools for modeling and controlling man-
ufacturing systems like box transportation, assembly of parts and an alarm studied in the course
of Industrial Processes Automation. Supervisory Control of DES is used to set the correct
behavior of the designed systems.
Our objective is to address a few IOPT Petri net models with synchronization problems or
shared output conflicts due to simultaneous multiple processes characterizing the model. And to
test with the toolchain and its algorithms for handling output conflicts in order to verify failure
or success in solving the problems and achieving the desired behavior of the modeled system
(see next sections).
The virtual environments in Factory IO are based on widely used industrial applications
with several challenge difficulty levels. In this thesis, some of those scenes were chosen for
being the most beneficial to new learners of PLC programming.
Setup In this scenario, the goal is transporting a box from one position to another and stopping
the conveyor belt’s motor when the box arrives to the desired position. The setup encompasses
only one sensor and one actuator. The sensor used is a retroflective sensor accompanied by a
reflector, both placed in opposite margins at the end of a conveyor as shown in the Figure 5.1.
44 Experiments and Results
Control In this scene, the box is already placed in point A and ready to be transported when
the simulation starts running. Analyzing the scene, we consider only two events (transitions)
that make the system evolve namely, the transition t1 that fires when the conveyor belt starts
and the transition t2 that is fired when the conveyor belt stops, both relying on the sensor’s state
alone, the input signal. Thus, our transition set is:
T = {t1 , t2 } (5.1)
We represent the system states relating them to the box position and output signal through
the places p1 idle conveyor, p2 busy conveyor and p3 queue forming the place set:
P = {p1 , p2 , p3 } (5.2)
Transition t1 and transition t2 are conditioned only by the retroflective sensor signal. There-
fore, when the simulation starts, transition t1 is already enabled to fire because the box to be
transported from point A and the sensor is not detecting any box in point B, hence, we insert a
5.1 Program 1, Moving Boxes 45
µ0 = {1, 0, 0} (5.3)
From start to finish, in this scene, only one box is transported and the conveyor belt will
never transport more than one box when active. So we form the set of arcs and weight vector
as:
w = {1, 1, 1, 1} (5.5)
The following tables detail the information on each place and transition of this IOPT.
Using the toolchain functions, it was extracted all the required information from the Petri
Net Mark up Language file. The obtained incidence matrix and initial marking for this Petri net
are:
−1 0 1
D = 1 −1 µ0 = 0 (5.6)
0 1 0
While editing the Petri net in IOPT Tools, we created transitions in the same order we want
to number. The IOPT Petri net to Petri net Conversion program lists the transitions and places
46 Experiments and Results
by order of the ID number in the Transition/Place properties screen. The following code was
generated using the Structured Text generator.
IF Sensor = 1 THEN
Conveyor=1;
END_IF;
IF Sensor = 0 THEN
Conveyor=0;
END_IF;
Using PLC programming notation of e.g. Schneider PLCs, the input and output signals map-
ping is separately configured in Unity Pro’s Data Editor screen as variables stored in memory
positions to be used as a bridge of communication with Factory IO. In Figure 5.2 is shown the
sequence of both IOPT Tools Simulator and the 3D virtual system simulator Factory IO, with
the correspondent guard conditions, input events that trigger signal changes in the simulated en-
vironment. Factory IO was configured in Driver options choosing the Modbus TCP/IP Client,
and it becomes possible to connect through Modbus communication protocol to Schneider’s
software Unity Pro thanks to the PLC Simulator Panel tool.
Running Unity Pro with the previous Structured Text program, the simulation in Factory IO,
was observed and concluded to perform the desired behavior.
5.2 Program 2, Parallel Conveyors Join 47
Figure 5.2: Simulation combining Factory IO (left column) and IOPT Tools Simulator (right
column). The currently active Petri net step is marked by a red filled circle.
Setup This scenario is more complex than the previous one. It requires that the location
and physics of the sensors, actuators, objects and the rest of the environment are well studied
thoroughly in order to guarantee the correct behavior of the pick and place simulation.
Table 5.3 lists the set of sensors and actuators used in the simulation.
1
This version was used in the first three experiments of this thesis. It does not fullfill the specification of a state
machine like the version described in 4 does
5.3 Program 3, Cascading Conveyors 49
IOPT Tools Model Similar to the Assembler scene, here we also include in the IOPT Petri net
modelling, two transitions as uncontrollable transitions since they model occurrences of unob-
servable and uncontrollable events in the simulator, corresponding to the Job Arrival, provoked
by the Part Emitter and the Job Delivery, when a box reaches the end of the assembly line and
is cleared from the buffer, making room for more parts incoming. Consequently, the simula-
50 Experiments and Results
tion starts with forcing Entry conveyor belt output ON only turning off when Sensor A detects
the box. Our primary goal was to keep transporting boxes as they arrive to point entry which
means it is necessary that Entry conveyor belt remains turned ON. However, there is a possi-
ble conflicting outcome due to the nature of the event of parts arriving to the Entry conveyor
that do not consider the limited capacity of the buffer conveyors and boxes will uncontrollably
accumulate. Thus, our next objective was to control the number of the transporting the boxes
in the conveyors and their movement considering both uncontrollable events: Job Arrivals and
5.3 Program 3, Cascading Conveyors 51
Job Deliveries.
We first started observing the actuators and sensor’s mechanics to develop an idea of the
desired behavior of the system represented in Figure 5.5. The square area limited by a dot line
is the Part Emitter, it can be configured internally to define the minimum and maximum amount
of time that boxes will take to spawn in the point A of the assembly line. This experience was
performed with Max Time: 2 and Min Time: 1, which represent time units of the simulator that
depend on the simulated PLC scan time settings that are also configurable in Unity Pro’s PLC
Simulator Panel setting minimum scan sleep time to 25. The scan cycle of a PLC involves the
interval for reading the status of inputs, interpret the program implemented and update output
status. In this case, both settings were left in default as it didn’t have an effect on the operation
of the simulation as the experiment showed.
The first iteration of the Petri net edited in IOPT Tools to model this system is illustrated in
the table 5.6.
Our place and transition sets are composed respectively by:
P = {p1 , p2 , p3 , p4 } (5.7)
52 Experiments and Results
T = {t1 , t2 , t3 , t4 , t5 } (5.8)
−1 1 0 0 0
1 −1 0 0 0
D= µ0 = (5.9)
0 1 −1 1
0
0 −1 0 1 0
Conversion IOPT net to ST Using the Structured Text generator, it was produced the fol-
lowing program code:
IF SensorB = 1 THEN
54 Experiments and Results
Conveyor:=1;
END_IF;
IF FE(SensorB)=TRUE THEN
Conveyor:=0;
END_IF;
IF SensorA = 0 THEN
Entryconveyor:=0;
END_IF;
The observed behavior in the simulation shows that the Entry conveyor will stay ON trans-
porting new boxes despite boxes stop being delivered at the end of the assembly line.
Applying our developed algorithm described in section 4.3.2 , the ’Supervisor_MutualExclusion.m’
identifies as linear constraints:
" #
0 1 1 0
L= (5.10)
1 0 0 1
−1 0 1 0 0 0
1 −1 0 0 0
0
0 1 0 −1 0 0
Dc = µ0 = (5.11)
0 0 −1 0 1
0
−1 0 0 1 0
1
1 0 1 0 −1 1
Our program created two different critical sections needing mutual exclusion based on the
following linear constraints:
µ1 + µ4 6 1 (5.12)
µ2 + µ3 6 1 (5.13)
5.3 Program 3, Cascading Conveyors 55
Figure 5.7: IOPT Petri net with supervisors applying mutual exclusion to each output
The first, 5.12 is related to the mutual exclusion of the output Entry Conveyor, and the
second 5.13 is related to the mutual exclusion of the output Conveyor.
Added place invariants p5 and p6 associating them to flag variables that prevent different
output bits being produced simultaneously. The flag variables are not linked to Factory IO Out-
puts but act as external agents to control the usage of the conveyor belts. A new PLC program
was implemented using the PLC controller simulator and Factory IO and we obtained the result
of the experience drawn in the sequence describing the situations: (a) when the box reaches
Sensor B and the assembly line stops, (b) a box is removed from the last buffer, (c) the assem-
bly line restarts until a new box reaches the delivery point.
Conveyor:=1;
END_IF;
IF FE(SensorB)=TRUE THEN
Conveyor:=0;
END_IF;
IF SensorA = 1 THEN
Entryconveyor:=0;
END_IF;\\
IF flag1=1 THEN
flag1:=0;
END_IF;
IF flag2=0 THEN
flag2:=1;
Entryconveyor:=1;
END_IF;
In the new simulation, the Entry conveyor belt is still conditioned by transition T3 enabling
it to stop when a box is detected at the end of this conveyor (Sensor B) but now it is also
controlled by the ’flag2’ allowing it to only activate once it has cleared room from the Conveyor
buffer. The removal of the box is done using the grab mechanism in the virtual simulator. Since
transition T5 is uncontrollable, the variable ’flag1’ allows the Conveyor to turn ON when he
finishes transporting, but this conveyor only activates when value of ’flag2’ is 1, warning the
system that the entry conveyor is bringing a new box. The supervisor that we applied created
a control structure that allows the conveyors in this scene to work in stand-by the arrival of
resources and safely limiting the buffer’s capacity. It prevented the conflict illustrated in Figure
5.6 by considering the outputs of the conveyors mutually exclusive.
5.4 Alarm System, Output Conflicts Handling 57
(c) Light indicators (d) Detail of the buzzer (e) Detail of push buttons
Figure 5.9: Alarm system, mockup system (a) vs simulated setup (b). Details of inputs and
outputs (c,d,e).
The hardware setup, shown on Figures 5.9 (a), is based on a PLC formed by with four
distinct modules namely the main module Modicon TSX-57-2634 which stores and runs the
program, the power supply module Modicon TSX-PSY-2600, the discrete input module DEY-
16D2 with 16 input pins and discrete output module TSX-DSY-16T2 with 16 output pins. The
PLC is connected to a power supply and a terminal board that is used to simulate the inputs
58 Experiments and Results
and outputs of the alarm and includes a keyboard (the keyboard is considered only in the next
experience). To model this system, we created an IOPT Petri net, shown on Figure 5.10, based
on the work of Meleiro [16] and adding IO signals information according to the definitions in
section 2.4. Tables 5.10 and 5.11 describe the IOPT Petri net places and transitions and its
general behavior.
Figure 5.10: Petri net edited with IOPT Tools [11] to control the alarm
The IOPT Petri net created to model the processes of the alarm can be divided in two distinct
parts representing the modes of operation named "Presence Mode" and "Active Mode". The
initial state of the system represents the alarm turned off.
The mode decides the state evolution progression of the alarm. In "Presence Mode", when
an intruder is detected, a red led turns on and also after 5 seconds, a buzzer sound is emitted for
1 second. Both are turned off if the intruder leaves and the alarm returns to "Presence Mode".
If the alarm is set in "Active Mode", the system stays in a pre-active mode state during 30
seconds before the alarm is armed. In this mode, when an intruder is detected, a red led is turned
5.4 Alarm System, Output Conflicts Handling 59
on for 5 seconds and after that a buzzer sound is intermittently emitted with 1 second ON and
2 seconds OFF. When the alarm is armed in "Active Mode", a blue led turns on to display an
option that allows the user to disarm the alarm by pressing the Cardinal key. If the Cardinal key
is pressed or the intruder leaves, the alarm returns to "Active Mode".
The IOPT Petri net model of the alarm was analyzed using our toolchain and none of the
output conflict types was identified among the model’s outputs. Therefore, the model was
transported to the virtual scenario without using supervisory control based in DES and the
Structured Text was generated promptly.
Virtual Scenario Following the original setup model, the simulating scenario is designed for
a total of 5 inputs (four push buttons and one sensor) and 5 outputs (four light LEDs and a
buzzer sound) detailed in 5.4.
The event responsible for sounding the alarm is the detection of a box by a sensor barrier.
The box can be placed using a part emitter. A simpler alternative is for the user to simply force
the input signal Presence Detection to the bit value 1 and consequently provoke a presence
detection by the alarm.
Transition Description
T3, T14, T16, T17, T18, T24-T28 Pushed button Alarm Off
T2 Pushed button Presence Detector
T8 Pushed button Active
T4, T15 Sensor detected the presence off a box
T1, T7, T19, T20 - T23 Sensor did not detect the presence off a box
T5, T6, T10-T13 Timed transition
T9 Cardinal button pressed
T29 Cardinal button released
Table 5.10: Description of the Alarm’s IOPT Petri net transitions
Conversion IOPT to ST For each timed transition of the IOPT Petri net, the ST converter
creates two variables to be used in TON function blocks in order to invoke or produce multiple
bits with Timers in Unity Pro. This is because the Timer TON function block in Structured Text
can only be connected to two variables (input and output) while a IOPT Petri net place/transition
can be associated to multiple signals.
Therefore, the ST generator program needs to create two necessary auxiliary flag variables
for each timed transition of the IOPT Petri net. The first flag variable (timer_flag_n_1) is in
charge of activating the TON timer when the timed transition is enabled and the second flag
60 Experiments and Results
Place Description
P1 Alarm off. No outputs.
P2 Presence detector mode on (Yellow light on).
P3 Alarm in pre-Active mode (Green led on)
Presence detector mode on (Yellow light on).
P4
Presence detected (Red light on)
Alarm mode on. Alarm in Active mode (Green light on)
P5
Column 3 activated (Blue light)
P6 Presence detector mode on (Yellow light). Buzzer on.
Alarm mode on (Green light) Column 3 activated (Blue light on)
P7
Presence detected (Red light).
P8 Presence detector mode on (Yellow led)
Alarm mode on (Green light) Column 3 activated (Blue light),
P9
Presence detected (Red light) Buzzer on
Alarm mode on, Active Mode on (Green light)
P10
Column 3 activated (Blue light)
P11 Alarm mode on, Alarm in Active mode (Green light)
Table 5.11: Description of the Alarm’s IOPT Petri net places
variable (timer_flag_n_2) produces the output signal bits characterizing the given place which
receives new token after the duration of the timed transition. These variables are also connected
to the virtual scene’s timing displays in Factory IO for monitoring the time left of the TON
timer to the corresponding timed transition. This means turning off the alarm will not reset
these displays as they are not part of the solution implemented with the toolchain and have no
influence on the behavior modeled system. The displays are useful to check if the system is
working as intended.
Running the system The Petri net is initialized pressing RUN Mode in Factory IO setting
"%MW101"=1 (represented by "Alarm in Mode Off"=0 and a token on place P1). Next, we
illustrate two possible progressions of the alarm system’s state evolution. In the following
picture 5.11, we see the alarm responds accordingly, envolving to the presence mode state
("%MW102"=1 and the place P2 when the user presses "Presence Mode".
Otherwise, if the user presses "Active Mode" the alarm evolves to the active mode state
(%MW103 and place P3) 30 seconds after staying in "pre-Active Mode" (%MW106 and place
p6 ) by firing the timed transition T13 that produces the output signal bits of the corresponding
place. This is depicted in Figure 5.11.
The setup proposed here has slight differences regarding the user interactions with the sys-
5.5 Alarm Keypad, Holding ON Outputs 61
Figure 5.11: API Alarm Setup Factory IO in Presence Mode or Active Mode
tem’s inputs due to limitations found in editing a virtual environment similar to the one available
in the course API. Therefore, it was arranged a practical mechanism to emulate the opening/-
closing of the store door of the hardware setup which is placing a box intentionally to be de-
tected by the Presemce Detector sensor. Another difference is using pressing buttons to choose
the alarm mode instead of a switch to choose between the three modes (OFF, Active mode and
Presence mode.
Figure 5.12: Physical interface (a) vs Simulated setup (b) for the Alarm and Keypad System
associated to the output signals ("Column 1","Column 2" and "Column 3"), related to power-
ing a keypad column, and associated to the output signal "Buzzer Sound". The output signal
"Buzzer Sound" is shared by the alarm and keypad.
The net can be seen in three similar blocks, each corresponding to one keypad column being
powered. In each block there is a hold state representing the system waiting for a button to
be pressed which lasts fifty milliseconds. If a button of the first column is pressed, the system
evolves to another hold state representing the system waiting for the same button to be released.
If a button of the first column is not pressed, the system evolves to a different state powering
the second column and stays in that hold state for fifty milliseconds waiting for a button of the
5.5 Alarm Keypad, Holding ON Outputs 63
Transition Description
T30 - T33 Pressing buttons of keypad column 1
T34 - T37 Releasing buttons of keypad column 1
T38 - T41 Pressing buttons of keypad column 2
T42 - T45 Releasing buttons of keypad column 2
T46 - T49 Pressing buttons of keypad column 3
T50 - T53 Releasing buttons of keypad column 3
T54, T55, T56 Powering keypad column 1, 2, 3
Table 5.12: Description of Keypad’s IOPT Petri net transitions
Place Description
P13 - P16 Power Column 1 and Buzzer Sound on
P18 - P21 Power Column 2 and Buzzer Sound on
P23 - P26 Power Column 3 and Buzzer Sound on
P12, P17, P22 Power Column 1, 2 or 3
Table 5.13: Description of the Keypad’s IOPT Petri net places
second column to be pressed. If a button of the second column is not pressed, the same process
is repeated powering instead the third column.
The timed transitions T54, T55 and T56 in the IOPT Petri net are responsible for making the
system transition between the hold states waiting for a button to be pressed. The activation of
different columns is represented by the marking of the places P12, P17 ad P22. The remaining
places represent the hold states of the system waiting for a button to be pressed/released. Tables
5.12 and 5.13 presents the description of the keypad places and transitions.
Buzzer is a Shared Output After setting up a simulation project similar to the projects of the
Industrial Automation course using Factory IO and in order to validate the complete toolchain,
in this experiment, we study one crucial characteristic of the desired behavior for this simula-
tion. Which is not interrupting the intermittent sound signal triggered by a presence detection
when keypad keys are pressed/released. We observed that the system behavior in the virtual
scene does not meet this specification. This is due to the output signal "Buzzer Sound" being a
shared output by the alarm system and the keypad.
This situation is an output conflict as described in subsection 4.3.4. It occurs when the
alarm and the keypad states simultaneously evolve setting the output signal "Buzzer Sound" to
opposite values. In the simulation, this conflict is originated when the alarm detects an intruder
and turns on the buzzer while the keypad is being used. And the result is the buzzer being turned
off unexpectedly during the intermittent sound signal (in Active Mode) when keypad buttons
64 Experiments and Results
are pressed and released. Because releasing the keypad button sets the output signal "Buzzer
Sound" value to 0 interrupting the periodic interval and consequently restarts the intermittent
sound signal.
The places P9 and P10 and the timed transition T10 and transition T11 are responsible for
the system’s states that describe the intermittent sound signal in the simulation. The desired
outcome is that if a keypad button is pressed and then released, the intermittent sound signal
is not interrupted. This means that the output signal "Buzzer Sound" should stay on and not
change even if the timed transitions T10 and T11 keep firing and the Petri net’s current marking
evolves between places P9 ("Buzzer Sound" on) and P10 ("Buzzer Sound" off).
To help the modeled system achieve the correct behavior in the virtual scene, we apply the
last step of our toolchain to consider and handle this output conflict concerning the output signal
"Buzzer Sound".
Shared Output Supervisor The output conflict described above should be resolved using
the Supervisory Control based on DES program of our toolchain that implements the solution
described in 4.3.4. The program uses the function Supervisor_SharedOutput.m developed in
MatLAB. The objective is to remove the system’s possibility of setting the "Buzzer Sound"
output signal bit to 0 during any processes that use this output signal.
The variable %MW127 of the program generated in Structured Text using our toolchain
(see Appendix D) is related to the place added by applying the supervisor. By inspection of
this variable in the PLC programming environment Unity Pro while Factory IO runs the virtual
simulation of the program, it is seen the variable holds an integer. This integer is equal to the
number of tokens in the place P27 and represents the marking resulting from the firing the timed
transition T11 ("Buzzer Sound" on) and the transition T30 ("Keyboard row1" on) consecutively.
This corresponds to the situation when the alarm’s system is producing an intermittent sound
signal turning on the "Buzzer Sound" and the user is pressing the keypad button "1". The net
marking in this state is given by
h i0
µ= ... 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2 (5.14)
The places P9, P13, P27 hold marking that allow the timed transition T10 and the transition
T34 to fire. Upon releasing the keypad button, transition T34 becomes enabled and is fired.
Resulting in consuming a mark in place P27 and correctly leaving Buzzer Sound still ON.
5.5 Alarm Keypad, Holding ON Outputs 65
Figure 5.14: Shared Output Supervisor applied to Alarm and Keypad System
66 Experiments and Results
Chapter 6
In this thesis, DES theory has been used, mostly in the veins of Petri net classes with extensions,
for PLC programming. Testing of the PLC programs has been based on virtual environments
created by the so-called applied games.
The experiments conducted allowed us to test our toolchain in different aspects. The output
conflicts detection step of the toolchain is helpful to dismiss common mistakes in PLC pro-
gramming and to make it more intuitive. The quick generation of PLC code from a DES can
be a powerful tool in modelling manufacturing processes. Using a virtual simulator has shown
to be a decent alternative to the classrooms education and also efficient to see the toolchain’s
results.
The validation of representing Discrete Event Systems (DES), with a more detailed Petri
net definition, using I/O signals, to model industrial processes and applying DES tools for
Supervisory Control has revealed itself to be practical and helpful.
The translation from DES to PLC programming code, namely Structured text, was proven
to be effective to implement our algorithms for Supervisory Control in Petri nets and effective
to model small to larger Petri net models. But it was left untested for very large size nets. This
translation also meant renouncing Petri net properties and tools.
The modalities proposed for handling output conflicts already cover a wide range of situa-
tions. It is however an aspect that real world practice may imply augmenting to handle novel
objectives and eventually doing more research.
Despite the size of the Petri nets have not been a limitation in this thesis, i.e. the time and
memory complexity were not an issue for the personal computer simulating and creating the
PLC code, and programs and data fit well into the PLC memory, large Petri nets (hundreds
of places and transitions) may be a concern firstly for the available PLC memory. Interesting
68 Conclusions and Future Work
future work will be researching methodologies for minimizing the PLC code and memory usage
resulting from the automatic conversion of IOPT Petri nets.
Appendix A
In this appendix, we list the software developed in MatLAB to create PLC programs in Struc-
tured Text language from a Petri net subclass. This software calls a function to handle Output
Conflicts proposing to the user three different solutions described in 4.3 and then procceeds to
generate the PLC code considering the user’s options.
source_places=sprintf(’ %%MW%d’,100+transition_list(i).previous_places_index(j));
if j==length(transition_list(i).previous_places_index)
arc_strings=string(sprintf(’%s >= %d’,source_places,arc_weight(transition_list(i).
,→ previous_places_index(j))));
consume_marking=string(sprintf(’%s:=%s − %d;’,source_places,source_places,arc_weight(
,→ transition_list(i).previous_places_index(j))));
consume_marking_string=[consume_marking_string consume_marking];
consume_marking_strings(i,j)= consume_marking;
fireable_trans_string=strcat(fireable_trans_string,arc_strings);
break
else
arc_strings=string(sprintf(’ %s >= %d’,source_places,arc_weight(transition_list(i).
,→ previous_places_index(j))));
consume_marking=string(sprintf(’%s:=%s − %d;’,source_places,source_places,arc_weight(
,→ transition_list(i).previous_places_index(j))));
consume_marking_strings(i,j)= consume_marking;
arc_strings=strcat(arc_strings,’ AND ’);
fireable_trans_string=strcat(fireable_trans_string,arc_strings);
end
end
for j=1:length(transition_list(i).related_places_index)
target_places=sprintf(’%%MW%d’,100+transition_list(i).related_places_index(j));
if j==length(transition_list(i).related_places_index)
produce_marking=string(sprintf(’%s:=%s + %d;’,target_places,target_places,arc_weight_2(
,→ transition_list(i).related_places_index(j))));
produce_marking_string=[produce_marking_string produce_marking];
produce_marking_strings(i,j)=produce_marking;
break
else
produce_marking=string(sprintf(’%s:=%s + %d;’,target_places,target_places,arc_weight_2(
,→ transition_list(i).related_places_index(j))));
produce_marking_string=[produce_marking_string produce_marking];
produce_marking_strings(i,j)=produce_marking;
end
end
% fireable transition string
assignin(’base’,’fireable_trans_strings’,fireable_trans_strings);
fireable_trans_strings=[fireable_trans_strings fireable_trans_string];
assignin(’base’,’consume_marking_strings’,consume_marking_strings);
assignin(’base’,’produce_marking_strings’,produce_marking_strings);
q=zeros(size(transition_vector));
arc_strings=[];
71
fireable_trans_string=[];
end
filename=strrep(ifname, ’.mat’, ’.txt’);
%Initializations
input_event=0;
input_event_signal=0;
input_event_trigger=0;
output_event=0;
output_event_signal=0;
output_event_trigger=0;
j=0;
%miu_0=initialMarking;
if isempty(input_vector)==0
input_vector_signal=input_vector.signal;
input_vector_signal=string(input_vector_signal);
end
if isempty(output_vector)==0
output_vector_signal=output_vector.signal;
output_vector_signal=string(output_vector_signal);
end
% filename=strtok(filename,’.’); %To remove extension .mat
% filename=strcat(filename,’.txt’) %To add extension .txt
fid = fopen(filename,’w’);
% Shared Output
if choice==2
fprintf(fid,’\n IF %%MW%d>=1 THEN %s:=1; ELSE %s:=0; END_IF;\n’,100+length(place_list),
,→ shared_output,shared_output);
end
output_event=transition_list(i).output_event;
output_event=string(output_event);
for j=1:length(output_event_vector)
if output_event==output_event_vector(j).event
output_event_trigger=output_event_vector(j).type;
output_event_signal=output_event_vector(j).signal;
end
end
output_event_signal=string(output_event_signal);
end
guard_condition=transition_list(i).guard_condition;
guard_condition=string(guard_condition);
if str2double(timed_transition)==0
% transition with no input event
if str2double(input_event)==0
fprintf(fid,’\nIF %s AND %s THEN’,fireable_trans_strings(i), guard_condition);
else
% transition with input event rising edge
if strcmp(’up’, input_event_trigger)
% transition with no guard condition
if str2double(guard_condition)==0
fprintf(fid,’\nIF %s AND RE(%s)=TRUE THEN’,fireable_trans_strings(i),
,→ input_event_signal);
else
fprintf(fid,’\nIF %s AND RE(%s)=TRUE AND %s THEN’,fireable_trans_strings(i),
,→ input_event_signal, guard_condition);
end
end
if strcmp(’down’, input_event_trigger)
if str2double(guard_condition)==0
fprintf(fid,’\nIF %s AND FE(%s)=TRUE THEN’,fireable_trans_strings(i),
,→ input_event_signal);
else
fprintf(fid,’\nIF %s AND FE(%s)=TRUE AND %s THEN’,fireable_trans_strings(i),
,→ input_event_signal, guard_condition);
end
end
end
if strcmp(’up’,output_event_trigger)
fprintf(fid,’\n %s:=1;’,output_event_signal);
end
74 Structured Text Construction
if strcmp(’down’,output_event_trigger)
fprintf(fid,’\n %s:=0;’,output_event_signal);
end
for m=1:length(transition_list(i).previous_places_index)
fprintf(fid,’\n %s’,consume_marking_strings(i,m));
end
previous_places_vector=unique(previous_places_vector,’first’); %to remove repetitive strings
for w=1:length(previous_places_vector)
if w == find(contains(previous_places_vector,shared_output))
else
previous_places_vector(w)=strcat(extractBefore(previous_places_vector(w),’=’),’:=’,’0;’);
fprintf(fid,’ %s ’,previous_places_vector(w));
end
end
for m=1:length(transition_list(i).related_places_index)
fprintf(fid,’\n %s’,produce_marking_strings(i,m));
end
related_places_vector=unique(related_places_vector,’first’); %to remove repetitive strings
for k=1:length(related_places_vector)
comprimento=k;
related_places_vector(k)=insertBefore(related_places_vector(k),’=’,’:’);
fprintf(fid,’ %s;’,related_places_vector(k));
end
fprintf(fid, ’\nEND_IF;\n’);
end
% Timed Transitions
if str2double (timed_transition)~=0
previous_places_vector=unique(previous_places_vector,’first’); %to remove repetitive strings
fprintf(fid, ’\n’);
fprintf(fid, ’IF %s ’,fireable_trans_strings(i)); % input_vector_signal
fprintf(fid, ’THEN\n’);
fprintf(fid, ’ timer_flag_%d_1:=1;\n’,i);
fprintf(fid, ’END_IF;\n’);
fprintf(fid,’MY_TON_%d(IN := timer_flag_%d_1,\n’,i,i);
fprintf(fid,’ PT:= t#%ss,\n’,time);
fprintf(fid,’ Q => timer_flag_%d_2,\n’,i);
fprintf(fid,’ ET => Timer%d);\n’,i);
fprintf(fid, ’IF timer_flag_%d_2=1 AND %s’,i,fireable_trans_strings(i));
fprintf(fid, ’ THEN\n’);
for m=1:length(transition_list(i).previous_places_index)
fprintf(fid,’%s\n’,consume_marking_strings(i,m));
75
end
previous_places_vector=unique(previous_places_vector,’first’); %to remove repetitive strings
for w=1:length(previous_places_vector)
if w == find(contains(previous_places_vector,shared_output))
else
previous_places_vector(w)=strcat(extractBefore(previous_places_vector(w),’=’),’:=’,’0;’);
fprintf(fid,’ %s ’,previous_places_vector(w));
end
end
fprintf(fid,’\n’);
for m=1:length(transition_list(i).related_places_index)
fprintf(fid,’ %s\n’,produce_marking_strings(i,m));
end
fprintf(fid, ’ %s; ’,strcat(extractBefore(related_places_vector,’=’),’:=’,extractAfter(
,→ related_places_vector,’=’)));
fprintf(fid, ’ timer_flag_%d_1:=0;\n’,i);
fprintf(fid, ’END_IF;\n’);
end
end
disp(’Structured Text generated’)
fid = fclose(fid);
76 Structured Text Construction
Appendix B
This is a step-by-step tutorial on how to use Schneider Unity Pro to control Factory IO through
a Modbus TCP/IP connection starting from IOPT Tools accompanied by the developed Matlab
programs.
78 Unity Pro Factory IO connection through Modbus TCP/IP
Switch the PLC to Run mode by clicking on PLC > Run. And then click Ok
81
12. Press F4 to open Driver Window and select Modbus TCP/IP Client.
IOPT Tools framework [11] offers a toolkit in a Web interface with a simulator to test system
behavior, a state-space analyzer for the verification of properties, automatic generation of soft-
ware in the languages C, VHDL and JavaScript for deployment into physical embedded devices
and testing of industrial automation applications. Its users have access to support tools for error
correction in every development stage allowing the implementation of real controllers without
the requirement of writing code and providing faster development times. The code generated
comes in a compressed ZIP archive along side with compilation directions.
An electric bucket cart goes around in a circular trajectory collecting cement, sand and
gravel from deposits equipped with sensors at unloading positions and ends with dumping the
materials into a mixer, which also is connected to a water supply. The water goes through a
water pipe regulated by sensors and the cart has weight sensors to measure the desired amounts
of material. Below, there are the lists of sensors and actuator signals connected to the inputs
and outputs of the controller to be modeled.
Places are drawn as yellow circles, transitions as cyan rectangles, input signals as cyan
arrow-head shaped rectangles, output signals as green arrow-head shaped rectangles, the input
events as cyan triangles and output events as green triangles. The arcs are the arrow lines be-
tween the places and transitions. Although it is possible to create multiple signal arithmetic or a
mathematical expression as guard conditions, in this example, every transition but one contains
a different guard condition depending respectively on a single input signal. And although places
can produce combining output actions, in this example, every place but one has a single output
action trigger resulting in the change of the respective output signal.
84 IOPT Petri net Model Example
Sensors(Input) Description
StartBtn Start button - Start Operation
CementArrive Cart arrived at cement position
CementLevel Cement load finished
SandArrive Cart arrived at sand position
SandLevel Sand load finished
GavelArrive Cart arrived at sand position
GavelLevel Gravel load finished
MixerArrive Cart arrived at mixer position
BucketEmpty Bucket unload finished
WaterLevel Water level reached
Table C.1: Sensors for the IOPT Tools Concrete Mixer Petri net
(a) Concrete Mixer Representation (b) IOPT Tools Concrete Mixer Petri net
Figure C.1: Concrete Mixer Representation(a) and IOPT Tools Concrete Mixer Petri net (b)
Appendix D
The PLC code listed in this appendix was generated implementing our toolchain. After mod-
elling the system with IOPT Tools and running the Structured Text generator, the user is warned
if his implementation of DES can lead to output conflicts and is given the possibility of choos-
ing one of the solutions described in chapter 4. To handle the situation described in section 5.5,
if the users decides to consider Buzzer output signal conflict, the following program will be
obtained:
%M15:=Column1;
%M16:=Column2;
%M17:=Column3;
ET => Timer12);
IF timer_flag_12_2=1 AND %MW105 >= 1 THEN
%MW105:= %MW105 − 1;
Alarm_in_Pre_Active_Mode:=0; Column3_Activated:=0; Presence_Detected:=0;
%MW127:=%MW127 + 1;
%MW109:=%MW109 + 1;
Buzzer_Sound:=1; Alarm_in_Pre_Active_Mode:=1; Presence_Detected:=1; Column3_Activated:=1;
,→ Buzzer_Sound:=1; timer_flag_12_1:=0;
END_IF;
%MW112:=%MW112 + 1; Column1:=1;
END_IF;
%MW117:=%MW117 + 1; Column2:=1;
END_IF;
%MW122:=%MW122 + 1; Column3:=1;
END_IF;
[1] Tilak Agerwala. Special feature: Putting petri nets to work. Computer, 12(12):85–94,
1979.
[2] P Alanche, K Benzakour, F Dolle, P Gillet, Paul Rodrigues, and Robert Valette. Psi: A
petri net based simulator for flexible manufacturing systems. In Advances in Petri Nets
1984, pages 1–14. Springer, 1985.
[3] Pierre Azema, Robert Valette, and Michel Diaz. Petri nets as a common tool for design
verification and hardware simulation. In DAC, volume 76, pages 109–116, 1976.
[4] Christos G Cassandras and Stephane Lafortune. Introduction to discrete event systems.
Springer Science & Business Media, 2009.
[5] René David and Hassane Alla. Petri nets for modeling of dynamic systems: A survey.
Automatica, 30(2):175–202, 1994.
[7] Georg Frey and Mark Minas. Editing, visualizing, and implementing signal interpreted
petri nets. In Proceedings of the AWPN 2000, pages 57–62. Citeseer, 2000.
[9] Luís Gomes, João Paulo Barros, Anikó Costa, and Ricardo Nunes. The input-output place-
transition petri net class and associated tools. In 2007 5th IEEE International Conference
on Industrial Informatics, volume 1, pages 509–514. IEEE, 2007.
98 BIBLIOGRAPHY
[10] Luís Gomes, Filipe Moutinho, and Fernando Pereira. Iopt-tools—a web based tool frame-
work for embedded systems controller development using petri nets. In 2013 23rd Inter-
national Conference on Field programmable Logic and Applications, pages 1–1. IEEE,
2013.
[12] Marian Iordache and Panos J Antsaklis. Supervisory control of concurrent systems: a Petri
net structural approach. Springer Science & Business Media, 2007.
[13] Rainer Konig and Lothar Quack. Petri-Netze in der Steuerungstechnik. Technik, 1988.
[14] A Lüder. A signal extension for petri nets and its use in controller design.
[15] ME Meda, A Ramirez, and A Malo. Identification in discrete event systems. In SMC’98
Conference Proceedings. 1998 IEEE International Conference on Systems, Man, and Cy-
bernetics (Cat. No. 98CH36218), volume 1, pages 740–745. IEEE, 1998.
[16] José Francisco Meleiro. Agile synthesis and identification of industrial processes, 2017.
[18] Rui Pais, SP Barros, and Luís Gomes. A tool for tailored code generation from petri net
models. In 2005 IEEE Conference on Emerging Technologies and Factory Automation,
volume 1, pages 8–pp. IEEE, 2005.
[19] Fernando Pereira and Luís Gomes. Automatic synthesis of vhdl hardware components
from iopt petri net models. In IECON 2013-39th Annual Conference of the IEEE Industrial
Electronics Society, pages 2214–2219. IEEE, 2013.
[20] Fernando Pereira, Filipe Moutinho, and Luís Gomes. Model-checking framework for em-
bedded systems controllers development using iopt petri nets. In 2012 IEEE International
Symposium on Industrial Electronics, pages 1399–1404. IEEE, 2012.
[21] Fernando Pereira, Filipe Moutinho, and Luís Gomes. Iopt-tools—towards cloud design
automation of digital controllers with petri nets. In 2014 International Conference on
Mechatronics and Control (ICMC), pages 2414–2419. IEEE, 2014.
BIBLIOGRAPHY 99
[22] James L Peterson. Petri net theory and the modeling of systems. Prentice Hall PTR, 1981.
[23] Carl Petri. Communication With Automata. PhD thesis, Darmstadt University of Technol-
ogy, 1962.
[24] Manuel Silva. Las Redes de Petri: en la Automática y la Informática. Editorial Ac, 1985.