Chapter 7
PLC Programming and Sequential Automation
Bachelors Program in Mechnical Engineering
Mechatronics & Industrial Automation
•
Bachelor
PLC Programming and Sequential Automation
Introduction and Context
Programmable logic controllers (PLCs) are industrial computers designed to monitor inputs, execute a control program, and command outputs in real time. They replaced much hard-wired relay logic because programs can be modified, diagnosed, documented, and reused with substantially less wiring. PLCs are central to packaging machines, conveyors, machine tools, process plants, robotic cells, and building automation.
Sequential automation concerns systems whose actions occur in a defined order. A filling machine, for example, may clamp a container, open a valve, wait until a level is reached, close the valve, release the container, and report completion. Correct operation depends not only on individual outputs but also on timing, conditions, interlocks, fault handling, and recovery after interruption.
This chapter develops the hardware, programming methods, and engineering practices required to design such systems using IEC 61131-3 languages. The emphasis is on ladder diagram (LD), function block diagram (FBD), and structured text (ST), supported by timers, counters, interlocks, and state-machine methods.
Learning Objectives
After studying this chapter, the reader should be able to:
Identify the principal components and signal types of a PLC system.
Explain the PLC scan cycle and its effect on control behavior.
Configure addressing, input/output modules, and basic communications.
Develop IEC 61131-3 programs using LD, FBD, and ST.
Apply timers, counters, latching logic, interlocks, permissives, and fault logic.
Design a sequential controller using states and transitions.
Test, commission, and troubleshoot a PLC-controlled machine safely.
Evaluate reliability, cybersecurity, safety, and maintainability implications.
1. PLC Architecture and Operation
A PLC system normally contains a power supply, central processing unit (CPU), memory, input modules, output modules, communication interfaces, programming software, and a field device network. Inputs may be push-buttons, proximity sensors, limit switches, encoders, pressure switches, or analog transmitters. Outputs may operate contactors, solenoid valves, relays, indicator lamps, variable-speed drives, and servo systems.
1.1 Discrete and analog signals
A discrete signal has a finite set of states, commonly 0 and 1. A 24 V DC sensor may be represented as TRUE when energized and FALSE when de-energized. Analog signals vary continuously within a range. Typical standards include 0–10 V and 4–20 mA. A transmitter range must be scaled in software. For a linear transmitter,
y = ymin + (x - xmin) (ymax - ymin)/(xmax - xmin)
where x is the measured input, x_min and x_max are the electrical input limits, and y_min and y_max are the engineering-unit limits. The equation assumes a linear sensor and correct calibration. For a 4–20 mA pressure transmitter ranging from 0 to 10 bar, a 12 mA signal gives y = 0 + (12 − 4)(10)/(20 − 4) = 5 bar.
1.2 PLC scan cycle
In a conventional cyclic PLC, the CPU generally:
Reads physical inputs into an input image table.
Executes the user program from beginning to end.
Updates physical outputs from the output image table.
Performs diagnostics and communications before beginning the next scan.
The scan time is the interval required for one complete cycle. If a sensor changes after its input has been read, the program may not recognize it until the next scan. A fast event can therefore be missed unless a high-speed input, interrupt, latch, or hardware counter is used. Output commands may also be delayed by the scan and output-module response time.
The normal scan-cycle model is useful for design, but it is not universal. Some PLCs use tasks with different priorities, event-triggered execution, or distributed I/O updates. Timing-critical specifications must therefore be checked against the selected PLC's documentation.
1.3 Memory and addressing
A PLC commonly stores Boolean variables, integers, real numbers, timers, counters, arrays, structures, and diagnostic data. Modern systems favor symbolic tags such as Conveyor_Run_Command over physical addresses such as %Q0.0. Symbolic programming improves readability and permits hardware changes with fewer program edits.
A sound tag convention identifies purpose and signal type. For example:
Tag
Type
Meaning
Start_PB
BOOL
Start push-button input
Guard_Closed
BOOL
Guard safety-status input
Part_Present
BOOL
Workpiece sensor
Motor_Run
BOOL
Motor command
Fill_Timer
TON
Filling timer instance
Part_Count
DINT
Completed-part count
Pressure_bar
REAL
Scaled pressure value
2. IEC 61131-3 Programming Languages
IEC 61131-3 defines programming languages and common concepts for programmable controllers. The principal languages relevant here are ladder diagram, function block diagram, structured text, sequential function chart, and instruction-list concepts in older systems. Vendor implementations vary, so portability is improved by using standard data types, clear interfaces, and limited dependence on proprietary instructions.
2.1 Ladder diagram
Ladder logic represents Boolean relationships using contacts, coils, set/reset elements, timers, counters, and function blocks. A normally open contact is TRUE when its associated variable is TRUE; a normally closed contact is TRUE when its associated variable is FALSE. A coil writes the result of a rung to an output or internal variable.
A basic motor-start circuit uses a start command in parallel with a holding contact and places stop and safety conditions in series:
Ladder logic motor start and seal-in circuit
Figure: Ladder logic motor start and seal-in circuit
Figure: A conceptual ladder seal-in circuit. Safety and stop conditions are placed in series; start and the motor's holding contact are parallel branches.
The seal-in circuit must not be treated as a substitute for a safety-rated emergency-stop system. Emergency stops, guard switches, and hazardous-motion removal normally require safety relays or safety PLC functions designed to the applicable machinery-safety standards.
2.2 Function block diagram
FBD represents logic as interconnected blocks. It is effective for analog processing, motor starters, PID controllers, mathematical functions, and reusable control blocks. A timer block may receive an enable signal and preset time and provide elapsed time and completion outputs. FBD makes signal flow visible, but excessive crossovers or poorly named intermediate signals can reduce readability.
2.3 Structured text
ST is a high-level textual language suited to calculations, loops, arrays, data structures, and state machines. A typical start/stop command can be written as:
IF NOT Stop_OK OR NOT Guard_OK THEN
Motor_Run := FALSE;
ELSIF Start_PB OR Motor_Run THEN
Motor_Run := TRUE;
END_IF;
This example assumes Stop_OK and Guard_OK are TRUE during normal operation. It demonstrates a dominant stop condition, but the actual safety function must be implemented in appropriately rated hardware or safety software.
3. Timers, Counters, and Edge Detection
3.1 Timers
The IEC timer-on-delay function block, TON, sets its output Q TRUE after the input IN remains TRUE for the preset time PT. The elapsed time is represented by ET. If IN becomes FALSE, a standard TON resets Q and ET. A TOF off-delay maintains its output for a specified period after its input becomes FALSE. A TP pulse timer generates a pulse of defined duration when triggered.
Timer behavior depends on the PLC runtime and task period. A preset of 2 s does not guarantee a physical response exactly at 2.000 s; scan period, task scheduling, clock resolution, and output delay introduce error. Timers should not be used for safety-critical stopping where certified safety timing is required.
3.2 Counters
An up-counter increments on a rising edge of its count input until its preset value is reached. Counters must receive pulses rather than a continuously TRUE signal, unless the function block itself performs edge detection. A reset condition should be explicit. Retentive counting and behavior after power loss must be specified.
3.3 Rising-edge detection
A rising-edge detector produces a one-cycle pulse when a Boolean signal changes from FALSE to TRUE. Conceptually,
RisingEdge(x) = x ∧ ¬xprevious
where x is the current value and x_previous is the value stored from the previous execution. The expression is valid only when the previous value is updated after evaluation and the task executes reliably. Edge detection prevents a held push-button or sensor from repeatedly incrementing a count.
4. Interlocks, Permissives, and Latching
An interlock prevents an action when a conflicting or hazardous condition exists. A permissive identifies conditions that must be satisfied before an action is allowed. Examples include preventing forward and reverse contactors from energizing simultaneously, requiring adequate lubrication pressure before a spindle starts, and blocking a valve command when a guard is open.
A robust motor command can be expressed conceptually as:
Run_Command = Auto_Request AND Guard_Closed AND Pressure_OK
AND NOT Fault_Latched AND NOT Reverse_Command
The following distinctions are important:
A permissive allows operation but does not necessarily remove energy immediately.
An interlock inhibits a conflicting command.
A trip or safety function drives equipment to a defined safe condition.
A latch stores a command until a reset or opposing condition occurs.
Fault latches should record the reason for stopping and should not reset automatically when doing so could create unexpected motion. Reset logic should require a deliberate action and confirm that the initiating fault has cleared.
5. Sequential Control and State Machines
A sequential controller is most clearly designed as a finite-state machine. A state describes the current phase of operation; a transition is a condition that causes movement to another state; actions define outputs associated with the current state.
For a simple indexing machine, states might be:
State
Main action
Transition condition
IDLE
All actuators safe
Start and permissives true
CLAMP
Energize clamp valve
Clamp-closed sensor true
PROCESS
Run spindle or tool
Process timer complete
RELEASE
De-energize clamp
Clamp-open sensor true
COMPLETE
Increment production count
Acknowledge or automatic return
FAULT
Remove commands, display fault
Reset and safe conditions
A state-machine design separates what phase the machine is in from why it may leave that phase. This is easier to test than a large collection of unrelated latches. Every state should have defined entry conditions, actions, exit transitions, timeout behavior, and recovery behavior.
A textual implementation may use an enumerated variable:
CASE State OF
IDLE:
Clamp_Valve := FALSE;
Spindle_Run := FALSE;
IF Start_Request AND Permissives_OK THEN
State := CLAMP;
END_IF;
CLAMP:
Clamp_Valve := TRUE;
IF Clamp_Closed THEN
State := PROCESS;
ELSIF Clamp_Timer.Q THEN
Fault_Code := 101;
State := FAULT;
END_IF;
PROCESS:
Spindle_Run := TRUE;
IF Process_Timer.Q THEN
State := RELEASE;
END_IF;
RELEASE:
Clamp_Valve := FALSE;
IF Clamp_Open THEN
State := COMPLETE;
END_IF;
COMPLETE:
Part_Count := Part_Count + 1;
State := IDLE;
FAULT:
Clamp_Valve := FALSE;
Spindle_Run := FALSE;
IF Reset_Request AND Safe_To_Reset THEN
State := IDLE;
END_IF;
END_CASE;
The example is illustrative rather than vendor-specific. In a real implementation, timers should be instantiated and managed so that they are enabled in the intended states, and output ownership should be unambiguous. A transition timeout is essential when a sensor may fail or a cylinder may jam.
5.1 Sequential Function Chart perspective
Sequential Function Chart (SFC) formalizes steps, transitions, and actions graphically. It is useful for communicating a sequence to operators, mechanical engineers, and maintenance personnel. LD or ST may implement individual actions and conditions. The choice depends on the project standard, team skill, tool support, and required diagnostics.
6. Hardware Configuration and Commissioning
PLC configuration begins with an I/O list. Each device should have a tag, electrical type, normal state, physical location, terminal identification, signal range, and failure response. The designer then selects modules for voltage, current, isolation, channel count, resolution, environmental rating, and required speed.
Configuration tasks include:
Create the controller and rack or remote-I/O topology.
Assign module types and network addresses.
Map physical channels to symbolic tags.
Configure analog ranges, filtering, scaling, and diagnostic behavior.
Set task periods and communication parameters.
Download hardware and program configuration.
Verify each channel using controlled tests.
A loop check should verify the complete signal path: field device, wiring, terminal, I/O channel, tag, logic, output channel, actuator, and feedback. For analog loops, the technician should test representative low, mid-scale, and high signals and confirm engineering-unit scaling.
7. Worked Application: Automated Part-Filling Station
Background
The following is an illustrative case. A small station receives an empty container on a conveyor, clamps it, fills it for a controlled period, releases it, and counts the completed units. The station contains a part sensor, clamp cylinder with open and closed sensors, a fill solenoid, a conveyor motor, a guard switch, and a reset button.
Problem definition
The machine must not fill unless a part is present and clamped. It must stop the sequence if the guard opens, a cylinder fails to reach position within 3 s, or the filling operation exceeds 8 s. Operators need a clear fault indication and a controlled reset.
Analysis and design
The sequence is represented by the states WAIT_PART, CLAMP, FILL, RELEASE, COUNT, and FAULT. The principal permissive is:
Permissives_OK = Guard_Closed AND EStop_Reset AND NOT Fault_Latched
The clamp timer has a 3 s preset, and the fill timer has an 8 s preset. The fill timer may have a normal process duration of, for example, 2 s, but the 8 s limit is a fault timeout rather than necessarily the desired fill duration. Separating process time from maximum allowed time makes the design easier to diagnose.
Solution structure
In WAIT_PART, the conveyor runs until Part_Present is TRUE.
In CLAMP, the conveyor stops and the clamp output energizes.
If Clamp_Closed becomes TRUE before the clamp timeout, the controller enters FILL.
In FILL, the fill valve opens. Completion occurs when the fill timer reaches its process preset. A separate maximum-duration timer detects abnormal delay.
In RELEASE, the valve closes and the clamp retracts.
In COUNT, a one-shot increments the completed-part counter.
Any guard, emergency, drive, or timeout fault transfers the machine to FAULT.
Verification
Testing should include normal operation, no-part start, guard opening in every state, failure of each position sensor, stuck valve simulation, timer timeout, power restoration, reset while unsafe, and counter retention. The expected result is not merely that the machine stops; it must stop in a predictable state, identify the cause, and require an appropriate recovery procedure.
Outcome and learning points
The state-machine approach gives each operating phase a visible meaning and gives maintenance personnel a direct diagnostic path. Timers identify failed motion rather than allowing the controller to wait indefinitely. Interlocks prevent filling without verified clamping. The case demonstrates that sequential automation is a combination of mechanical design, electrical design, software, safety engineering, and commissioning discipline.
8. Testing, Troubleshooting, and Maintenance
PLC troubleshooting should proceed from the physical process toward the program rather than assuming that every fault is software-related. A useful sequence is:
Make the equipment safe and follow lockout/tagout procedures.
Read the alarm and fault history.
Check power supplies, fuses, networks, and diagnostic LEDs.
Confirm the field device and its wiring.
Observe the input tag while actuating the device.
Trace the logic and identify the first false permissive or unexpected state.
Check the output tag and physical output channel.
Verify the actuator, air pressure, mechanical alignment, and feedback.
Correct the cause, test under controlled conditions, and document the repair.
Forcing an input or output can be useful during commissioning but is hazardous in a live machine. Forces must be authorized, recorded, clearly displayed, and removed after testing. Online edits require version control and post-change validation.
Common software defects include duplicated output ownership, incorrect timer reset behavior, missing edge detection, reversed sensor logic, race conditions between tasks, uninitialized variables, and automatic restart after power recovery. A program should include diagnostic states, meaningful fault codes, watchdog monitoring, and an operator display that distinguishes a process condition from an equipment fault.
9. Safety, Cybersecurity, and Professional Practice
A standard PLC is not automatically a safety controller. Risk reduction may require dual-channel emergency-stop circuits, monitored guard switches, safety relays, safety PLCs, redundant contactors, safe torque off, and validated safety functions. The required architecture depends on the risk assessment and applicable regional standards.
Safety-related control systems should be designed according to recognized machinery-safety principles, including risk assessment, defined safe states, diagnostic coverage, fault exclusion where justified, validation, and documented proof testing. Software must never bypass a protective device merely to improve production.
Networked PLCs also create cybersecurity exposure. Good practice includes role-based access, strong authentication, segmented control networks, controlled remote access, backups, patch governance, malware protection where appropriate, secure engineering workstations, and change logs. Availability and deterministic operation matter in industrial systems, so cybersecurity controls must be engineered rather than copied indiscriminately from office IT.
Artificial intelligence can assist with alarm classification, predictive maintenance, code review, and anomaly detection. It should not autonomously alter safety logic or production control without engineering review, validation, traceability, and authorization. Training data may contain biased or incomplete operating conditions, and a statistically plausible recommendation is not proof of a safe control action.
10. Contemporary Developments and Best Practices
Modern PLC platforms increasingly support object-oriented program organization, reusable function blocks, OPC UA and industrial Ethernet, edge analytics, digital twins, simulation-based commissioning, and integrated safety. These technologies can reduce commissioning time, but they also increase configuration complexity and dependence on network and software lifecycle management.
Recommended practices are:
Write a functional specification before coding.
Use symbolic tags and consistent naming conventions.
Separate safety logic, sequence logic, equipment modules, and human-machine-interface code.
Give every state a timeout and defined fault response.
Make output ownership single and explicit.
Use version control, backups, code reviews, and documented changes.
Test normal, abnormal, boundary, and recovery conditions.
Design for maintenance, including diagnostics and readable comments.
Validate the machine after software or hardware changes.
Treat safety, cybersecurity, and data integrity as engineering requirements.
Chapter Summary
PLCs provide a flexible platform for industrial control by scanning inputs, executing programs, and updating outputs. Effective sequential automation requires more than individual Boolean instructions: it requires sound hardware configuration, correctly scaled signals, appropriate timers and counters, edge detection, interlocks, permissives, fault latching, and explicit recovery behavior. IEC 61131-3 languages serve different purposes: ladder logic is highly accessible for discrete control, FBD exposes signal relationships and reusable functions, and structured text is powerful for calculations and state machines.
Finite-state-machine design is especially valuable for machines with ordered actions because it makes states, transitions, outputs, timeouts, and fault handling explicit. Commissioning must verify the complete signal chain and must be performed safely. Standard PLC logic must not be confused with certified safety control. Cybersecurity, documentation, version control, validation, and maintainability are integral to professional automation engineering.
Key Terms
PLC: Industrial computer designed for real-time control.
Scan cycle: Repeated sequence of input reading, program execution, and output updating.
Input image table: Memory representation of input values used by the program.
Discrete signal: Signal represented by finite states, commonly TRUE or FALSE.
Analog signal: Continuously varying signal within a defined range.
IEC 61131-3: International framework for PLC programming languages and concepts.
Ladder diagram: Graphical PLC language based on relay-control symbolism.
Function block diagram: Graphical language using interconnected functional blocks.
Permissive: Condition that must be satisfied before operation is allowed.
Interlock: Logic that prevents conflicting or hazardous operation.
Latch: Stored Boolean command maintained until reset or opposing logic occurs.
State machine: Controller organized into states and transition conditions.
Edge detection: Identification of a change in Boolean state, such as FALSE-to-TRUE.
Retentive data: Data preserved through a specified reset or power event.
Safety PLC: Controller designed and certified for specified safety-related functions.
Commissioning: Structured process of testing and putting a control system into service.
Review Questions
Short Answer Questions
What are the principal stages of a conventional PLC scan cycle?
Distinguish a permissive from an interlock.
What is the purpose of rising-edge detection in a counter circuit?
Why can a standard PLC not automatically be treated as a safety controller?
State one strength of ladder diagram, function block diagram, and structured text.
Long Answer Questions
Explain PLC hardware architecture and describe the selection considerations for digital and analog I/O modules.
Describe how a state machine can be used to control a clamping and filling sequence.
Explain TON, TOF, and TP timers, including their typical industrial applications and limitations.
Develop a systematic troubleshooting procedure for a motor that receives a PLC command but does not run.
Discuss the roles of documentation, version control, cybersecurity, and validation in PLC projects.
Analytical / Application Questions
Design the states, transitions, timeout conditions, and fault responses for a conveyor that detects, drills, and ejects a workpiece.
A 4–20 mA transmitter represents 0–250 °C. Determine the temperature represented by 15.2 mA and explain the assumptions used in the scaling.
A forward/reverse motor control occasionally energizes both contactors during a command change. Analyze possible PLC and hardware causes and propose interlocks and test procedures to eliminate the hazard.
Multiple Choice Questions with Answers
Question 1
Which sequence best describes a conventional PLC scan cycle?
A. Update outputs, read inputs, compile the program, shut down
B. Read inputs, execute the program, update outputs, perform diagnostics
C. Execute outputs, read diagnostics, erase memory, read inputs
D. Read inputs, reset outputs, wait for an operator, execute diagnostics
Correct Answer: B. Read inputs, execute the program, update outputs, perform diagnostics
Question 2
Which IEC 61131-3 language is generally most suitable for a calculation-heavy state-machine implementation?
A. Structured text
B. Ladder diagram only
C. Wiring schematic
D. Mechanical drawing
Correct Answer: A. Structured text
Question 3
A TON timer normally sets its output TRUE when which condition occurs?
A. Its input is FALSE for the preset time
B. Its input remains TRUE for the preset time
C. Its output is forced by an operator
D. The PLC loses power
Correct Answer: B. Its input remains TRUE for the preset time
Question 4
Why is a rising-edge detector commonly used before an up-counter?
A. To convert analog current into voltage
B. To ensure a held signal produces only one count pulse
C. To increase motor speed
D. To disable all interlocks
Correct Answer: B. To ensure a held signal produces only one count pulse
Question 5
Which statement best describes a permissive?
A. A condition that must be satisfied before an action is allowed
B. A device that stores electrical energy
C. A mechanical component that converts rotary motion
D. A network cable standard
Correct Answer: A. A condition that must be satisfied before an action is allowed
Question 6
In a state-machine design, what normally causes a transition?
A. A defined condition associated with the current state
B. A random change in an unrelated output
C. A permanent deletion of the current state
D. A change in the PLC brand
Correct Answer: A. A defined condition associated with the current state
Question 7
A 4–20 mA transmitter has a 0–10 bar range. What pressure corresponds ideally to 12 mA?
A. 2 bar
B. 4 bar
C. 5 bar
D. 8 bar
Correct Answer: C. 5 bar
Question 8
Which practice most directly helps prevent simultaneous forward and reverse motor commands?
A. Removing all feedback sensors
B. Using mutually exclusive interlocks
C. Increasing the analog input range
D. Disabling diagnostic messages
Correct Answer: B. Using mutually exclusive interlocks
Question 9
What is the safest first priority when troubleshooting a malfunctioning industrial machine?
A. Force every output TRUE
B. Modify the program online without documentation
C. Make the equipment safe and follow lockout/tagout procedures
D. Replace the CPU immediately
Correct Answer: C. Make the equipment safe and follow lockout/tagout procedures
Question 10
Which statement about a standard PLC and safety control is correct?
A. Every standard PLC is automatically safety-rated
B. Safety functions never require validation
C. A standard PLC can replace every emergency-stop circuit
D. Safety functions require appropriate rated hardware or safety software and validation
Correct Answer: D. Safety functions require appropriate rated hardware or safety software and validation
Mechatronics & Industrial Automation
Chapter 7
of 15