You are on page 1of 36

Structured Software Development

TM230

TM230TRE.00-ENG
2013/03/12
Prerequisites and requirements
TM210 Working with Automation Studio
TM223 Automation Studio Diagnostics
Training modules TM24x At least one programming language
Software Automation Studio 3.0.90
Hardware None

2 TM230 - Structured Software Development


Inhaltsverzeichnis

INHALTSVERZEICHNIS

1 INTRODUCTION.................................................................................................................................. 4
1.1 Training module objectives..................................................................................................... 4
2 THE SOFTWARE DEVELOPMENT PROCESS..................................................................................5
2.1 Steps in software development.............................................................................................. 5
2.2 Software quality.......................................................................................................................6
2.3 The high cost of error correction............................................................................................ 6
3 PROJECT STRUCTURE..................................................................................................................... 7
3.1 Structured software architecture............................................................................................. 7
3.2 Case study: Injection molding machine.................................................................................. 8
4 STATE DIAGRAMS............................................................................................................................ 10
4.1 Types of logic........................................................................................................................10
4.2 State machines..................................................................................................................... 13
4.3 Implementation...................................................................................................................... 14
4.4 Case study: Sorting parts with a conveyor belt.................................................................... 17
5 B&R SOFTWARE ENGINEERING GUIDELINES............................................................................. 21
5.1 Concept and design..............................................................................................................21
5.2 Compiler warnings................................................................................................................ 21
5.3 Creating documentation........................................................................................................ 22
5.4 Naming conventions..............................................................................................................22
5.5 Code format.......................................................................................................................... 25
5.6 Programming techniques...................................................................................................... 28
5.7 Testing...................................................................................................................................31
6 SUMMARY......................................................................................................................................... 32

TM230 - Structured Software Development 3


Introduction

1 INTRODUCTION

This training module covers the topic of software development in the field of automation.
If you are a programmer of systems or machines, please take a moment to think about the
following questions:
Is software development more than just programming, programming and still more program-
ming?
How can I improve the quality of my software?
What is software quality?
What are the costs involved in correcting errors?
How do I create well-structured software?
Is there a formal and precise way to analyze, describe and discuss machine logic?
How can I write better source code?
How should I document and test my software?

Interested? Then jump right into the next section!

Every error costs time and money!

1.1 Training module objectives

Aided by selected examples that describe typical application tasks, you will learn how to optimize the
way you work.
Once you have completed this module, you will have gained...
General knowledge regarding various software development approaches, software design and
meeting software quality standards.
A good introduction and overview of state diagrams and state machines.
The ability to analyze, describe and discuss machine logic formally and precisely.
Knowledge of B&R coding guidelines for developing high-quality source code, test procedures
and documentation.

4 TM230 - Structured Software Development


The software development process

2 THE SOFTWARE DEVELOPMENT PROCESS

What does software development actually mean? Here are two definitions:

IEEE 610.12 S. R. Schach: Software Engineering


The application of a systematic, disciplined, quan- Software engineering is a discipline whose aim
tifiable approach to the development, operation is the production of quality software, delivered on
and maintenance of software; that is, the applica- time, within budget and satisfying user's needs.
tion of engineering to software.
Table: Two definitions of software development

2.1 Steps in software development

Typical steps in software development include:


Analyzing the requirements
Developing a software specification
Defining the software design/architecture
Programming
Testing
Creating documentation
Performing the first maintenance steps

The first step in developing a software product is to determine and analyze the necessary requirements.
This requires some degree of both technical knowledge as well as experience in order to identify re-
quirements that are incomplete, unclear or contradictory.
The result should be a precise definition of the software to be developed the software specification.
A software specification is generally a written agreement with the customer regarding the project and
its scope.
As such, this specification forms the basis of how the software architecture is developed. It lays down
basic principles about what the software should do without going into too much detail.
Software architecture can be defined as "the set of structures needed to reason about the software sys-
tem, which comprise software elements, the relations between them and the properties of both elements
and relations". It is always a good idea to discuss and agree upon an architecture together with the
customer.
During the implementation phase, this architecture is drafted in a specific programming language.
Subsequent steps include testing, creating documentation and maintaining the software.

The following points must be taken into consideration when analyzing the requirements and
developing the software specification:
Operating modes (manual, automatic, etc.)
Emergency situations and safety
Error handling
Providing diagnostic information
Remote access (via HMI, VNC, HTTP, etc.)

TM230 - Structured Software Development 5


The software development process

2.2 Software quality

The following are criteria important to the quality of application software:


Making sure that the specification matches the requirements
No software errors
Source code quality:
How a program is written can have dramatic consequences, especially for maintenance. Read-
ability, easy maintenance and a code structured in logical sections are crucial.
Light resource requirements (memory, CPU time, etc.)

2.3 The high cost of error correction

Like any other project, developing a software system requires both people and money.
People make mistakes, and mistakes cost money. When developing software, it pays to do things right
the first time, especially since the cost of correcting errors increases dramatically from the time an error
is made to the time it is detected. This is illustrated by an image taken from Steve McConnell's book
Code Complete.

The cost of error correction: Comparison of when an error is made and when it has been detected (S. McConnell: Code
Complete)

As this image shows, it is extremely important to detect and correct errors as soon as possible after
they have been made.

6 TM230 - Structured Software Development


Project structure

3 PROJECT STRUCTURE

3.1 Structured software architecture

A clean architecture and design are the basis for developing good software.
It is important in this regard to consider the possibilities and limits of all of the platforms on which the
software is to be used.
During the conception phase, take the time to work on the software design until you are completely
satisfied with your concept. The time used to develop an ideal software architecture is not wasted by
any means since it will easily be regained later during the implementation phase.
Studies have shown that programmers who jump right in without thinking require much more time to
complete their projects than those who plan ahead.
One possibility to consider when developing the system architecture is the structured design approach.
This is a top-down approach characterized by either a continuous or step-by-step refinement of the
software. With this methodology, a problem is analyzed and split into a series of smaller parts that are
easier to manage (a process known as continuous refinement).
This strategy dates back at least 2000 years in human history to the time of Marcus Aurelius, a Roman
emperor made famous by his dictum "divide et impera", or "divide and conquer".
The basic approach of the structured design methodology is to take a general statement of what the
software should be doing (i.e. its function) and break it down into more detailed and specific tasks.
Subsystems are defined first, with the program being split into its main components and linked together
by interfaces that must also be defined. Well-designed interfaces between modules are an extremely
important aspect of software architecture. The lists below provide additional information about these
topics.

An extremely important part of software design has to do with how the information flow is
represented. This is used to determine answers to the following questions:
Where is data located in the software objects?
How is data exchanged between software objects?
How is the data contained in data structures managed?

Software architecture formulated using this method can be summarized as follows:


The highest level is defined first.
Details are shifted to lower levels.
Each level is formalized.
Each level is checked against the specification.
Continue to the next level.
As soon as it becomes easier to program the next level, the process of dividing up levels is
stopped. The design should then be simple and transparent.

Software design is not strictly a deterministic process; creativity plays a much greater role.

TM230 - Structured Software Development 7


Project structure

3.2 Case study: Injection molding machine

Level 1
Let us take a look at an injection molding machine. The highest level of the software architecture is the
entire machine itself. Each detail is allocated to a lower level.

Software architecture at the highest level

Level 2
The basic functions of the machine are divided up on the second level (mechanically in this case): the
injection unit, hydraulic clamp cylinder, mold, transport, feeder, dosage and a general module responsible
for the logical functions that take place on the machine.
The following image illustrates the second level of the system architecture including all interrelationships
and interfaces.

Software architecture on the second level

The "Transport" module


Components that handle basic functions are further refined on the
third level.
For example, the "Transport" module is divided up into two addition-
al modules "Scales" and "Conveyor belt". The "Scales" module
weighs the product and tells the "Conveyor belt" module what should Dividing up the "Transport" module
be done with it (additional processing if the product is OK or discard
if not). The "Conveyor belt" module then signals when it is ready for
the next product.

8 TM230 - Structured Software Development


Project structure

The "Mold" module


The "Mold" module is further refined into the "Hydraulic ejec-
tor", "Cores" and "Mold heating" modules. "Hydraulic ejector" and
"Cores" may not be active at the same time. Neither of them have a
connection to "Mold heating", which is nonetheless exchanging data
with the "General" module.
Dividing up the "Mold" module

The "Injection unit" module


The "Injection unit" module is further divided between the "Injection
piston" and "Barrel heating" modules. There is no direct connection
between these modules, but both receive their instructions from the
"General" module.
Dividing up the "Injection unit" module

Data interrelationships
The following image illustrates the data interrelationships between the "General", "Mold" and "Transport"
modules.

Data interrelationships between modules

TM230 - Structured Software Development 9


State diagrams

4 STATE DIAGRAMS

One of the most frequent tasks of software engineers in the field of industrial automation is to program
the logic that determines the general functionality of a particular machine or system.
Usually, this machine or system logic is described using text, which can be very imprecise. The logic of
machines and systems can be described very precisely and formally through the use of state diagrams,
however. In addition, state diagrams are often a practical and formal way to discuss the behavior of a
machine with customers.
Once the state diagram for the desired logic has been defined, implementation is generally no longer
a problem.
This section therefore presents a good opportunity to learn more about state diagrams and their use as
a powerful method for analyzing and describing machine sequences and system procedures.
All program sections described in the section below refer to ANSI C, including the list of operators in
the following table:

Operator Description
! Logical negation
= Basic assignment
== Equal to
&& Logical AND
++ Increment
Table: List of operators

4.1 Types of logic

4.1.1 Combinational logic

Let us consider a tank that is filled with water:

Closed loop water tank temperature control

Water is released from the tank when an external valve is opened. The water level is kept constant by
a pump that is turned on as soon as water falls beneath a certain level. The level is monitored by a
level sensor:
pumpOn = (!levelSwitch);

10 TM230 - Structured Software Development


State diagrams

Next, a heating element should keep the temperature of the water at the value Tset. The current water
temperature Tact is measured with a temperature sensor. The heating element is turned on if the water
level is OK and the temperature is below the value Tset:
heaterOn = ((levelSwitch == 1) && (Tact < Tset));

This example uses the following inputs and outputs.

Data direction Name Data type Description


IN Tset INT Temperature setpoint
IN Tact INT Current temperature
IN levelSwitch BOOL Level sensor
OUT pumpOn BOOL Pump controller
OUT heaterOn BOOL Heating element
Table: Inputs and outputs in this example

The outputs are a function of and only of the current inputs. There is therefore a static relationship,
known as combinational logic, between the inputs and outputs. This type of logic is implemented without
the use of memory.
Because memory is not used, combinational logic has severe limitations when implementing the desired
functionality of a machine or system.
Disadvantages of the example above:
If the water level falls beneath the level sensor, then the pump is turned on. The water refills,
and the pump is turned back off again. Continuously turning the pump on and off in this way
will have negative effects on the service life of the pump over time.
The same is true for the heating element. If it is turned on, then the water temperature increas-
es, causing the heating element to be turned back off again. The water cools, which then turns
the heating element back on. This also decreases the lifespan of the heating element.

To eliminate these disadvantages, we will need to make our logic a bit more intelligent.

4.1.2 Sequential logic

The solution described in this section will not turn off the pump as soon as the level sensor has been
reached; a delay time tDelay will be applied instead.

TM230 - Structured Software Development 11


State diagrams

Sequential water level control logic: Delay time (tDelay)

In addition, we will add a hysteresis value to the switching threshold for turning off the heating element.
It will not be turned off when Tact reaches the value of Tset, but only when Tact > (Tset+deltaT).

Sequential water temperature control logic: Hysteresis

Now the heaterOn and pumpOn outputs are no longer switched directly by the inputs:
If Tset < Tact < (Tset+deltaT), then the past history of Tact will determine whether the
heating element is turned on or not. It will be turned on if less time has passed since the last
occurrence of the state Tact == Tset than the time that has passed since the last occur-
rence of the state Tact == (Tset+deltaT). Otherwise, the heating element is turned off.
The pump can now be turned on if levelSwitch == 1. Again, the past history of lev-
elSwitch determines whether the pump is turned on or off. It will be turned on if less than tDe-
lay seconds have passed since the last time levelSwitch changed from 0 to 1.

As a result, the outputs in this improved logic scenario no longer depend solely on the current state of
the inputs, but rather on their past states as well. This type of logic is called sequential logic. Sequential
logic is able to take note of and save information for later use.

12 TM230 - Structured Software Development


State diagrams

To describe the behavior of sequential logic, we will need additional variables to hold the stored infor-
mation. These variables, referred to as state variables, store the current state of the logic.

4.2 State machines

The first step when analyzing sequential logic is to define the number of state variables and the various
possible states they can represent. We can use the following state variables for our example:

pumpState with three possible values heaterState with two possible values
PUMP_OFF HEATER_OFF
PUMP_ON_LEVELTOOLOW HEATER_ON
PUMP_ON_TIMEDELAY
Table: Overview of state variables

Our sequential logic therefore has two state variables: the pumpState state variable can have three
possible values, whereas heaterState can have two.
A state machine describes sequential logic with a finite number of states.

Element Description
States A state could represent the initialization or default state of the machine
when it is turned on, for example.
Events Events triggers transitions between states and must be prioritized if simul-
taneous events are allowed to occur in a particular state (see the section
after the next example).
Actions There are two types of actions:
Actions that are triggered when transitioning to a state (e.g. setting
outputs)
Actions that are triggered during a state (e.g. counters)
Transitions Transitions occur between states, are triggered by events and trigger ac-
tions themselves, e.g "If we are in State x1 and Event y occurs, trigger Ac-
tion z and switch to State x2".
Table: Elements of a state machine

In our example, a transition between states can be triggered by one of the following events:
TooCold: (Tact < Tset) switches from FALSE to TRUE
TooHot: Tact > (Tset+deltaT) switches from TRUE to FALSE
LevelOk: levelSwitch switches from FALSE to TRUE
LevelNotOk: levelSwitch switches from TRUE to FALSE
TimerElapsed: tDelay seconds have passed since the last occurrence of LevelOk

These actions are available:


SwitchPumpOn
SwitchPumpOff
SwitchHeaterOn

TM230 - Structured Software Development 13


State diagrams

SwitchHeaterOff
ResetTimer
IncrementTimer (this action does not trigger a transition but is instead executed while in the
TIMER_ON state)

4.2.1 Transition tables

A transition table lists the available transitions in table form:

State Event Action Transition to


HEATER_OFF TooCold SwitchHeaterOn HEATER_ON
HEATER_ON TooHot SwitchHeaterOff HEATER_OFF
Table: Transition table for the heating element

State Event Action Transition to


PUMP_OFF LevelNotOk SwitchPumpOn PUMP_ON
PUMP_ON LevelOk ResetTimer TIMER_ON
TIMER_ON TimerElapsed SwitchPumpOff PUMP_OFF
Table: Transition table for the pump

4.2.2 State diagrams

State diagrams are a visual representation of a state machine.

State diagram for the heating element

State diagram for the pump

4.3 Implementation

After the sequential logic for the machine has been described and formalized successfully, the actual
implementation is a clear and simple task. Pseudocode can be used, for example, to sketch out how a
state machine can be implemented.
switch(state)
for all states i
case (state i)
perform actions in state i
for all events j

14 TM230 - Structured Software Development


State diagrams

if event j
then take action k
transition to state l
This code snippet is written in brief notation to illustrate the sequential logic. Actual implementation can
be considerably longer, as demonstrated in the following example:

/*************************************************************
* COPYRIGHT B&R Industrial Automation
*************************************************************
* Program: Closed loop tank control
* File: CLTankcontrol.c
* Created: 1/4/2012
*************************************************************
* Implementing the closed loop tank control program
*************************************************************/

#include<bur/plctypes.h>

#ifdef _DEFAULT_INCLUDES
#include <AsDefault.h>
#endif

#define PUMP_OFF 0
#define PUMP_ON 1
#define TIMER_ON 2

#define HEATER_OFF 0
#define HEATER_ON 1

/* ----------- Events ------------ */


BOOL TooCold( void)
{ return(Tact < Tset);}

BOOL TooHot( void)


{ return(Tact > (Tset + deltaT));}

BOOL LevelOk( void)


{ return(!levelSwitch);}

BOOL LevelNotOk( void)


{ return(levelSwitch);}

BOOL TimerElapsed( void)


{ return(timer == tDelay);}

/* ---------- Actions ---------- */


void SwitchPumpOn( void)
{ pumpOn = 1;}

void SwitchPumpOff( void)


{ pumpOn = 0;}

TM230 - Structured Software Development 15


State diagrams

void SwitchHeaterOn( void)


{ heaterOn = 1;}

void SwitchHeaterOff( void)


{ heaterOn = 0;}

void ResetTimer( void)


{ timer = 0;}

void IncrementTimer( void)


{ timer++;}

void_CYCLIC WaterTankCYCLIC( void )


{
/* ----------- Pump ----------- */
switch (pumpState)
{
case PUMP_OFF:
if (LevelNotOk())
{
SwitchPumpOn();
pumpState = PUMP_ON;
}
break ;

case PUMP_ON:
if (LevelOk())
{
pumpState = TIMER_ON;
ResetTimer();
}
break ;

case TIMER_ON:
IncrementTimer();
if (TimerElapsed())
{
SwitchPumpOff();
pumpState = PUMP_OFF;
}
break ;
}
/* end switch */

/* ---------- Heating element ---------- */


switch (heaterState)
{
case HEATER_OFF:
if (TooCold())
{
SwitchHeaterOn();

16 TM230 - Structured Software Development


State diagrams

heaterState = HEATER_ON;
}
break ;

case HEATER_ON:
if (TooHot())
{
SwitchHeaterOff();
heaterState = HEATER_OFF;
}
break
;
}
/* end switch */
}
/* end WaterTankCYCLIC */

4.4 Case study: Sorting parts with a conveyor belt

Let us assume we have a conveyor belt that is being used to transport parts of various length. The control
logic should sort out the parts where L <= A1 or L >= A2. The length of the parts is measured using
photoelectric barriers (digital inputs B1, B2 and B3). An input switches to 1 whenever a part moves past.
The sorting out process is implemented using the digital signal lengthOk = 1, which controls a pneu-
matic actuator that pushes parts with the correct length to another conveyor belt. The actuator then re-
turns automatically to its original position.
The distances between the barriers are A1 and A2, where A1 > A2/2. The interval between two parts
is much greater than A2 to prevent any problems.

TM230 - Structured Software Development 17


State diagrams

The sorting procedure

Our task is to design the control logic for the pneumatic actuator. In this example, we will be concen-
trating on the process logic and explicitly neglecting error handling (which is otherwise an essential
component of real applications).
The photoelectric barriers are represented by (B1B2B3) in the following.

(010) means B1 = 0, B2 = 1 and B3 = 0.

Condition Sequence
Sequence at the input for a part with the correct length:
A1 < L < A2 (000),(100),(110),(010),(011),(001),(000)
Sequences for incorrect length:
L > A2 (000),(100),(110),(111),(011),(001),(000)
L = A2 (000),(100),(110),(011),(001),(000)
L = A1 (000),(100),(110),(010),(001),(000)
A4 < L < A1 (000),(100),(110),(010),(000),(001),(000)
L = A4 (000),(100),(010),(000),(001),(000)
L < A4 (000),(100),(000),(010),(000),(001),(000)
Table: Overview of sequences

18 TM230 - Structured Software Development


State diagrams

Event Description
Enter1 B1 switches from 0 to 1 (part arrives at Barrier 1)
Enter2 B2 switches from 0 to 1 (part arrives at Barrier 2)
Enter3 B3 switches from 0 to 1 (part arrives at Barrier 3)
Pass1 B1 switches from 1 to 0 (part passes Barrier 1)
Pass2 B2 switches from 1 to 0 (part passes Barrier 2)
Pass3 B3 switches from 1 to 0 (part passes Barrier 3)
Table: Overview of events

Action Description
lengthOk = 1 Sets Push
lengthOk = 0 Resets Push
Table: Overview of actions

A solution with 13 states and 19 transitions is illustrated in the following state diagram.
Events with the highest priority are indicated with (P) in the transition table.
This means, for example, if we are in the state OK1 and the Pass1 event occurs, we switch to the state
TOOSHORT1. If Pass1 and Enter2 occur in the same cycle, however, then we switch to TOOSHORT2.

State Event Action Transition to


INIT Enter1 OK1
OK1 Pass1 & Enter2 (P) TOOSHORT2
OK1 Pass1 TOOSHORT1
OK1 Enter2 OK2
OK2 Pass1 & Enter3 (P) TOOLONG2
OK2 Enter3 TOOLONG1
OK2 Pass1 OK3
OK3 Pass2 & Enter3 (P) FAILED
OK3 Pass2 TOOSHORT3
OK3 Enter3 OK4
OK4 Pass2 OK5
OK5 Pass3 Push FINALOK
FINALOK Reset INIT
TOOSHORT1 Enter2 TOOSHORT2
TOOSHORT2 Pass2 TOOSHORT3
TOOSHORT3 Enter3 FAILED
Table: Overview of transitions

TM230 - Structured Software Development 19


State diagrams

State Event Action Transition to


TOOLONG1 Pass1 TOOLONG2
TOOLONG2 Pass2 FAILED
FAILED Pass3 INIT
Table: Overview of transitions

Note that actions are only executed in 2 of the 19 transitions, with the transition from FINALOK
to INIT not having to be triggered by an event. This takes place automatically at the next cycle.

State diagram for the conveyor belt logic

20 TM230 - Structured Software Development


B&R software engineering guidelines

5 B&R SOFTWARE ENGINEERING GUIDELINES

Computer programming is an engineering task, and as always in software development, there is one
absolute truth either the program works or it doesn't.
Nevertheless, programming is also an art (see the well-known book "The Art of Computer Programming"
by Donald E. Knuth, which counts among the best scientific monographs ever written), and it is often a
matter of personal taste as to whether a program looks attractive and how effectively it performs its job.
Without a doubt, programming is a creative process. The production of software costs money but it
also generates money. B&R follows a philosophy of producing high-quality products, and software is
no exception.

Characteristics of high-quality code include:


A clean architecture and design
Easy to read and to understand
Easy to maintain
Reusable
Clearly and thoroughly commented
Error-free

This section is meant to help you improve your own source code.
Following these guidelines is certain to produce source code of outstanding quality.
When working in a team, it is important to consider the other engineers you are working with. There's
a good chance they won't appreciate going over source code that was written in a rush at 2:00 AM on
Saturday morning, for example.
In the end, we're each responsible for the source code that we write ourselves. Conscientious work is
the key to success.

5.1 Concept and design

A clean architecture and well thought-out design are the foundation for developing good software. Take
your time during the design phase until you are completely satisfied with your software concept.
Before starting, please consider the concepts and methods covered in the various sections of this training
module.

5.2 Compiler warnings

Compiler warnings indicate potentially unexpected program behavior, whose cause would otherwise be
difficult to identify.
A project must be free of warnings output during compilation. Any warnings that do occur must be iden-
tified at the source and corrected.

TM230 - Structured Software Development 21


B&R software engineering guidelines

5.3 Creating documentation

Documenting your software is also a very important task. On the one hand, it supports users in figuring
out how to make use of all of the functionality available to them. On the other hand, it also supports other
programmers who might want to fix an error or add new functionality to the software.
Documentation usually consists of information contained within the code (e.g. comments) as well as
information provided outside of it (e.g. a separate document).

5.4 Naming conventions

Choosing meaningful names for variables and data types is a key factor in creating clear program code.
All names should be descriptive and easy to read. To increase readability, capital letters are used when
combining words. For example:
ActPressure = ActForce / PistonArea;
CommandCount++;
The only exception to this rule is counter variables. Individual letters can be used for these, for example
i, k and m.
Variable names can include both letters and numbers, but they must start with a letter. Reserved key-
words cannot be used. A complete list of reserved keywords for each programming language can be
found in the Automation Studio online help documentation.

5.4.1 User data types (structures)

User data types start with a capital letter and end with _type. Elements in a structure start with a capital
letter:
TYPE
Recipe_type: STRUCT
Base: UINT;
Binder: UINT;
Additive: USINT;
END_STRUCT ;
MachineParams_type: STRUCT
Speed: REAL;
Pressure: REAL;
Temperature: INT;
pRecipe: REFERENCE TO Recipe_type;
END_STRUCT ;
END_TYPE

5.4.2 Constants

Constants are written in CAPITAL LETTERS. Underscore characters are used to more clearly separate
words written together:
VAR CONSTANT
STEP_CONDITIONING: USINT := 23;
HEATING_TIME_OUT: UINT := 5000; (* [s] *)
MAX_PRESSURE: REAL := 6.7e+006; (* [Pa]*)
END_VAR

22 TM230 - Structured Software Development


B&R software engineering guidelines

These rules also apply to constants that have been defined with the #define directive or the enum
statement in ANSI C. Note that declarations made with these statements only apply to that particular
section of the C source code.

5.4.3 Local variables

Local variables begin with a capital letter. Capital letters can also be used elsewhere to improve read-
ability:

VAR
MachineStep: USINT;
ActualPressure: REAL; (* [bar] *)
AverageTemperature: INT; (* [0.1C] *)
END_VAR

5.4.4 Global variables

Global variables begin with the prefix "g" followed by a capital letter:
VAR
gHeaterOn: BOOL;
gActualCommand: Command_typ;
gCommandCount: UINT;
END_VAR
This naming convention is only intended for global variables and variables defined globally in a package
it is not to be used for local variables.

5.4.5 Pointers

Local pointers begin with the prefix "p" followed by a capital letter. Global pointers are not supported
in IEC languages.
VAR
pActualRecipe: REFERENCE TO Recipe_type;
END_VAR
There is no defined prefix for structure addresses. Nevertheless, the name itself should indicate that it
is an address:
AddressRecipe := ADR(RecipeRegularCoffee);

pActualRecipe ACCESS AddressRecipe;

ActualPrice := pActualRecipe.Price;
ActualSetTemperature := pActualRecipe.SetTemperature;
ActualMilk := pActualRecipe.Milk;
ActualSugar := pActualRecipe.Sugar;
ActualCoffeePowder := pActualRecipe.CoffeePowder;
ActualWater := pActualRecipe.Water;

5.4.6 Hardware-related variables

Variables assigned to hardware inputs or outputs start with a prefix that identifies the type of I/O point:

TM230 - Structured Software Development 23


B&R software engineering guidelines

Prefix Type
di Digital input
do Digital output
ai Analog input
ao Analog output
at Temperature input
Table: Overview of prefixes and types

Once again, the prefix is followed by a capital letter:


VAR
diEmergencyOff: BOOL;
doSolidStateOn: BOOL;
aiActualPressure: INT; (* [0.1bar] *)
aoValvePos: INT; (* 0=closed, 32767=open *)
atActualTemperature: INT; (* [0.1C] *)
END_VAR
Prefixes are combined for global I/O points:
VAR
gdiEmergencyOff: BOOL;
gdoSolidStateOn: BOOL;
END_VAR
This naming convention is reserved for hardware-related variables it is not to be used for other vari-
ables.

5.4.7 Function blocks instances

Function blocks instances must be named in a way that indicates their function in the code. Other than
that, the same naming conventions as described above apply.
VAR
ValveSwitchTimer : TON;
AbsoluteMoveConveyor : MC_BR_MoveAbsoluteTriggStop;
PressurePIDControl : LCPID;
END_VAR

5.4.8 Enumerators

Enumerators allow the programmer to create an "array of constants". When an enumeration variable is
created, it can only accept (valid) values defined in the enumeration. Examples of when to use enumer-
ators include machine/sequence modes or access rights for users.
Enumerators make it possible to assign any element a value; however, two elements can never have
the same value. The first element has a value of 0 (unless otherwise defined), while each subsequent
element is incremented by 1.
Elements in enumerators are defined in Automation Studio with the type DINT, which allows them to
take on negative values as well.

24 TM230 - Structured Software Development


B&R software engineering guidelines

Rules for enumerators:


Enumerator names are always written in CAPITAL LETTERS.
Enumerators are not identified by a prefix or suffix.
Each enumerator element must start with the name of the enumerator (e.g.
USERLEVEL_NONE, USERLEVEL_OPERATOR, USERLEVEL_SUPERVISOR, etc.).

5.5 Code format

Source code layout should precisely represent the logical structure of a computer program. How code
is structured visually can be an important factor in how the brain processes the information conveyed.

5.5.1 Indentation

Proper use of indentation plays an important role in aspects such as readability and is an absolute must
in all programs.
The purpose of indentation is to clearly indicate where a block of statements begins and ends.
Large indentation (6 - 8 characters) makes it easier to understand the code structure, while smaller
indentation (2 - 4 characters) saves space on the right side of the screen.

The editor offers some assistance here by providing automatic indentation and highlighting
associated pairs of parentheses.

5.5.2 File headers

Each file (source code, variable declarations, data type declarations, etc.) must have a header that at
least includes the following information:
Information about the author (e.g. B&R Sweden), file, program, date and copyright
A short description explaining the purpose of the code
A description of the task interfaces (input and output variables used in the task)
Information about project development: revision number, date (in a format understood world-
wide, e.g. 09-August-2010 instead of 09-08-2010), author and a brief description of the
changes made since the previous version
Timing and memory requirements, if critical
Limitations of the task

Example:
(***************************************************************
* COPYRIGHT -- Bernecker + Rainer
***************************************************************
* Program: Calculation
* File: Calculation.st
* Author: B&R International Application
* Created: June 16, 2010
***************************************************************
* Implementation of program Calculation
***************************************************************

TM230 - Structured Software Development 25


B&R software engineering guidelines

* Description:
- Task to calculate the pyramid positions
- Error handling included
* Interface
- gCalculate is the interface of this task
- Commands are received over the gCalculate.cmd inputs
- Calculated values will be written to the
gCalculate.PyramidPosition structure
***************************************************************
Version | Date | Author | Description
---------------------------------------------------------------
V1.00.0 | 27-June-2010 | Int. App. | Calculation of one pyramid
V1.00.1 | 28-June-2010 | Int. App. | Calculation of two pyramids
V2.00.0 | 01-July-2010 | Int. App. | Error handling improved
**************************************************************)
A header template is included automatically when a program is created in Automation Studio.
The format used for the revision number is Vxx.yy, with xx incremented after each major change or
update (e.g. if new features are integrated or if functions become incompatible with the previous version).
yy is incremented after smaller updates such as bug fixes.

5.5.3 Comments

Documentation contained within the code is intended for developers, not users.
The largest contribution to good documentation is not provided by the comments, but rather by the
programming style itself. Good code is its own best documentation.
Nevertheless, comments are necessary in every program to provide information that the code itself
cannot provide.
Types of comments:
Summary comment
Like the foreword at the beginning of a book, this type of comment provides an overview of the
program at the beginning of the code.
Indented comment
This type of comment explains the purpose of a section of code with an emphasis on the problem
rather than the solution (explains the why, not the how).
Marker comment
This type of comment marks sections of code where an error is suspected or where improve-
ments or additions are planned. These are useful during development but should not be included
in the final version.

Things to be documented:
Derived data types (structures, enumerations, derived types with subranges, etc.)
Variable declarations (also with respect to physical relationships)
Main steps in your routines
Boundaries between your routines
Global relationships between your routines
Suggestions for interfaces
Version history

26 TM230 - Structured Software Development


B&R software engineering guidelines

Things not to be documented:


Things that are obvious to programmers
If your code is too hard for others to understand, rewrite it!

Do not forget to update your comments when something is changed in the code!

5.5.4 Spaces

A space should be added before and after each operator to improve readability:
XAxisPosition = XAxis + DeltaX;
if (MachineState == STATE_RUN)
...
Keep in mind the following exceptions:

Operator Description
. Structure element operator
-> Structure element operator
[] Index operator
() Function call or function declaration
(type) Type conversion
++ Increment operator
-- Decrement operator
! Negation
~ One's complement
Table: Spaces may not be used in front of these operators

If the assignment operator "=" is used directly after a variable, then it is possible to find only variable
assignments in the editor by searching for something like "someVariable=" (also applies to search and
replace). If this is important to you, then you should write your assignments like this:
XAxisPosition= XAxis + DeltaX;
We recommend writing reference "&" and dereference "*" operators together with the type (not with the
name) in the declaration:
void GetControlParameter(Parameters_type* pControlParameters)

5.5.5 Visual alignment

A visual alignment of related elements adds to the perceived relationship between them:
Parameter.X0 = pInternal->X0;
Parameter.DeltaX = Parameter.Dir * abs(Inst.Options.DeltaX);
Parameter.T1Set = 0;
Parameter.T2Set = 0;

TM230 - Structured Software Development 27


B&R software engineering guidelines

5.6 Programming techniques

5.6.1 Local C variables

The scope of variables defined in C source code is not visible outside of the area where they are defined,
e.g. they will not appear in the Watch or Trace windows.
Recipe_type* pPrevRecipe = 0;
USINT cmdCount = 0;
REAL actSpeed = 0;
A variable that is not defined as "static" will be allocated by the stack each time the routine is executed,
but it will not be initialized! This is why it is always a good idea to initialize variables when they are
declared (as shown above).

5.6.2 GOTO statement

The GOTO statement should never be used since it stands in the way of clearly structured code.
If you do feel the temptation to use the GOTO statement, think about the famous letter from Edsger W.
Dijkstras entitled "Go To Statement Considered Harmful", published in 1968:
"For a number of years, I have been familiar with the observation that the quality of programmers is a
decreasing function of the density of GOTO statements in the programs they produce."
There's really nothing else to add.

5.6.3 Using standard algorithms

Standard algorithms can be used for things like ring buffers, searching or sorting. If you were to implement
these algorithms yourself, it would probably require quite a bit of testing and debugging. A better solution
is to use an algorithm from a reliable source, such as a companion CD for a book about algorithms.

5.6.4 Using IEC data types

To ensure platform independence and consistency, IEC data types should be used in C source code.
They can be included automatically with:
#include<bur\plctypes.h>

5.6.5 Dynamic memory management

Caution is advised when dealing with dynamically allocated memory. Accessing memory that has only
been allocated in your mind, instead of in the operating system, can lead to errors that are very difficult
to find!
Frequently allocating and enabling memory in cyclic tasks leads to memory fragmentation and should
be avoided. Eventually, you will run out of memory.

5.6.6 Determining the size of arrays

If you need to know the size of an array (e.g. when the last element is used or a loop should be applied
to all elements), it can be determined using the "sizeof" command:
for (i = 0; i < ( sizeof(Array)/sizeof(Array[0])); i++)
{
loop body

28 TM230 - Structured Software Development


B&R software engineering guidelines

5.6.7 Hardware-related variables

The basic rule here is that outputs must only be defined in exactly ONE location in a project. Defining
an output in two different places in a project can have unpredictable consequences!
We therefore recommend copying inputs and outputs to an appropriate software module structure in a
single separate task.
This task can then be disabled to interrupt the connection to the inputs and outputs for testing purposes.
It also makes it much faster and easier to make changes to the inputs and outputs (e.g. inverting an
output).
The following images illustrate this sort of structure and the associated mapping:

Input and output structures

Input task mapping example

Output task mapping example

TM230 - Structured Software Development 29


B&R software engineering guidelines

5.6.8 Data alignment

Data alignment is an aspect that must be considered when creating user-defined data types. The com-
piler generally adds meaningless bytes (usually 1-3) between elements in a structure so that they can
be accessed at a specific address (e.g. even number).
As a result, the compiled data ends up being larger than the sum of its elements. This can vary with
different hardware architectures but is easily checked using the "sizeof" function.
When writing code that is platform-independent or setting up communication to other devices, be sure to
take data alignment into consideration, especially when using data objects. This will allow you to place
unused alignment bytes where you need them in order to ensure the same data layout for all hardware:

TYPE
Cutter_type: STRUCT
Speed: REAL; (* 4 bytes *)
CommandCount: USINT; (* 1 byte *)
Reserve1: USINT; (* Alignment *)
XPosition: UINT; (* 2 bytes *)
YPosition: UINT; (* 2 bytes *)
Reserve2: USINT; (* Alignment *)
Reserve3: USINT; (* Alignment *)
CutterTON: TON_typ; (* Align like 4-byte type *)
END_STRUCT
END_TYPE

Additional information about data alignment can be found in the Automation Studio online help docu-
mentation.

5.6.9 Communication between software modules

Communication between modules can be implemented using global data structures, but this requires
careful consideration. Be sure to assign clear and meaningful names to your communication data struc-
tures.

Communication between software modules can also be implemented using variable mapping.

Programming \ Editors \ Configuration editors \ Variable mapping

5.6.10Handshakes

Handshaking methods must be defined between two programs that communicate with each other in
order to prevent one or both of the tasks from crashing. It is also important to consider multithreading
problems that can occur when two programs are running in different task classes.

30 TM230 - Structured Software Development


B&R software engineering guidelines

5.7 Testing

The testing phase is essential for ensuring the quality of software and guaranteeing that the code be-
haves as specified.
The first step in testing usually involves defining test cases that are based on the software specifica-
tion. The testing of particular situations and functions (special and worst-case scenarios) demands care-
ful attention, e.g. determining what happens if a function is provided with an incorrect value. As Brian
Kernighan, co-author of the C programming language, explains, "An effective way to test code is to ex-
ercise it at its natural boundaries."
When working on a project in a team, keep in mind that you will be testing each other's code (one of
your colleagues independently tests your code, and vice-versa).
Automation Studio provides excellent tools for testing, for example the Watch window, a variable oscillo-
scope and the ability to force variables. These diagnostic tools are covered in greater detail in the TM223
Automation Studio Diagnostics training module.

5.7.1 Unit testing

The goal of unit testing is to determine whether isolated sections (libraries, modules, functions, etc.)
work correctly.

5.7.2 Integration testing

Integration testing involves combining individual software modules into a group and testing them to en-
sure that they work together properly.

5.7.3 System testing

System testing is performed on an entire system to test the requirements listed in the specification (IEEE
Computer Standards directory). This is generally performed when a machine or system is being com-
missioned.

5.7.4 Operability testing

This type of testing helps determine the user-friendliness of the system you have programmed by indi-
cating how easily it can be operated by personnel. This test applies primarily to HMI.

TM230 - Structured Software Development 31


Summary

6 SUMMARY

This training module had covered a lot of ground regarding structured software development as it is
applied to the field of industrial automation.
The different approaches to software development were discussed in the section entitled "The software
development process". We have learned that computer programming is not just about programming, but
also involves analyzing requirements, developing a specification, coding, testing, creating documentation
and performing maintenance.
We have also learned that high-quality software involves more than just making sure that program code
does not contain errors; it includes ensuring that the original requirements are met, the specification
is adhered to, overall readability, simple maintenance and a logical structure that is broken down into
clear parts.

Well-structured program code... ...saves time

The "Project structure" section dealt with software architecture and design as a crucial component of
quality software. Good programming doesn't start with the programming it begins with the architecture.
Combinational logic and sequential logic were discussed in the "State diagrams" section. The latter
allows information to be saved, making it ideally suited for describing the logical functions of a machine.
State machines are a formal and exact description of sequential machine logic and consist of states,
events, actions and transitions. State diagrams are a visual representation of a state machine.
The "B&R software engineering guidelines" section covered B&R coding guidelines for industrial au-
tomation applications and provided additional support for programmers striving to develop a program-
ming style that includes creating, testing and documenting high-quality source code.

32 TM230 - Structured Software Development


Training modules

TRAINING MODULES

TM210 Working with Automation Studio


TM213 Automation Runtime
TM220 The Service Technician on the Job
TM223 Automation Studio Diagnostics
TM230 Structured Software Development
TM240 Ladder Diagram (LD)
TM241 Function Block Diagram (FBD)
TM242 Sequential Function Chart (SFC)
TM246 Structured Text (ST)
TM250 Memory Management and Data Storage
TM400 Introduction to Motion Control
TM410 Working with Integrated Motion Control
TM440 Motion Control: Basic Functions
TM441 Motion Control: Multi-axis Functions
TM450 ACOPOS Control Concept and Adjustment
TM460 Initial Commissioning of Motors
TM500 Introduction to Integrated Safety
TM510 Working with SafeDESIGNER
TM530 Developing Safety Applications
TM540 Integrated Safe Motion Control
TM600 Introduction to Visualization
TM610 Working with Integrated Visualization
TM630 Visualization Programming Guide
TM640 Alarms, Trends and Diagnostics
TM670 Advanced Visual Components
TM800 APROL System Concept
TM811 APROL Runtime System
TM812 APROL Operator Management
TM813 APROL XML Queries and Audit Trail
TM830 APROL Project Engineering
TM890 The Basics of LINUX
TM920 Diagnostics and Service for End Users

TM1010 B&R CNC System (ARNC0)


TM261 Closed Loop Control with LOOPCONR
TM480 The Basics of Hydraulics
TM481 Valve-based Hydraulic Drives
TM482 Hydraulic Servo Pump Drives

TM230 - Structured Software Development 33


Training modules

34 TM230 - Structured Software Development


Training modules

TM230 - Structured Software Development 35


www.br-automation.com
TM230TRE.00-ENG / V1.2.0.1
2013/03/12 by B&R. All rights reserved.
All registered trademarks are the property of their respective owners.
We reserve the right to make technical changes.

You might also like