Chapter 5
Programmable Logic Controllers and IEC 61131-3 Programming
Bachelor Program in Mechatronics Engineering
Industrial Automation
•
Bachelor
Programmable Logic Controllers and IEC 61131-3 Programming
Introduction
A programmable logic controller (PLC) is an industrial computer designed to monitor inputs, execute a control program, and command outputs in real time. PLCs are central to mechatronic systems because they connect sensors, actuators, drives, robots, safety devices, and supervisory systems while providing deterministic and maintainable control.
Unlike general-purpose computers, PLCs are designed for electrical noise, vibration, temperature variation, continuous operation, and straightforward maintenance by plant personnel. Their programming environments support languages standardized by IEC 61131-3, including ladder diagram (LD), function block diagram (FBD), structured text (ST), and sequential function chart (SFC).
This chapter develops the practical and theoretical foundations needed to configure PLC hardware and I/O, write IEC 61131-3 programs, implement interlocks and sequences, and test and diagnose automated equipment.
Learning Objectives
By the end of this chapter, the reader should be able to:
Explain PLC architecture, scan-cycle operation, and memory organization.
Select and configure CPUs, power supplies, communication modules, and I/O.
Distinguish sinking and sourcing digital circuits and correctly interface field devices.
Develop equivalent control logic in LD, FBD, ST, and SFC.
Design permissives, interlocks, alarms, sequencing, and fault recovery.
Apply simulation, commissioning, forcing, and diagnostic methods safely.
Evaluate PLC solutions in relation to safety, cybersecurity, maintainability, and standards.
1. PLC Architecture and Operating Model
A PLC system normally consists of a power supply, central processing unit (CPU), input and output modules, communication interfaces, programming software, and field wiring. The CPU stores the user program and data, executes instructions, communicates with devices, and supervises faults.
PLC control architecture showing field devices, input modules, CPU, output modules and actuators
Figure: PLC control architecture showing field devices, input modules, CPU, output modules and actuators
Figure: Basic PLC control architecture and feedback path.
1.1 The scan cycle
A conventional PLC repeatedly performs the following activities:
Read physical inputs into an input image table.
Execute the user program using the stored input values and internal data.
Transfer output image values to physical output modules.
Perform communications, diagnostics, and housekeeping.
The time required for one complete cycle is the scan time. The exact order differs among manufacturers, and some systems update selected I/O asynchronously. Therefore, the programmer must consult the controller documentation when timing is critical.
If an input changes immediately after the input update, the program may not recognize it until the next scan. A short pulse can therefore be missed. High-speed counters, interrupt inputs, event tasks, or dedicated motion modules are used when ordinary cyclic scanning is inadequate.
A timer implemented in software is also affected by task execution and clock resolution. A timer should therefore be treated as an approximate process delay unless the PLC specification guarantees a particular timing behavior.
1.2 Memory and data types
Typical PLC data include:
Data type
Typical use
BOOL
Binary states, commands, alarms
INT / DINT
Counts and signed integer values
UINT / UDINT
Non-negative counts and addresses
REAL
Scaled measurements and calculations
TIME
Delays and durations
STRING
Messages and identifiers
Arrays and structures
Recipes, status records, device data
Good designs separate physical I/O from logical variables. For example, I_Start_PB may represent a physical pushbutton, while Cmd_Start represents a validated command. This separation makes simulation, maintenance, and later hardware changes easier.
2. Hardware and I/O Configuration
2.1 Selecting the controller
Selection begins with the process requirements rather than with a preferred brand. Important criteria include:
number and type of digital and analog points;
required scan time and task structure;
memory capacity and program complexity;
motion, high-speed counting, and PID requirements;
communication protocols and network topology;
environmental rating and temperature range;
safety-controller requirements;
expansion capacity and lifecycle support.
A design should include spare I/O, commonly 10–20% depending on project policy and expected expansion. Spare capacity is not a substitute for correct electrical design: voltage, current, isolation, and short-circuit protection must still be verified.
2.2 Digital inputs and outputs
Digital inputs accept two-state signals such as 24 V DC sensors, limit switches, and selector switches. Digital outputs control solenoid valves, contactor coils, lamps, and relay interfaces. Outputs may be transistor, relay, or triac types. Each has different switching speed, leakage current, load compatibility, and protection requirements.
In a sourcing arrangement, the output device supplies positive voltage to the load; in a sinking arrangement, it provides the return path to 0 V. The sensor and input module must use compatible conventions. A wiring error can produce apparently inverted logic or prevent the input from changing.
Inductive loads such as relays and solenoids generate voltage transients when switched off. Suppression devices—flyback diodes for suitable DC coils, RC networks or varistors for AC loads—reduce contact wear and electrical interference. The suppression method must be compatible with the load and switching device.
2.3 Analog I/O
Analog modules represent physical quantities such as pressure, temperature, speed, or position. Common signals include 0–10 V and 4–20 mA. Current loops are often preferred in industrial environments because they are less sensitive to voltage drop and can identify a broken wire when a live-zero convention is used.
For a linear sensor, engineering value may be obtained by interpolation:
Here, x is the measured raw input, x_min and x_max are the calibrated input limits, and y is the engineering value between y_min and y_max. The equation assumes a linear sensor and correctly calibrated limits. Units of x must be consistent, while y has the engineering units of the process variable.
For a 4–20 mA pressure transmitter ranged 0–10 bar, a measured 12 mA gives:
p = 0 + (12 - 4)(10 - 0)/(20 - 4) = 5 bar
The result is valid only if the signal is within its configured range and the transmitter is linear. Values below the live-zero threshold may indicate a wiring or transmitter fault rather than negative pressure.
Analog resolution is determined by the module’s converter. Quantization introduces a small error, and accuracy is also affected by module specifications, wiring, grounding, sensor accuracy, and environmental noise. Shielding and correct grounding practices must follow the manufacturer’s instructions; shields should not be casually connected at multiple points.
2.4 Addressing and tag conventions
Physical addresses vary by platform. Symbolic tags are preferable because they express meaning and reduce dependence on terminal locations. A useful convention includes prefixes such as:
DI_ and AI_ for physical inputs;
DO_ and AO_ for physical outputs;
Cmd_ for commands;
Sts_ for status;
Perm_ for permissives;
Alm_ for alarms;
SP_ and PV_ for setpoint and process value.
Every I/O point should have a documented terminal, signal type, normal state, electrical rating, and field-device description.
3. IEC 61131-3 Programming Languages
IEC 61131-3 provides a common conceptual framework for PLC programming. Implementations differ, so portability is not guaranteed at the software-project level. The standard supports multiple languages because different control tasks benefit from different representations.
3.1 Ladder diagram
Ladder diagram resembles relay-control schematics. Contacts represent Boolean conditions, and coils represent assignments. It is effective for interlocks, motor starters, alarms, and maintenance troubleshooting.
A motor command can be described logically as:
MotorRun = Start ∧ ¬Stop ∧ Permissive ∨ SealIn
The intended precedence must be made explicit in the actual program. A safer structured interpretation is:
This represents a seal-in circuit, but a PLC implementation should avoid ambiguous self-references and should define reset behavior clearly. Emergency-stop and safety functions should not depend solely on ordinary ladder logic.
3.2 Function block diagram
FBD connects graphical blocks such as AND, OR, timers, counters, comparisons, and controllers. It is especially readable for signal conditioning and function composition. A start/stop function may use AND, OR, and NOT blocks, while a motor-control function block can encapsulate commands, feedback, timeout, and fault status.
Reusable function blocks improve consistency. For example, a MotorFB may have inputs StartCmd, StopCmd, Permissive, Feedback, and Reset, and outputs RunOutput, Running, and Fault. The block should document whether a feedback timeout is enabled and how faults are latched.
3.3 Structured text
Structured text is a high-level language suitable for calculations, arrays, state machines, data handling, and complex conditions. A conceptual motor routine is:
IF Reset THEN
Fault := FALSE;
END_IF;
IF NOT Permissive OR StopCmd THEN
RunOutput := FALSE;
ELSIF StartCmd AND NOT Fault THEN
RunOutput := TRUE;
END_IF;
IF RunOutput AND NOT Feedback THEN
StartTimer(IN := TRUE, PT := T#3s);
ELSE
StartTimer(IN := FALSE);
END_IF;
IF StartTimer.Q THEN
Fault := TRUE;
RunOutput := FALSE;
END_IF;
This is illustrative IEC-style pseudocode; timer invocation and retentive behavior vary by platform. A complete implementation must specify initialization, task execution, and the behavior when commands disappear.
3.4 Sequential function chart
SFC represents a process as steps, transitions, and actions. A step describes a state such as Idle, Clamp, Drill, or Unload; a transition describes the condition for moving to the next state. SFC is valuable when order, waiting conditions, and recovery paths are central.
A sequence should define what happens if a transition never becomes true. Timeouts, operator reset, fault steps, and safe outputs prevent a machine from remaining indefinitely in an unexplained state.
4. Interlocks, Permissives, and Safety
A permissive is a condition that must be true before an action is allowed. An interlock prevents an unsafe or conflicting action. For a conveyor motor, permissives might include guard closed, downstream available, air pressure adequate, and no active fault.
The distinction is important:
A permissive authorizes starting.
A run interlock may stop an already-running device.
An alarm informs an operator.
A safety function brings equipment to a defined safe state.
Safety-related functions require appropriate risk assessment, architecture, validation, and certified devices. A standard PLC may monitor a safety signal, but it is not automatically a safety controller. Emergency stops, guard switches, and safety light curtains commonly use safety relays or safety PLCs designed for the required performance level or safety integrity level.
Interlocks should be fail-safe where practicable. For example, a normally closed stop circuit provides a de-energize-to-trip behavior, although final design depends on the risk assessment. Software should also detect discrepancies such as a commanded motor with no feedback, or a cylinder reported extended and retracted simultaneously.
5. Sequencing and State-Based Design
State-based design is often clearer than a large collection of independent coils. A state machine contains:
a finite set of operating states;
permitted transitions;
actions associated with each state;
defined fault and recovery behavior.
For a pick-and-place unit, states may be Idle, Extend, Grip, Retract, Place, and Fault. Only the outputs appropriate to the active state should be enabled. A transition from Extend to Grip may require the extend sensor, while a timeout moves the system to Fault.
A robust sequence includes:
initialization and homing;
validation of sensors before motion;
mutually exclusive actuator commands;
confirmation of completed motion;
timeout supervision;
safe response to loss of air, power, or communication;
operator-visible status and reset rules.
Timers must be selected according to process tolerance. A timeout should exceed normal movement time but remain short enough to detect a genuine fault. The value should be justified by measured performance, not chosen arbitrarily.
6. Diagnostics and Testing
Testing progresses from low-risk evidence to live operation:
Static review: check tags, addresses, data types, comments, and unreachable logic.
Unit testing: test function blocks with simulated inputs and expected outputs.
Integration testing: connect PLC logic to I/O simulators, drives, and networks.
Factory acceptance testing: verify sequences and fault responses before shipment.
Site acceptance testing: confirm field wiring, device direction, safety circuits, and production conditions.
A test specification should state the initial condition, stimulus, expected result, acceptance criterion, and recorded evidence. Testing only the normal cycle is inadequate. Tests should include sensor failure, feedback loss, contradictory signals, communication loss, power restoration, operator reset, and attempts to start with each permissive absent.
Forcing an input or output can assist commissioning but is hazardous. A force overrides normal logic and may cause unexpected movement. Forces must be authorized, documented, visibly identified, removed after use, and verified before automatic operation.
Useful diagnostic features include:
first-out fault indication;
alarm timestamps;
sequence step and transition status;
I/O health and communication status;
device runtime and start counters;
maintenance warnings;
event logs and controller diagnostics.
A diagnostic message should identify the equipment, condition, probable cause, and recommended action. “Fault 17” is less useful than “Conveyor 2: run command present, feedback absent for 3 s; check overload, contactor, and sensor.”
7. Applied Case: Automated Pallet Transfer Cell
Background
The following is an illustrative case. A pallet-transfer cell moves a pallet onto a conveyor, clamps it, transfers it to a second conveyor, and releases it. The cell contains photoelectric sensors, clamp cylinders, a motor-driven conveyor, solenoid valves, a safety gate, and a PLC.
Problem
An initial implementation used separate ladder rungs for each actuator. During testing, the clamp sometimes remained energized after a sequence interruption, and a failed photoelectric sensor caused the sequence to wait indefinitely. Operators also lacked clear information about whether the machine was waiting, faulted, or ready.
Analysis
The process requires mutually exclusive states and confirmation of each physical action. The design team identified these signals:
This Boolean expression assumes that each signal has already been validated and that safety functions are implemented in the appropriate safety system.
Approach and solution
The sequence was redesigned as an SFC/state machine:
Idle: all actuators off; wait for Pallet_In.
Clamp: energize clamp extension; transition when Clamp_Ext is true.
Transfer: start conveyor; transition when the destination sensor is active.
Release: retract clamp; transition when Clamp_Ret is true.
Return: stop conveyor and return to Idle.
Fault: remove motion commands, retain the fault code, and await a defined reset.
Each movement received a timeout. For example, if the clamp did not extend within the permitted period, the system entered Fault and recorded “Clamp extension timeout.” The output commands were generated from the active state rather than from multiple independent memory coils.
The HMI displayed the current state, active permissive, timer progress, and first fault. A simulation test verified normal operation and injected sensor failures. On the physical cell, technicians first tested at reduced speed and with safe clearance.
Outcome
The revised design prevented simultaneous clamp commands, identified failed sensors, and made recovery predictable. Maintenance staff could distinguish a missing pallet from a clamp fault without examining raw ladder logic.
Learning points
The case demonstrates that PLC programming is not merely the translation of a process description into contacts and coils. Reliable automation depends on state modeling, validated feedback, explicit fault behavior, safe hardware, and documentation that supports future maintenance.
8. Engineering Practice, Cybersecurity, and Contemporary Developments
PLC projects should use version control, approved backups, change records, and controlled access. Default passwords should be changed, unused services disabled, and programming ports protected. Network segmentation separates control systems from business networks, while authenticated remote access reduces exposure. Cybersecurity should not be treated as an afterthought because unauthorized logic changes can create physical hazards.
Modern PLCs increasingly support OPC UA, industrial Ethernet, edge computing, digital twins, condition monitoring, and data collection for predictive maintenance. Artificial intelligence can assist anomaly detection or maintenance prioritization, but an AI recommendation should not directly bypass deterministic interlocks or safety logic. Training data, false alarms, explainability, and responsibility for decisions must be considered.
Professional practice also requires compliance with applicable electrical, machinery, functional-safety, EMC, and cybersecurity standards. IEC 61131-3 addresses programming languages and software structure; it does not by itself certify that a machine is safe. Standards, legislation, and site procedures must be interpreted for the jurisdiction and application.
Chapter Summary
PLCs are industrial computers that cyclically read inputs, execute programs, update outputs, and perform diagnostics. Correct system design requires coordinated selection of CPU, I/O, power, communications, environmental protection, and field wiring. Digital circuits must account for sourcing, sinking, load types, suppression, and fail-safe behavior. Analog signals require correct scaling, calibration, units, and fault interpretation.
IEC 61131-3 languages serve different purposes: LD is effective for relay-like logic, FBD for connected function networks, ST for calculations and data processing, and SFC for sequences and state transitions. Reliable programs use symbolic tags, clear permissives, interlocks, feedback supervision, timeouts, alarms, and defined recovery states. Safety functions require appropriate safety hardware and validation rather than reliance on ordinary PLC logic alone.
Testing should proceed through review, simulation, integration, factory testing, and site acceptance. Diagnostic design, cybersecurity, version control, and documentation are essential professional responsibilities. State-based design is particularly valuable for mechatronic cells in which actions must occur in a controlled order and faults must be recoverable.
Key Terms
PLC: Industrial computer designed for deterministic monitoring and control.
CPU: Central processing unit that executes the PLC program and manages data.
Scan cycle: Repeated process of reading inputs, executing logic, updating outputs, and performing housekeeping.
Input image table: Memory representation of input states used during program execution.
Digital input: Binary field signal interpreted as on or off.
Analog input: Continuously varying electrical signal representing a process quantity.
Sourcing: Circuit arrangement in which a device supplies positive voltage to a load.
Sinking: Circuit arrangement in which a device provides the return path to zero volts.
Permissive: Condition that must be true before an action is allowed.
Interlock: Condition that prevents or stops an unsafe or conflicting action.
Ladder diagram: Graphical IEC programming language resembling relay logic.
Function block diagram: Graphical language connecting reusable logical and functional blocks.
Structured text: Text-based IEC language for algorithms, calculations, and data handling.
Sequential function chart: State-and-transition language for sequential processes.
Retentive variable: Variable whose value is preserved through defined power or restart events.
Feedback: Signal confirming the actual response of equipment.
Timeout: Maximum permitted duration for an expected operation.
Force: Commissioning override applied to an input or output.
First-out fault: Initial fault recorded when several subsequent symptoms occur.
Safety PLC: Controller designed and certified for specified safety-related functions.
Review Questions
Short Answer Questions
What are the principal stages of a conventional PLC scan cycle?
Distinguish a permissive from an interlock.
Why can a conventional PLC miss a short input pulse?
State one suitable application for each of LD, FBD, ST, and SFC.
Why are feedback signals important in actuator control?
Long Answer Questions
Explain PLC architecture and discuss how CPU, I/O, communications, and power-supply selection affect system performance.
Compare sourcing and sinking digital circuits, including wiring compatibility and typical failure considerations.
Explain how a 4–20 mA signal is scaled into engineering units and discuss sources of analog measurement error.
Describe a systematic testing strategy from program review through site acceptance testing.
Explain why safety functions should not depend solely on ordinary PLC program logic.
Analytical / Application Questions
Design the states, transitions, permissives, feedback signals, and timeout responses for a pneumatic pick-and-place mechanism.
A motor receives a run command but its feedback remains false. Propose a diagnostic sequence that distinguishes a wiring fault, overload trip, failed sensor, and mechanical jam.
Develop a PLC architecture for a small conveyor cell with eight digital inputs, six digital outputs, two analog inputs, an HMI, and a safety gate. Justify I/O types, tags, interlocks, testing methods, and cybersecurity controls.
Multiple Choice Questions with Answers
Question 1
Which activity normally occurs first in a conventional PLC scan cycle?
A. Updating physical outputs
B. Reading inputs into the input image
C. Executing communications diagnostics
D. Resetting all timers
Correct Answer: B. Reading inputs into the input image
Question 2
A 4–20 mA transmitter is ranged from 0 to 10 bar. What pressure corresponds to 12 mA?
A. 2.5 bar
B. 4 bar
C. 5 bar
D. 8 bar
Correct Answer: C. 5 bar
Question 3
Which IEC 61131-3 language is generally most suitable for array processing and complex calculations?
A. Structured text
B. Ladder diagram
C. Sequential function chart
D. Wiring diagram
Correct Answer: A. Structured text
Question 4
What is the principal purpose of a permissive?
A. To record historical alarms
B. To authorize an action only when required conditions are true
C. To increase analog resolution
D. To replace a safety relay in every application
Correct Answer: B. To authorize an action only when required conditions are true
Question 5
Why is feedback supervision used for a motor command?
A. To confirm that the commanded physical action occurred
B. To reduce the PLC memory size
C. To eliminate the need for overload protection
D. To convert AC voltage into a digital signal
Correct Answer: A. To confirm that the commanded physical action occurred
Question 6
Which design is most appropriate for a process with clearly ordered operating stages?
A. A state-based sequence or SFC
B. Only independent output coils
C. An analog scaling block alone
D. A communication cable without a program
Correct Answer: A. A state-based sequence or SFC
Question 7
What is a major hazard of forcing a PLC output during commissioning?
A. It permanently increases scan time
B. It overrides normal logic and may cause unexpected movement
C. It converts all inputs to analog values
D. It automatically validates the safety circuit
Correct Answer: B. It overrides normal logic and may cause unexpected movement
Question 8
Which device is normally selected for certified safety-related control functions?
A. An uncertified general-purpose timer
B. A standard HMI screen
C. A safety relay or safety PLC appropriate to the risk
D. A spreadsheet running on an office computer
Correct Answer: C. A safety relay or safety PLC appropriate to the risk
Question 9
For an inductive DC solenoid, which suppression device is commonly appropriate when polarity and voltage are suitable?
A. Flyback diode
B. Thermocouple
C. Photoelectric receiver
D. Fuse with no switching protection
Correct Answer: A. Flyback diode
Question 10
Which practice best supports PLC maintainability?
A. Using undocumented absolute addresses everywhere
B. Removing all diagnostics to simplify the program
C. Using meaningful symbolic tags, version control, and documented tests
D. Allowing unrestricted remote programming access
Correct Answer: C. Using meaningful symbolic tags, version control, and documented tests