Industrial Automation & PLC

Chapter 5
PLC Programming Standards and Languages

Bachelors Program in Electrical Engineering
Industrial Automation & PLC   •   Bachelor

PLC Programming Standards and Languages

Introduction

Programmable logic controllers (PLCs) are industrial computers designed to monitor inputs, execute control logic, and command outputs in a predictable cycle. The quality of a PLC application depends not only on whether the machine operates, but also on whether the program is understandable, testable, maintainable, reusable, and safe to modify. Programming standards provide the common language and engineering discipline needed to achieve these qualities.

IEC 61131-3 is the principal international standard associated with PLC programming languages and software organization. It defines programming languages and concepts that allow engineers to structure control applications independently of a particular manufacturer. The standard does not eliminate vendor-specific features, but it provides a widely understood foundation for designing automation software.

This chapter examines four important IEC 61131-3 languages: Ladder Diagram (LD), Function Block Diagram (FBD), Structured Text (ST), and Sequential Function Chart (SFC). It also explains tags, variables, functions, function blocks, programs, program organization units (POUs), modular design, naming conventions, documentation, testing, and practical implementation.

Learning Objectives

After studying this chapter, the learner should be able to:

  1. Explain the purpose and structure of IEC 61131-3.
  2. Distinguish between Ladder Diagram, Function Block Diagram, Structured Text, and Sequential Function Chart.
  3. Select an appropriate language for a control task.
  4. Use tags and data types systematically.
  5. Differentiate functions, function blocks, and programs.
  6. Develop modular PLC software using POUs.
  7. Apply coding, documentation, testing, and version-control conventions.
  8. Analyze a practical automation problem and propose a maintainable solution.

1. IEC 61131-3 and the PLC Software Model

IEC 61131-3 treats a PLC application as a collection of organized software components rather than as one undivided block of logic. The principal elements are:

  • Variables: Data objects used by the program.
  • Data types: Rules describing the kind of value a variable stores.
  • POUs: Reusable software units such as functions, function blocks, and programs.
  • Tasks: Execution mechanisms that determine when programs or blocks run.
  • Languages: Standardized representations of control algorithms.

A PLC normally repeats a scan cycle. During a typical cycle, it reads physical inputs or updates their process image, executes applicable program logic, and writes output commands. Modern controllers may also use event tasks, periodic tasks, motion tasks, and communication tasks. The exact execution model is vendor-dependent, so engineers must consult the controller documentation when scan timing is safety-critical.

A simplified cyclic sequence is:

  1. Acquire input data.
  2. Execute scheduled POUs.
  3. Update outputs.
  4. Perform communications, diagnostics, and housekeeping.
  5. Begin the next cycle.

The scan model has important consequences. A contact in Ladder Diagram does not continuously monitor a sensor in the same way that an electrical relay does; it is evaluated when the relevant logic is executed. Similarly, a timer or counter is updated according to task execution and controller implementation.

1.1 Data Types and Tags

A tag is a meaningful symbolic name assigned to a variable. Tags should express engineering meaning rather than physical addresses. For example, Tank_Level_High is more informative than I0.3.

Common IEC-related data types include:

TypeTypical meaningExample
BOOLTrue or falsePump_RunCmd
SINT, INT, DINTSigned integerBatch_Count
USINT, UINT, UDINTUnsigned integerPart_Total
REAL, LREALFloating-point quantityTank_Level
TIMEDurationFill_Time
DATE, TIME_OF_DAYCalendar or clock valueShift_Start
STRINGCharacter sequenceRecipe_Name
ARRAYOrdered collectionTemperature_History
STRUCTGroup of related fieldsMotor_Status
ENUMNamed set of statesMachine_State

The required size, range, precision, and memory representation vary by platform. Engineers must avoid silently mixing incompatible data types. A temperature represented as a REAL should not be confused with a raw analog input represented as an integer count.

A tag convention may distinguish physical inputs, outputs, commands, statuses, alarms, parameters, and internal states. For example:

  • DI_EStop_OK: digital input
  • DO_Conveyor_Run: digital output
  • Cmd_Start: operator or supervisory command
  • Sts_Running: status indication
  • Alm_Overtemperature: alarm condition
  • Par_MaxSpeed: configurable parameter
  • Mem_FillComplete: internal memory bit

The exact convention may differ between organizations, but consistency is essential.

2. Program Organization Units

A POU is a defined software unit with a specific interface and execution behavior. The principal POUs are functions, function blocks, and programs.

2.1 Functions

A function accepts input values and returns a result. In the mathematical abstraction, a function is commonly represented as:

y = f(x₁, x₂, …, xₙ)

Here, x₁ through xₙ are input values, f is the defined operation, and y is the returned value. A pure function should not retain hidden operating state between calls. Given the same valid inputs, it should produce the same result.

Typical PLC functions include unit conversion, limit checking, scaling, Boolean combination, and engineering calculations. A function is appropriate for reusable stateless logic such as converting a raw analog value into a percentage.

A function should define behavior for invalid inputs. For example, a division function must specify what happens if the divisor is zero. In safety-related or production-critical code, error handling should be explicit rather than dependent on undocumented controller behavior.

2.2 Function Blocks

A function block (FB) combines algorithms with retained instance data. Each instance has its own memory. Examples include:

  • Motor control blocks
  • PID controllers
  • Valve sequencing blocks
  • Alarm managers
  • Timers and counters
  • Communication drivers

A motor function block may have inputs such as Start, Stop, Fault_Reset, and Permissive, and outputs such as Run_Command, Running, and Fault. Internally it may retain state, timing information, fault latches, and operating statistics.

If one function block type is instantiated three times for three motors, each instance must have independent state. This is a major distinction from a stateless function.

2.3 Programs

A program is a POU that organizes a major control application and is usually called by a task. It may invoke functions and function blocks. A program commonly represents a machine, production cell, or plant area.

A useful hierarchy is:

Task
 └── Program: PackagingCell
      ├── FB_Motor: Conveyor_1
      ├── FB_Motor: Conveyor_2
      ├── FB_Valve: Inlet_Valve
      ├── Function: Scale_Raw_Input
      └── Sequence: Filling_Sequence

This hierarchy separates scheduling from control responsibility. It also makes commissioning and troubleshooting more systematic.

3. Ladder Diagram

Ladder Diagram is a graphical language derived from relay logic. It represents logic through power rails, contacts, coils, function blocks, and network structures. The basic Boolean operations are visually intuitive:

  • Series contacts represent logical AND.
  • Parallel branches represent logical OR.
  • Normally closed contacts commonly represent logical NOT.
  • Coils assign values to outputs or internal variables.

For example, a motor command may require a start command, a safety permissive, and the absence of a fault. Conceptually:

Motor_Run := Start_Command AND Safety_OK AND NOT Motor_Fault

In Ladder Diagram, these conditions would normally appear as contacts in series followed by a coil.

3.1 Seal-In Logic

A traditional motor circuit may use a seal-in or holding contact. The command is energized by a start pushbutton and remains energized through an auxiliary contact until a stop condition opens the circuit. In PLC logic, this can be implemented using a feedback contact, but care is required. A software seal-in circuit must not bypass emergency stops, safety relays, or required interlocks.

A robust design separates:

  1. Operator request.
  2. Safety authorization.
  3. Process permissive.
  4. Equipment command.
  5. Actual equipment feedback.

A start request should not be interpreted as proof that the motor is running. Running status should come from feedback such as an auxiliary contact, drive status, or measured speed.

3.2 Strengths and Limitations

Ladder Diagram is especially effective for:

  • Discrete Boolean logic
  • Motor and valve interlocks
  • Maintenance-oriented diagnostics
  • Applications familiar to electricians
  • Direct representation of relay replacement logic

Its limitations include difficulty expressing complex calculations, large data structures, algorithmic iteration, and extensive state management. Overly large Ladder programs can become difficult to navigate and may encourage duplicated logic.

4. Function Block Diagram

Function Block Diagram represents control logic as interconnected blocks. Each block has inputs and outputs, and signal flow is shown graphically. FBD is particularly suitable for analog processing, control loops, reusable equipment blocks, and signal conditioning.

A temperature-control network might contain:

  1. An analog input block.
  2. A scaling block.
  3. A limit or alarm block.
  4. A PID block.
  5. An output-limiting block.
  6. An analog output block.

FBD makes data flow visible. However, the visual arrangement must not be mistaken for a complete execution specification. The controller’s rules for evaluating interconnected blocks, feedback paths, and task order remain important.

FBD is also useful for representing standard blocks such as TON timers, rising-edge detectors, counters, and PID controllers. Engineers should document the time base, parameter units, reset behavior, and output limitations of each block.

5. Structured Text

Structured Text is a high-level textual language resembling Pascal and other structured programming languages. It is well suited to arithmetic, loops, arrays, data structures, state machines, recipe handling, and complex conditions.

A conceptual Structured Text example is:

IF Safety_OK AND Start_Command AND NOT Fault_Active THEN
    Run_Command := TRUE;
ELSIF Stop_Command OR Fault_Active THEN
    Run_Command := FALSE;
END_IF;

The exact syntax varies slightly among IEC 61131-3 environments. Therefore, the manufacturer’s compiler rules must be followed.

Structured Text supports readable modularity when it is divided into short routines and meaningful blocks. Long unstructured sections can be harder for maintenance personnel to troubleshoot than equivalent Ladder logic. Comments should explain purpose, assumptions, units, and exceptional behavior rather than merely restating syntax.

5.1 Iteration and Bounds

Loops are useful for processing arrays, but they must be bounded. An unbounded or excessively long loop can prevent time-critical tasks from completing. For each loop, the programmer should verify:

  • The initial value.
  • The termination condition.
  • The increment or decrement.
  • The valid array index range.
  • The maximum execution time.

Structured Text is not automatically safer or more efficient than graphical languages. Good engineering depends on design, review, testing, and task scheduling.

6. Sequential Function Chart

Sequential Function Chart is intended for processes that proceed through steps and transitions. A chart consists of:

  • Steps: Stable process conditions or phases.
  • Actions: Operations associated with a step.
  • Transitions: Boolean conditions that permit movement to the next step.
  • Initial step: The starting state.
  • Alternative or parallel branches: Different or simultaneous paths.

A filling sequence may contain the following states:

  1. Idle
  2. Pre-check
  3. Open inlet valve
  4. Fill tank
  5. Close inlet valve
  6. Confirm level
  7. Transfer material
  8. Complete or fault

SFC is valuable because it expresses the process state explicitly. It prevents a common design error in which several unrelated conditions simultaneously attempt to control the same equipment.

A transition should be based on observable and validated conditions. For example, the transition from “Fill” to “Close Valve” might require a valid high-level signal and a maximum fill-time condition. A timeout should normally lead to a clearly defined fault step rather than silently advancing.

SFC often works best with other languages: SFC defines sequence, FBD defines analog control, LD defines interlocks, and ST implements data processing.

7. Selecting a Language

No single language is best for every task.

TaskSuitable primary languageReason
Relay-style interlockLDFamiliar Boolean representation
Analog signal processingFBDVisible signal flow
Mathematical or data processingSTCompact structured expressions
Machine sequenceSFCExplicit steps and transitions
Reusable equipment behaviorFB in LD, FBD, or STEncapsulation and instance memory

Language selection should consider the maintenance team, project standards, safety requirements, controller support, diagnostic needs, and future modifications. A mixed-language architecture is often superior to forcing the whole application into one notation.

8. Modular Programming and Interfaces

Modularity divides a system into units with clear responsibilities. A good module has:

  • One principal purpose.
  • A documented interface.
  • Limited dependence on global variables.
  • Predictable execution.
  • Defined fault behavior.
  • Testable inputs and outputs.

For example, a FB_Motor should manage motor command logic, interlocks, feedback monitoring, and motor-specific faults. It should not also calculate production reports, operate unrelated valves, or manipulate operator graphics directly.

An interface should distinguish input, output, and in-out data. Parameters should have meaningful names and units. A speed parameter should indicate whether it is expressed in revolutions per minute, hertz, percentage, or a raw drive count.

Global variables may be necessary for system-wide status, but excessive global access creates hidden coupling. Passing values through interfaces improves traceability and testing.

9. Coding Conventions and Documentation

A professional PLC standard normally defines:

  • Naming rules.
  • Indentation and formatting.
  • Comment requirements.
  • Data-type rules.
  • Alarm conventions.
  • Version identification.
  • Retentive-memory policy.
  • Error-handling requirements.
  • Use of constants and parameters.
  • Rules for forcing or overriding I/O.

Comments should answer questions such as: Why is this interlock required? What unit is used? What happens after a timeout? Is the value retained through a power cycle? Which document defines the safety requirement?

Magic numbers should be avoided. Instead of writing IF Level > 75.0, use a named parameter such as Par_HighLevel_Percent. This improves readability and allows controlled configuration.

The following practices are strongly recommended:

  1. Use one tag for one clearly defined purpose.
  2. Avoid writing to the same command variable from unrelated routines.
  3. Separate commands, statuses, alarms, and parameters.
  4. Keep routines short enough to review.
  5. Use explicit units in names or documentation.
  6. Avoid unnecessary type conversion.
  7. Initialize state variables deliberately.
  8. Document retentive data.
  9. Record every forced variable during commissioning and remove forces before production.
  10. Store source code and controller revisions under version control.

10. Worked Design Example: Automated Tank-Filling Cell

The following is an illustrative case.

Background

A small process cell fills a tank from an inlet valve and transfers the contents using a pump. The cell has a start command, stop command, emergency-stop status, high-level switch, low-level switch, pump feedback, valve feedback, and a maximum filling time.

Problem

A single block of relay-style logic has caused three difficulties:

  • The pump can be commanded without reliable level confirmation.
  • A failed valve may leave the filling operation waiting indefinitely.
  • Operators cannot easily determine whether the system is idle, filling, transferring, or faulted.

Analysis

The process has both discrete interlocks and sequential behavior. Therefore, a mixed-language solution is appropriate:

  • SFC for process states.
  • LD for emergency and equipment permissives.
  • FB for the pump and valve equipment modules.
  • ST for timeout calculations and diagnostic data.

Approach

The main states are:

StateActionTransition condition
IdleAll commands offStart and safety conditions valid
FillOpen inlet valveHigh level reached or timeout
SettleClose valve and verify closureValve closed or fault
TransferRun pumpLow level reached or timeout
CompleteStop pump and report cycle completeOperator reset
FaultStop equipment and record causeFault reset with safe conditions

The safety permissive is calculated independently of the sequence. Conceptually:

Safety_OK := EStop_OK AND Guard_Closed AND No_SafetyRelayFault

The fill command is then constrained by both sequence and safety:

Fill_Command := State_Fill AND Safety_OK AND NOT Fill_Fault

A timer is started when the Fill state becomes active. If the high-level signal does not arrive before the configured maximum time, the sequence enters Fault. The maximum time must be selected from the process design and validated during commissioning; it should not be an arbitrary programming value.

The pump block receives Run_Request, Safety_OK, and Permissive. It returns Run_Command, Running, and Fault. The program should distinguish a command from confirmation. If Run_Command is true but Running remains false beyond a feedback delay, a pump-start fault is generated.

Outcome

The modular design makes the machine state visible to operators, limits unsafe command paths, and allows the pump block to be reused in another cell. A technician can test the pump module independently from the filling sequence. A timeout produces a defined diagnostic rather than an unexplained halt.

Learning Points

  1. Sequence logic and equipment logic should not be confused.
  2. Commands are not equivalent to feedback.
  3. Timeouts require process-based engineering justification.
  4. SFC, LD, ST, and FBs can complement one another.
  5. Clear states improve diagnostics and maintainability.

11. Testing, Commissioning, and Validation

PLC testing should progress from small units to the complete system.

Unit Testing

Test functions and function blocks with normal, boundary, and invalid inputs. For a level-limit function, test values below, at, and above each limit. Verify behavior when sensors are unavailable or contradictory.

Integration Testing

Test interactions among modules. For example, verify that a sequence cannot start the pump when the pump block reports a fault, and that a safety loss removes the equipment command as designed.

Simulation and Hardware-in-the-Loop

Simulation can test sequence transitions without operating physical machinery. Hardware-in-the-loop testing may connect the real controller to simulated sensors and actuators. These methods reduce commissioning risk but cannot replace physical verification of wiring, safety circuits, sensor installation, and machine behavior.

Commissioning Controls

Forcing an input or output can be useful, but it is hazardous if not controlled. A force should be authorized, recorded, time-limited, clearly displayed, and removed after testing. Safety functions must be validated according to the applicable machinery and functional-safety requirements. Standard PLC logic should not be treated as a substitute for a certified safety system where one is required.

12. Limitations, Governance, and Contemporary Practice

IEC 61131-3 improves portability and communication, but complete portability is not guaranteed. Vendor libraries, motion instructions, networking features, data representations, task models, and safety extensions may differ. Engineers should document platform-specific dependencies.

Industrial control code is also a cybersecurity asset. Access control, authenticated engineering workstations, backups, change approval, secure remote access, and audit trails are essential. A well-written program can still create risk if unauthorized users can alter it.

Modern automation projects increasingly combine PLCs with supervisory systems, industrial networks, edge devices, and data platforms. Artificial intelligence may assist with code search, documentation, anomaly detection, or predictive maintenance, but generated code must be reviewed, tested, and validated by competent engineers. AI output should never bypass safety analysis, functional testing, or change-control procedures.

A mature engineering organization treats PLC software as a controlled product. Requirements, design decisions, source code, test records, I/O lists, alarm databases, and backups should be traceable. Changes should be reviewed for effects on safety, production, cybersecurity, and maintenance.

Chapter Summary

IEC 61131-3 provides a structured foundation for PLC programming through standardized languages, variables, data types, and program organization units. Ladder Diagram is effective for relay-like Boolean logic and maintenance diagnostics. Function Block Diagram provides clear signal-flow representation for analog and reusable control blocks. Structured Text supports calculations, arrays, data structures, and algorithmic processing. Sequential Function Chart expresses machines as explicit steps, actions, and transitions.

Functions are generally stateless and return results, while function blocks retain instance-specific data. Programs organize major control applications and are executed by tasks. Tags, interfaces, naming conventions, comments, and modular boundaries are central to maintainability. Professional PLC development also requires unit testing, integration testing, controlled commissioning, version management, cybersecurity, and safety validation. A mixed-language architecture is often the most effective solution because different languages express different aspects of industrial control clearly.

Key Terms

IEC 61131-3: International standard describing PLC programming concepts and languages.

Tag: Symbolic name assigned to a variable.

Variable: Data object whose value may be read or changed.

Data type: Definition of the kind, range, and representation of a value.

Program Organization Unit (POU): Structured software unit such as a function, function block, or program.

Function: Usually stateless POU that returns a result from its inputs.

Function block: POU containing algorithms and retained instance data.

Program: POU that organizes an application and is called by a task.

Task: Scheduling mechanism that determines when software executes.

Ladder Diagram: Graphical PLC language based on relay and Boolean logic.

Function Block Diagram: Graphical language based on interconnected functional blocks.

Structured Text: High-level textual PLC programming language.

Sequential Function Chart: Language for representing steps, actions, and transitions.

Interlock: Condition that prevents an operation unless required criteria are satisfied.

Permissive: Condition authorizing an operation to proceed.

Retentive variable: Variable whose value can survive a defined restart or power interruption.

Scan cycle: Repeated controller sequence involving input processing, program execution, and output updating.

Tag convention: Agreed system for naming and classifying variables.

Modularity: Division of software into independent, reusable units with defined interfaces.

Force: Temporary override of an input, output, or variable during testing.

Review Questions

Short Answer Questions

  1. What is the purpose of IEC 61131-3 in PLC engineering?
  2. Define a tag and explain why symbolic tags are preferable to raw addresses.
  3. State one important difference between a function and a function block.
  4. What are the principal elements of a Sequential Function Chart?
  5. Why should a PLC program distinguish an equipment command from equipment feedback?

Long Answer Questions

  1. Compare Ladder Diagram, Function Block Diagram, Structured Text, and Sequential Function Chart in terms of representation, strengths, and limitations.
  2. Explain how programs, tasks, functions, and function blocks can be organized in a modular PLC application.
  3. Discuss the importance of naming conventions, data types, comments, and version control in industrial automation software.
  4. Describe a systematic testing and commissioning strategy for a PLC-controlled machine.
  5. Explain why safety, cybersecurity, and change management are part of professional PLC programming.

Analytical / Application Questions

  1. Design a language and POU architecture for a conveyor system containing two motors, a barcode reader, a reject cylinder, and an operator-selected production recipe. Justify each language choice.
  2. A tank-filling sequence sometimes remains active after the high-level switch fails. Analyze the likely design weakness and propose a modular fault-handling strategy.
  3. Develop the states, actions, transitions, commands, and feedback signals for a three-stage batch process. Explain how you would prevent conflicting commands and diagnose timeout faults.

Multiple Choice Questions with Answers

Question 1

Which IEC 61131-3 language is most directly suited to representing a sequence of machine states and transitions?

A. Sequential Function Chart

B. Structured Text

C. Function Block Diagram

D. Ladder Diagram

Correct Answer: A. Sequential Function Chart

Question 2

What is the defining characteristic of a function block compared with a typical function?

A. It can only process Boolean values

B. It retains instance-specific data

C. It cannot have outputs

D. It must be written in Ladder Diagram

Correct Answer: B. It retains instance-specific data

Question 3

Which tag is the most meaningful symbolic name for a digital input?

A. I0.3

B. Bit_3

C. DI_EStop_OK

D. Input_Value

Correct Answer: C. DI_EStop_OK

Question 4

Which language is generally most suitable for array processing and complex arithmetic?

A. Ladder Diagram

B. Structured Text

C. Sequential Function Chart

D. Function Block Diagram only

Correct Answer: B. Structured Text

Question 5

In a PLC application, what is the primary purpose of a task?

A. To define the physical wiring

B. To schedule software execution

C. To replace all function blocks

D. To store only analog values

Correct Answer: B. To schedule software execution

Question 6

Why should an equipment command be distinguished from equipment feedback?

A. A command proves that the equipment is operating

B. Feedback is used only for screen colors

C. A command requests operation, while feedback confirms actual behavior

D. Commands and feedback must always have identical names

Correct Answer: C. A command requests operation, while feedback confirms actual behavior

Question 7

Which design is most appropriate for a reusable motor-control module with retained fault and timing information?

A. A function block

B. A single constant

C. A raw input address

D. A comment only

Correct Answer: A. A function block

Question 8

What is a major risk of an unbounded loop in Structured Text?

A. It can prevent a time-critical task from completing

B. It automatically improves scan performance

C. It converts all variables to Boolean values

D. It disables all physical inputs permanently

Correct Answer: A. It can prevent a time-critical task from completing

Question 9

In Sequential Function Chart, what normally permits movement from one step to another?

A. A transition condition

B. A tag name

C. A version number

D. A physical output address

Correct Answer: A. A transition condition

Question 10

Which practice best supports maintainable PLC software?

A. Using unexplained numeric constants throughout the code

B. Writing unrelated equipment commands from many routines

C. Using meaningful tags, defined interfaces, and documented units

D. Leaving test forces enabled after commissioning

Correct Answer: C. Using meaningful tags, defined interfaces, and documented units

Industrial Automation & PLC
Chapter 5 of 15