Programming Styleguide DOCU v11 en
Programming Styleguide DOCU v11 en
https://support.industry.siemens.com/cs/ww/de/view/81318674
Warranty and Liability
We do not accept any liability for the information contained in this document.
Any claims against us – based on whatever legal reason – resulting from the use of
the examples, information, programs, engineering and performance data etc.,
described in this programming guideline will be excluded. Such an exclusion will
not apply in the case of mandatory liability, e.g. under the German Product Liability
Act (“Produkthaftungsgesetz”), in case of intent, gross negligence, or injury of life,
body or health, guarantee for the quality of a product, fraudulent concealment of a
deficiency or breach of a condition which goes to the root of the contract
Siemens AG 2015 All rights reserved
Security Siemens provides products and solutions with industrial security functions that
informa- support the secure operation of plants, solutions, machines, equipment and/or
tion networks. They are important components in a holistic industrial security
concept. With this in mind, Siemens’ products and solutions undergo continuous
development. Siemens recommends strongly that you regularly check for
product updates.
For the secure operation of Siemens products and solutions, it is necessary to
take suitable preventive action (e.g. cell protection concept) and integrate each
component into a holistic, state-of-the-art industrial security concept. Third-party
products that may be in use should also be considered. For more information
about industrial security, visit http://www.siemens.com/industrialsecurity.
To stay informed about product updates as they occur, sign up for a product-
specific newsletter. For more information, visit
https://support.industry.siemens.com.
Table of Contents
Warranty and Liability ................................................................................................. 2
1 Introduction ........................................................................................................ 4
2 Explanation of Terms ........................................................................................ 6
3 General Specifications ...................................................................................... 8
3.1 Specifications and customer requirement ............................................ 8
3.2 Settings in TIA Portal ............................................................................ 9
3.3 Identifier .............................................................................................. 11
3.3.1 Formatting .......................................................................................... 11
3.3.2 Abbreviations ...................................................................................... 12
4 PLC Programming ........................................................................................... 13
4.1 Program blocks and sources .............................................................. 13
4.1.1 Block name and numbers................................................................... 13
4.1.2 Formatting .......................................................................................... 14
4.1.3 Programming ...................................................................................... 14
4.1.4 Comments .......................................................................................... 15
4.1.5 Formal parameters: Input, Output und InOut ..................................... 16
4.2 Tag declaration ................................................................................... 18
4.2.1 Static and temp .................................................................................. 18
4.2.2 Constants ........................................................................................... 18
4.2.3 Arrays ................................................................................................. 20
Siemens AG 2015 All rights reserved
1 Introduction
When programming SIMATIC controllers, the task of the programmer is to create
as clear and readable a user program as possible. Each user uses its own
strategy, for example, how to name tags or blocks or the way of commenting. The
different philosophies of the programmers create very different user programs that
can only be interpreted by the respective programmer.
Note The programming guidelines described here are a mere suggestion for sticking
to a consistent programming style. It is up to you which rules and
recommendations you consider sensible and which ones you use or not.
Siemens AG 2015 All rights reserved
However, please note that the rules and recommendations described here are
adapted to one another and do not interfere with each other.
The programming guidelines described here help you create a consistent program
code which can be better maintained and reused. That is, errors can be detected
early on (e.g. by means of a compiler) or avoided.
The source code must have the following properties:
consistent continuous style
easily readable and comprehensible
For maintenance and clarity of the source code it is initially necessary to stick to a
certain external format. However, optical effects - for example, a consistent number
of space characters before each comma - contribute only little to the quality of the
software. It is much more important to find rues, for example, that support the
developer in the following way:
Avoiding typing errors and slips which the compiler then interprets wrongly.
Objective: the compiler shall detect as many errors as possible.
Support from the program code for diagnosing program errors, such as reusing
a temp tag beyond one cycle, for example.
Objective: the code points at problems early on.
Consistent standard applications and libraries
Objective: familiarization shall be easy and reusability of program code
increased.
Simple maintenance and simplification of further development
Objective: modification of program code in the individual modules that may
include functions (FCs), function blocks (FBs), data blocks (DBs), organization
blocks (OBs) in libraries or in the project shall have minimal effects on the
overall program/overall library. Modifications of program code in the individual
modules shall be performed by different programmers.
Validity
This document applies for (customer) application examples, such as libraries
created in the IEC 1131-3 (DIN EN 61131-3) programming languages Structured
Text (ST), Ladder Diagram (LAD), Function Block Diagram (FBD) and Statement
List (STL).
2 Explanation of Terms
Rules / recommendations
Specifications are divided into recommendations and rules.
Rules are binding specifications and must be met. They are mandatory for
reusable and performant programming. In exceptional cases, rules may also be
violated. However, this must be documented accordingly.
Recommendations are specifications which, on the one hand, serve for a
consistent code and, on the other hand, are intended as support and information.
Recommendations should principally be followed; however, there may be cases
where the recommendation is not followed. This may be due to efficiency, but also
because the code is more readable otherwise.
Performance
Performance of an automation system specifies the processing time (cycle time) of
a program.
A performance loss refers to the possibility of reducing processing time, hence the
cycle time of a program run by means of applying the programming rules and
skillful programming of the user program.
Identifier / name
Siemens AG 2015 All rights reserved
Abbreviations
The following abbreviations are used within the text:
Table 2-1: Abbreviations for blocks
Abbr. Type
OB Organization block
FB Function block
FC Function
DB Data block
TO Technology object
SFB System function block
SFC System function
3 4
3 General Specifications
Generally, it should be noted that the names used are always unique regarding
functionality and used interface type.
That is, if the same name is used, the functionality behind it should also always be
the same.
The basis for this document is the programming guideline for S7-1200/1500. It
describes the system properties of the S7-1200 and S7-1500 controllers and how
to program them in an ideal way.
takes priority. The rules defined by the customer must be documented in suitable
format in the source text.
3.3 Identifier
3.3.1 Formatting
Recommendation: no separator
Separator (underscore) should not be used in identifiers; the length of the identifier
should be kept short.
Example
temporary tag: tempMaxLength
3.3.2 Abbreviations
Sum
Old Old value (e.g. for edge detection)
4 PLC Programming
4.1 Program blocks and sources
4.1.1 Block name and numbers
Example
Single-instance: InstPidHeater (capital letter own block)
Multi-instance: instTimerMotor (lower case within one instance)
Siemens AG 2015 All rights reserved
4.1.2 Formatting
4.1.3 Programming
programming language LAD or FBD provides the service staff with easier
diagnostics and quicker overview.
4.1.4 Comments
Recommendation: Comments
A block comment must be set in front of the respective code section in one or
several rows.
For frequently changing control or status tags, it may make sense to declare these
directly as elementary Input or Output tags for simple access in LAD / FBD outside
such a PLC data type.
Note For InOut interfaces, setting the optimization at the block and at the
interconnected data must be paid attention to.
Only if the optimization settings match (data optimized and block optimized, or
data not optimized and block not optimized) no local copy of the data is created
by the system.
If the optimization settings differ, from arrays at least one element is always
copied into the stack, from other data types always the complete data. This
makes the performance advantage of InOut interfaces void.
Siemens AG 2015 All rights reserved
4.2.2 Constants
Global user constants can be created as PLC tag in the copy templates of the
library. However, these global constants are not automatically adopted into the
controller as well when using the typed block in the project.
Example
Figure 4-3: Constants in an FB
Example
Figure 4-4: Using constants
Siemens AG 2015 All rights reserved
Note Constants are text replacements for numerical values exchanged by the
preprocessor. Using constants in the CPU neither causes a performance loss,
nor does the memory consumption increase in the data memory.
Only the memory consumption in the load memory of the CPU increases due to
the increasing number of characters in the block sources.
4.2.3 Arrays
Example
Figure 4-5: Example - PLC data type
Note An exception are know-how protected blocks. In this case, the application of PLC
data types should be carefully considered. The reason for this is that in the
background, a number is assigned for each PLC data type. If this PLC data type
is then used in a know-how protected block, this number must stay the same
when copying into another project. If this is not the case, the new project, can
only be compiled with the password for know-how protection.
If a block shall be know-how protected, PLC data types are only used where
type-safe copying processes or interconnections with the respective structured
data type are performed.
4.2.5 Initialization
Example
Figure 4-7: Initialization of temporary data
#tempAcceleration := 0.0;
#tempVelocity := #MAX_VELOCITY;
#tempRampAct := 0.0;
Example
Figure 4-8: Initialization of static data
4.3 Instructions
4.3.1 Operators and expressions
Example
//Okay
#statSetValue := #statSetValue1 + #statSetValue2;
//Not okay
#statSetValue:=#statSetValue1+#statSetValue2;
Example
#tempSetFlag := (#tempPositionAct < #MIN_POS)
Siemens AG 2015 All rights reserved
Example
IF (DriveStatus() = #OK) //Comment
AND
((#statOldDrive XOR #tempActDrive)
OR (#statOldPower XOR #tempActPower)
) //Comment
AND (#start = True)
THEN
; //Statement
ELSE
; //Statement
END_IF;
CASE #tempSelect OF
1: //Comment
; //Statement
4: //Comment
Siemens AG 2015 All rights reserved
; //Statement
2..5: //Comment
; //Statement
ELSE
; //Generate error message
END_CASE;
Example
CASE instruction
//-------------------
CASE #statSelect OF
CMD_INIT: //Comment
; //Statement
CMD_READ: //Comment
; //Statement
CMD_WRITE: //Comment
; //Statement
ELSE
; //Generate error message
END_CASE;
Example
FOR instruction
//---------------
FOR #tempIndex := 0 TO #MAX_NUMBER – 1 DO
; //Statement
END_FOR;
Siemens AG 2015 All rights reserved
Example
FOR instruction with width of the jump
//---------------
FOR #tempIndex := 0 TO #MAX_NUMBER – 1 BY 2 DO
; //Statement
END_FOR;
Example
Conditional termination of a loop with EXIT
//---------------
FOR #tempIndex := 0 TO #MAX_NUMBER – 1 BY 2 DO
IF #tempCondition THEN
EXIT; //EXIT Loop
END_IF;
END_FOR;
Example
Recheck loop condition with CONTINUE
//---------------
FOR #tempIndex := 0 TO #MAX_NUMBER – 1 BY 2 DO
IF #tempCondition THEN
CONTINUE; //loop condition
END_IF;
END_FOR;
Example
WHILE instruction
//---------------
WHILE #tempCondition DO
; //Statement
END_WHILE;
Example
REPEAT instruction
//---------------
REPEAT
; //Statement
UNTIL #tempCondition END_REPEAT;
Input parameters
execute execute without ‘continuousUpdate’:
All parameters are started with a rising edge at the execute input and the
functionality is started. If changes of the parameters become necessary,
the execute input must be retriggered.
enable:
enable All parameters are adopted with a rising edge at the enable input and can
be continuously changed. The function is activated level-controlled (for
TRUE) and deactivated (for FALSE).
Output parameter
Exclusiveness: With execute:
done The outputs done, busy, commandAborted and error are mutually
busy exclusive, that is, only one of the outputs can be set at any given time. If
valid execute is set, one of these outputs must be set.
commandAborted
error With enable:
The outputs valid and error are mutually exclusive.
With enable:
The FB is currently busy processing a command. New output values can
be expected. busy is set with a rising edge of enable and remains set for
The job is started with a rising edge at the execute parameter and the values
pending at the input parameters are adopted.
Subsequently changed parameter values are only adopted at the next job start, if
no continousUpdate is used.
Resetting the execute parameter does not terminate processing the job, however, it
affects the display duration of the job status. If execute is reset before a job has
been completed, the parameters done, error and commandAborted are
respectively only set for one call cycle.
After the job has been completed, a new rising edge is required at execute to start
a new job.
This ensures that for each start of a job, the block is in the initial state and the
function is processed independently of the previous jobs.
Example
Figure 4-9: LAD representation
<FunctionBlockName>
NOTICE If input execute is reset before output done is set, output done must only be set
for one cycle.
Figure 4-10: Signal flow diagram of a function block with execute input
a) done, error and commandAborted are reset with falling edge at execute.
b) The functionality of the FB is not stopped with falling edge at execute.
c) If execute is already FALSE, then done, error and commandAborted are only
pending for one cycle.
d) A new job is requested with a rising edge at execute while the block is still
processed (busy = TRUE). The old job is either terminated with the parameters
pending at the start of the job, or the old job is cancelled and restarted with the
new parameters. The behavior follows the application case and must be
documented accordingly.
e) If processing a job is interrupted by a higher or equal priority job (of another
block/instance), commandAborted is set by the block. It immediately interrupts
the remaining job processing. This job occurs if an emergency stop at an axis
shall be executed, while another block executes a move job at the axis.
Setting the enable parameter starts the job. As long as enable remains set, job
processing is active and new values can be adopted processed continuously.
Resetting the enable parameter terminates the job.
If a new job is started, the block is put to its initial state and can be switched and
configured completely new.
If the programmer uses the enable input, at least the output parameter valid must
be used.
Example
Figure 4-11: LAD representation
<FunctionBlockName>
a) error on TRUE is used to reset valid and stop all functionalities of the FB.
Since it is an error that can be removed by the block itself, busy remains set.
b) After removing the error cause (e.g. restoring communication) valid is set again.
c) An error occurs that can only be removed by the user. Here, error must be set,
busy and valid be reset.
d) The pending error that has to be removed by the user can only be
acknowledged by a falling edge at enable.
e) valid on TRUE means, that the block is activated, no errors are pending, and
hence, the outputs of the FB are valid.
f) If enable is reset to FALSE, valid and busy are also reset.
CommandAborted, error and done are always set for as long as the execute signal
is pending, at least, however, for one cycle.
Note This chapter is no longer part of the PLCopen Function Blocks for Motion Control
V2.0 standard.
The following additional rules and recommendations describe further
requirements for consistent programming of error return and diagnostics in
function blocks.
Status Word
Nibble 3 2 1 0
Classification of status:
16#0 = Execution finished
16#7 = Execution possible or execution in progress
16#8 = Error occurred in execution
Recommodation: Use of output status for state and error codes of instruction
State codes of instructions (system blocks) are looped through unchanged to
output status. Therefore the documentation of the blocks and its error and state
codes can refer to the TIA Portal help.
Example
Figure 4-14: status and statusID by nested blocks
statusID=w
status=16#....
statusID=x
status=16#....
statusID=y
status=16#....
statusID=z
status=16#....
statusID
Siemens AG 2015 All rights reserved
status
statusID=w
status=16#.... statusID=14
status=16#8001
statusID
statusID=x status
status=16#....
Example
statusID=4
status=16#8001 Offset = 10
status=16#8001
statusID + Offset
status
statusID=z
status=16#....
statusID
status
In parameter timestamp, the time at which the error has occurred is stored.
In stateNumber, the current state of the state machine is stored. For a function
block with different operating modes, the operating mode in which the error has
occurred is stored in the modeNumber tag.
If an error of a system function or a called FB / FC was detected, the return code is
stored in the subfunctionStatus element.
The unique error code of the status output is additionally stored in the status
element of the diagnostic structure.
Additional parameters for an error are stored in the additionalValueX tags. The
neutral designation of the additionalValueX values should be kept to enable saving
different values on a memory area.
If further elements become necessary, they can be added.
4.6 Libraries
In this chapter, rules and recommendations for programming libraries are specified.
The rules for source code and tag names introduced in the previous chapters are
binding for creating libraries.
the library and the block/constant name. The maximal character length for a library
name, and hence for the prefix, is limited to 8 characters.
This restriction is used for compact name assignment.
NOTICE If a block is inserted into a library, all properties of the block, such as block
number and know-how protection, must have been set already. Once the block is
in a library, its properties cannot be changed anymore.
Example
Table 4-6: Example for name assignment for library LExample
Type name according to styleguide
Library LExample
PLC data type LExample_type<Name>
Function block LExample_<Name>
Function LExample_<Name>
Organization block LExample_<Name>
PLC tags LExample_<Name>
general constant LEXAMPLE_<NAME>
Constant for error code LEXAMPLE_ERR_<NAME>
Example
Identifier: LCom_CommToClient
Library: LCom
Functionality: communication via TCP/IP between different devices
4.6.2 Setup
NOTICE Know-how protection binds the block to the controller type and firmware of
the last compilation.
That is, if the block has been compiled on an S7-1500 in the development phase,
it cannot be used on an S7-1200 despite S7-1200 compatible programming. It
must also be noted here, that the block is also bound to the firmware as well as
the controller type. A know-how protected block cannot be compiled again
without password. If PLC data types are used, the user must ensure not to
Siemens AG 2015 All rights reserved
Example
Figure 4-16: Structure of a library
Example
Table 4-7: Example for changing the version
Library FB1 FB2 FC1 FC2 Comment
Siemens AG 2015 All rights reserved
Example
Figure 4-17: Properties of a library
4.6.5 Delivery
Example
Figure 4-18
Siemens AG 2015 All rights reserved
6 History
Table 6-1
Version Date Modifications
V1.0 10/2014 First version after internal release
V1.1 06/2015 Adjustments and corrections