Bachelors Program in Electrical Engineering
Industrial Automation & PLC
•
Bachelor
Logic, Sequencing and Machine Control
Introduction
Industrial machines rarely perform a single independent action. A packaging machine, pumping station, conveyor cell, or robotic fixture must interpret operator commands, verify safe conditions, execute actions in a prescribed order, monitor time and quantity, and respond predictably to abnormal conditions. The programmable logic controller (PLC) provides the scan-based computational platform for this work, but reliable machine control depends on more than knowing ladder symbols. It requires a disciplined control model.
This chapter develops that model. It explains timers, counters, comparisons, arithmetic, data handling, state machines, step sequences, alarms, permissives, interlocks, operating modes, and robust start-up and shutdown. The emphasis is on translating a process description into deterministic, maintainable PLC logic.
Learning Objectives
By the end of this chapter, a student should be able to:
Explain the operation and limitations of PLC timers, counters, comparisons, arithmetic instructions, and data structures.
Distinguish permissives, interlocks, trips, alarms, and operator commands.
Design a state machine or step sequence for an automated machine.
Implement automatic, manual, jog, maintenance, and fault-reset modes safely.
Develop robust start-up, normal shutdown, emergency shutdown, and restart logic.
Analyze race conditions, retentive data, scan timing, and failure modes in PLC programs.
Document and test machine-control logic using professional engineering practices.
1. From Process Description to Control Algorithm
A useful control specification separates five types of information:
Inputs: sensors, pushbuttons, selector switches, network values, and analog measurements.
Outputs: motor contactors, valves, heaters, solenoids, indicators, and messages.
Conditions: facts that must be true before an action is allowed.
Sequence: the order and completion criteria for actions.
Exceptions: faults, timeouts, unsafe states, and recovery requirements.
For example, “start the conveyor when the operator presses Start” is incomplete. A proper specification might state:
When the machine is in Auto mode, the safety circuit is healthy, no active trip exists, guards are closed, downstream capacity is available, and the conveyor is not already running, a rising edge of Start shall initiate the conveyor-start sequence. If the run feedback does not arrive within 2 s, the command shall be removed and a start-failure fault shall be generated.
This statement identifies mode, permissives, command edge, state, feedback, timeout, and fault response. Such precision prevents ambiguous logic.
A PLC generally repeats the following cycle:
Read or update input images.
Execute the program from beginning to end.
Update physical outputs and communications.
Perform diagnostics and housekeeping.
If the scan time is Ts and an input changes just after it is read, the program may not react until the next scan. For ordinary machine sequencing this delay is negligible, but it matters for high-speed counting, pulse measurement, and time-critical safety functions. Safety-related stopping must use appropriately certified safety hardware or safety PLC functions, not ordinary logic alone.
2. Boolean Logic and Control Permissions
The basic Boolean operations are AND, OR, and NOT. If A and B are Boolean variables, then A ∧ B is true only when both are true; A ∨ B is true when at least one is true; and ¬A is true when A is false.
A permissive is a condition that allows an action. A pump permissive might be:
PumpPermissive = Auto ∧ SafetyOK ∧ LevelHigh ∧ ¬PumpTrip
A command expresses an intended action, while a permissive determines whether that action may occur. Thus:
PumpRunCmd = StartRequest ∧ PumpPermissive
An interlock prevents an action because another condition makes it unsafe or damaging. A forward and reverse motor command should be mutually exclusive:
ForwardCmd = ForwardRequest ∧ ¬ReverseOutput
ReverseCmd = ReverseRequest ∧ ¬ForwardOutput
For contactor-controlled motors, electrical and mechanical interlocking should supplement the PLC logic. A PLC output failure must not be the only barrier against simultaneous contactor energization.
A trip is a condition that removes an action, often requiring acknowledgement or reset. An alarm communicates an abnormal condition; it may or may not stop the machine. These terms must be defined in the functional specification rather than used interchangeably.
Seal-in Logic and Its Risks
A conventional run latch is conceptually:
RunLatch = (Start ∨ RunLatch) ∧ Stop ∧ SafetyOK
Here Stop and SafetyOK represent healthy conditions. In practice, a normally closed stop contact is often represented by a true “StopHealthy” variable. A latch must have a clearly dominant stop or trip path. If a start and stop request occur simultaneously, the design should specify which wins; for safety-related systems, stopping normally has priority.
Latches can conceal the reason an output remains energized. State-based logic is often clearer because the machine’s current state explicitly explains its behavior.
3. Timers, Counters, Comparisons, and Arithmetic
3.1 Timers
Common PLC timer types are:
Timer
Function
Typical use
TON
On-delay; output becomes true after input remains true for a preset time
Start confirmation, delay before valve opening
TOF
Off-delay; output remains true for a period after input becomes false
Fan overrun, lubrication delay
TP or pulse timer
Generates a pulse of specified duration
Solenoid pulse, alarm horn
Retentive timer
Accumulated elapsed time is retained when input becomes false until reset
Operating-hour total
For a non-retentive on-delay timer, if the enabling input remains true continuously, elapsed time increases until it reaches preset time. If te is elapsed time and tp is preset time, the done condition is conceptually:
te ≥ tp
The units of te and tp must be identical. If the preset is 2 s, a millisecond-based instruction requires 2000 ms. A timer’s accuracy is limited by implementation, scan period, task scheduling, and hardware clock resolution. A timer should not be treated as a precision measurement instrument.
A timeout should monitor feedback, not merely the command. For example, a valve-open timeout begins when the open command is issued and completes successfully only when the open limit switch is detected. If the limit is absent at timeout, the system should enter a defined fault response.
3.2 Counters and Edge Detection
An up-counter increments on a false-to-true transition, not continuously while its input remains true. If a sensor stays blocked for ten scans, it should normally represent one object, not ten objects. An edge detector creates a one-scan pulse:
RisingEdge = CurrentInput ∧ ¬PreviousInput
The previous value must be updated at a suitable point in the program. Fast sensors may require high-speed counter hardware because ordinary scan-based edge detection can miss pulses.
A count-complete condition can be represented as:
CountComplete = Count ≥ TargetCount
Counter preset, current value, reset behavior, and retentiveness must be specified. A reset should not accidentally erase production totals that are required for traceability.
3.3 Comparisons and Deadbands
Comparisons convert measurements into decisions. For a high-temperature alarm:
HighAlarm = Temperature ≥ HighLimit
Repeated switching around a threshold can cause chatter. Hysteresis uses different thresholds for activation and clearing:
AlarmSet when x ≥ xH AlarmClear when x ≤ xL, where xL < xH
The difference xH − xL is the deadband. The correct deadband depends on sensor noise, process dynamics, and acceptable control variation.
Range checking is useful for validating analog or network data:
Valid = (x ≥ xmin) ∧ (x ≤ xmax)
The limits must reflect engineering units and sensor characteristics. A raw input count must not be compared directly with an engineering-unit limit unless the conversion has been performed or the limit has been converted consistently.
3.4 Arithmetic and Scaling
PLC programs commonly calculate totals, rates, offsets, and engineering values. A linear conversion from raw value R to engineering value E is:
Here Rmin and Rmax are the calibrated raw endpoints, while Emin and Emax are the corresponding engineering-unit endpoints. The formula assumes a linear sensor relationship and Rmax ≠ Rmin. It is essential to prevent division by zero and to decide whether values outside the raw range are clamped, flagged invalid, or extrapolated.
Worked example. A 4–20 mA transmitter is represented by raw counts from 4000 to 20,000 and measures 0–100 °C. At a raw value of 12,000:
The result is dimensionally consistent because the raw-count ratio is dimensionless and is multiplied by the engineering span in degrees Celsius.
Other important arithmetic issues include integer truncation, overflow, signed versus unsigned interpretation, and division by zero. Use data types large enough for the maximum credible value. For a production total, a 32-bit or 64-bit integer may be necessary even if the per-batch count fits in 16 bits.
4. Data Handling and Structured PLC Design
A maintainable program separates data by purpose:
Data category
Examples
Design concern
Process inputs
Limit switches, pressure, temperature
Quality, plausibility, timestamp
Commands
Start, stop, reset, mode request
Edge detection and priority
Status
Running, ready, step number
Operator visibility
Parameters
Timeouts, target quantity, limits
Access control and validation
Alarms
Active, acknowledged, historical
Latching and reset policy
Diagnostic data
Scan time, fault code, last state
Troubleshooting
Use meaningful names such as Conveyor_RunFeedback rather than addresses such as I:2/5. Symbolic names reduce errors and improve portability. User-defined structures can group related fields, for example a motor structure containing command, feedback, overload, permissive, runtime, and fault status.
Parameters should be validated at startup or when edited. A zero valve timeout, negative speed reference, or target count beyond equipment capability should be rejected with a configuration fault. Operator-editable values should have access control, units, ranges, and audit requirements where appropriate.
Retentive memory deserves particular care. Retaining a state such as “filling in progress” across a power failure can be dangerous if the physical process has changed while the PLC was off. A safe restart generally reinitializes the sequence to an inspection or recovery state, unless the equipment and risk assessment specifically support automatic resumption.
5. State Machines and Step Sequences
A state machine represents the machine as a finite set of states and transitions. A state defines what the machine is doing and which outputs are permitted. A transition defines the condition for moving to another state.
For a simple filling process:
Idle: waiting for a valid start request.
Verify: checking material, guards, and downstream availability.
Clamp: energizing the clamp and waiting for clamp-closed feedback.
Fill: opening the fill valve until level or quantity is reached.
Release: opening the clamp after the fill operation.
Complete: recording the batch and returning to Idle.
Fault: removing hazardous commands and presenting diagnostic information.
Only one normal sequence state should be active at a time. A state transition should be explicit, and each state should have entry, action, and exit behavior. Repeatedly executing an entry action every scan can cause problems; a one-shot StateEntered pulse is useful for initialization.
A transition can be expressed as:
Transition = Statei ∧ Conditioni
After the transition, Statei is cleared and Statej is set. The implementation may use integer step numbers, enumerated states, sequential function charts, or a structured state variable. The method matters less than the discipline: one authoritative state, defined transitions, and defined fault behavior.
State sequence for a filling machine
Figure: State sequence for a filling machine
Figure: A state-based filling sequence with a common fault destination.
A timeout belongs to the transition or state supervision, not merely to the actuator command. For example, the Clamp state should leave only when ClampClosed is true; otherwise a clamp timer expires and transfers control to Fault. This prevents the next step from starting while the physical mechanism has not reached position.
6. Modes of Operation
A professional machine commonly includes:
Off: outputs are de-energized except designated safe-status devices.
Manual: an authorized operator commands individual devices under interlocks.
Jog: motion occurs only while a maintained or momentary command is present, often at reduced speed.
Automatic: the sequence controls actions and transitions.
Maintenance/setup: specialized access with documented risk controls.
Fault/reset: faults are displayed and reset conditions are evaluated.
Mode selection must be mutually exclusive and validated. A mode change should not silently create an output conflict. One effective policy is to require the machine to be stopped before changing between Manual and Auto. Another is to define bumpless transfer rules explicitly.
Manual mode is not permission to bypass safety. Guard circuits, emergency stops, safe torque off, pressure protection, and other critical protective functions should remain effective. Any controlled bypass must be authorized, time-limited where feasible, logged, and governed by a risk assessment.
7. Start-Up, Shutdown, and Fault Recovery
Start-up
On power-up, the controller should establish a known logical state, validate configuration, read safety status, and determine whether physical feedback is plausible. A robust start-up sequence often includes:
Initialize non-retentive commands and timers.
Validate parameters and communication health.
Confirm safety circuits and required utilities.
Check that actuators are in permissible positions.
Require an operator reset or deliberate start request.
Execute homing or recovery if position is unknown.
Permit automatic sequencing only after all conditions are satisfied.
The PLC must not infer that a motor is stopped simply because its command is false; feedback should be checked where stopping confirmation matters.
Normal shutdown
Normal shutdown is a controlled sequence. It may stop material feed, allow a conveyor to clear, close valves, remove heat, and run a cooling fan for a prescribed period. Each action needs a completion condition or timeout.
Emergency shutdown and trips
An emergency stop is not simply a software alarm. The safety function must be designed according to applicable machinery-safety requirements, risk assessment, stopping category, and validation procedures. The standard PLC can report the safety status and coordinate orderly consequences, but it should not replace the safety system.
A trip response should identify:
which outputs are removed immediately;
which outputs remain active for safe dissipation or cooling;
whether the sequence state is retained or reset;
what acknowledgement is required;
what physical conditions must be restored before reset;
whether restart requires a new start command.
A reset should clear a fault indication only when the initiating condition is absent and the reset command is deliberate. Reset must not automatically restart hazardous motion.
8. Alarms, Diagnostics, and Human–Machine Interfaces
An alarm should be actionable. A useful alarm record includes tag, description, cause, consequence, priority, timestamp, acknowledgement state, and recommended operator action. “Motor fault” is less useful than “Filler motor overload—check jam, overload relay, and coupling.”
Alarm classes may include:
Advisory: information requiring attention but not immediate intervention.
Warning: abnormal condition that may become serious.
Trip: condition that has stopped or inhibited equipment.
Safety status: indication of a protective-device condition.
Alarm flooding reduces attention and can hide the initiating event. Use deadbands, delays, suppression rules, and first-out diagnostics carefully. Suppression must never conceal a safety-critical condition.
The HMI should show current state, active permissives, inhibited conditions, timers, counter values, fault code, and the last successful or failed transition. A state number without a textual description is not sufficient for operations personnel.
Consider an illustrative carton-filling cell. A conveyor positions a carton, a pneumatic clamp holds it, a filling valve dispenses product, and the conveyor transfers the carton to the next station. Inputs include Start, Stop, guard status, air pressure, carton sensor, clamp-closed feedback, fill-level sensor, valve feedback, motor overload, and emergency-stop status.
Problem
An initial program energized the conveyor whenever Start was pressed. It sometimes advanced without a carton, opened the valve before clamping was complete, and remained in a run command when the valve limit switch failed. Operators also reported that an alarm reset occasionally restarted motion.
Analysis
The original design mixed commands, permissives, and sequence states. It had no explicit timeout for clamp or valve movement, no edge detection on the carton sensor, and no distinction between a fault reset and a start request. The absence of a state model made it difficult to identify which step had failed.
Approach and solution
The redesigned logic uses the states Idle, Verify, Clamp, Fill, Release, Transfer, and Fault. The Verify state checks SafetyOK, AirPressureOK, GuardClosed, NoOverload, and valid parameters. In Clamp, the clamp command is energized and a 1.5 s TON supervises the wait for ClampClosed. In Fill, the valve opens and a 3 s timer supervises valve confirmation and fill-level completion. A rising-edge detector counts each carton sensor transition once.
The conveyor command is generated only in Transfer and only when the downstream-ready permissive is true. A fault transfers the sequence to Fault, removes process commands, records the state and fault code, and requires the physical cause to clear plus a separate reset. Reset returns the machine to Verify or Idle; it does not generate Start.
Outcome
The revised design prevents premature filling, identifies failed actuators through timeouts, avoids duplicate carton counts, and gives operators a meaningful diagnostic path. Testing also revealed that the air-pressure switch could chatter, so a short validation delay and a pressure-loss trip policy were added. The example demonstrates that reliable automation is primarily an exercise in explicit assumptions and controlled transitions.
Learning points
A command is not proof that an action occurred.
Feedback and timeout supervision are essential for sequential equipment.
Fault reset and machine start should be separate events.
State and fault information must be visible to operators and maintainers.
Safety functions require suitable hardware, assessment, and validation.
10. Testing and Professional Practice
Test logic progressively:
Perform code review and I/O verification.
Simulate each input and confirm expected output behavior.
Test every state transition and every timeout.
Test simultaneous and conflicting commands.
Remove feedback deliberately to verify fault response.
Test power loss, communication loss, sensor failure, and restart.
Conduct factory acceptance testing, then site acceptance testing.
Record revisions, test evidence, bypasses, and open defects.
Use a cause-and-effect matrix for important equipment. For each abnormal condition, document affected outputs, alarm, reset requirements, and restart policy. Online forcing of outputs is hazardous and should be controlled, authorized, recorded, and removed after testing.
11. Limitations and Contemporary Practice
PLC scan logic is deterministic only within the timing and architecture of its task system. Network delays, asynchronous I/O, variable scan loads, and clock resolution can affect behavior. High-speed motion, safety, and precision measurement may require dedicated motion controllers, safety PLCs, hardware counters, or real-time systems.
Modern PLC platforms increasingly support structured text, sequential function charts, object-oriented data structures, OPC UA, version control, and diagnostics. These tools improve engineering when accompanied by naming standards, cybersecurity controls, and change management. Artificial intelligence can assist with alarm analysis, anomaly detection, and maintenance prediction, but it should not silently alter safety interlocks or replace validated deterministic control. Any AI-derived recommendation must remain observable, bounded, tested, and subject to human approval.
Cybersecurity is part of machine control. Strong authentication, network segmentation, least privilege, secure backups, patch management, and controlled remote access help prevent unauthorized logic changes. Regulatory obligations vary by jurisdiction, but machinery safety, electrical installation, functional safety, and industrial cybersecurity standards should be identified during project definition rather than after commissioning.
Best-Practice Checklist
Define commands, permissives, interlocks, trips, and alarms separately.
Use symbolic names and engineering units.
Detect edges for events and count objects once.
Supervise commanded actions with physical feedback and timeouts.
Use hysteresis where measurements can chatter.
Validate parameters and guard against overflow and division by zero.
Represent complex behavior with explicit states and transitions.
Make safety behavior independent of ordinary control logic where required.
Separate reset from restart.
Make current state, permissives, and fault causes visible.
Test abnormal conditions, not only the normal happy path.
Control bypasses, forces, revisions, and remote access.
Chapter Summary
Reliable machine control begins with a precise process specification that distinguishes inputs, commands, conditions, sequence steps, and exceptions. Timers provide temporal supervision, counters record discrete events, comparisons and hysteresis convert measurements into stable decisions, and arithmetic converts and evaluates process data. These functions must account for scan timing, data types, units, overflow, edge detection, and parameter validation.
Permissives allow actions, interlocks prevent unsafe combinations, trips remove operation, and alarms communicate abnormal conditions. State machines provide a clear representation of machine behavior, while step sequences organize actions around explicit completion feedback and timeouts. Mode management must prevent conflicting control sources and must not compromise safety.
Robust start-up and shutdown logic establishes known conditions, checks feedback, handles utilities and recovery, and prevents an alarm reset from causing an unexpected restart. Professional PLC engineering also requires diagnostics, testing, documentation, cybersecurity, controlled changes, and suitable safety hardware. These practices transform a collection of instructions into a dependable industrial control system.
Key Terms
Alarm: A notification of an abnormal or noteworthy condition.
Arithmetic scaling: Conversion of a raw value into an engineering-unit value.
Counter: An instruction that records discrete input events.
Deadband: Difference between activation and clearing thresholds.
Edge detection: Detection of a transition, such as false-to-true, rather than a sustained signal.
Fault: An abnormal condition requiring defined corrective action.
Hysteresis: Use of separate set and clear thresholds to prevent chatter.
Interlock: A condition that prevents an action because it is unsafe or incompatible.
Latch: Logic that maintains a state after the initiating signal is removed.
Mode: A defined method of operating equipment, such as Manual or Auto.
Permissive: A condition that must be true before an action is allowed.
Retentive data: Data preserved when an instruction or controller loses its enabling condition.
Rising edge: A false-to-true transition of a Boolean signal.
Sequence: Ordered machine actions and their transition conditions.
State machine: A model consisting of defined states and transitions.
Timeout: A fault-supervision limit applied when expected feedback does not arrive.
TON timer: A timer whose done output occurs after a continuous on-delay.
Trip: A condition that stops or inhibits equipment, often requiring reset.
Review Questions
Short Answer Questions
Distinguish a permissive, an interlock, an alarm, and a trip.
Why should a counter normally use edge detection for a photoelectric sensor?
State two differences between a non-retentive and a retentive timer.
Why is actuator feedback needed in a sequential machine?
Why should resetting a fault not automatically restart hazardous motion?
Long Answer Questions
Explain how a finite-state machine can improve the design and diagnosis of an automated filling process.
Describe a robust PLC start-up sequence, including parameter validation and physical feedback checks.
Explain linear analog scaling, define every variable in the scaling equation, and discuss out-of-range handling.
Compare Manual, Jog, Automatic, and Maintenance modes, including their safety implications.
Develop an alarm and diagnostic philosophy for a conveyor-driven production cell.
Analytical / Application Questions
A motor command is issued, but run feedback does not arrive within the specified time. Design the state transition, timer action, alarm, output response, reset condition, and restart policy.
A 0–10 V sensor has raw values 0–32,000 and measures 0–250 °C. Calculate the temperature at a raw value of 20,000 using linear scaling, and identify two validation checks needed in the PLC.
Design a state sequence for a machine that indexes a part, clamps it, performs an operation, unclamps it, and transfers it. Include at least one permissive, one interlock, a timeout for each motion, and a common fault state.
Multiple Choice Questions with Answers
Question 1
Which timer becomes done after its enabling input remains true for the preset duration?
A. TON
B. TOF
C. Counter
D. Pulse counter
Correct Answer: A. TON
Question 2
Why is rising-edge detection commonly used with a product sensor connected to a counter?
A. To make the sensor analog
B. To count one event rather than every scan while the sensor is active
C. To increase motor speed
D. To retain the count after power loss
Correct Answer: B. To count one event rather than every scan while the sensor is active
Question 3
Which statement best describes a permissive?
A. It records historical alarm data
B. It guarantees that an actuator has moved
C. It is a condition that allows an action to occur
D. It always removes power independently of hardware
Correct Answer: C. It is a condition that allows an action to occur
Question 4
For linear scaling from raw value R to engineering value E, which expression is correct?
A. E = R + Emax
B. E = Emin + (R − Rmin) × (Emax − Emin) ÷ (Rmax − Rmin)
C. E = R × Rmax ÷ Rmin
D. E = (Rmin − Rmax) ÷ (Emin − Emax)
Correct Answer: B. E = Emin + (R − Rmin) × (Emax − Emin) ÷ (Rmax − Rmin)
Question 5
What is the principal purpose of hysteresis in a threshold alarm?
A. To prevent repeated switching near the threshold
B. To increase the PLC scan frequency
C. To convert a digital signal to analog
D. To reset a retentive timer
Correct Answer: A. To prevent repeated switching near the threshold
Question 6
In a state machine, what normally causes a transition from one state to another?
A. An explicit transition condition
B. Any unrelated input change
C. A power-cycle only
D. The HMI screen color
Correct Answer: A. An explicit transition condition
Question 7
Which practice is safest for a machine fault reset?
A. Reset and immediately restart all outputs
B. Clear the fault only when the cause is absent and require a separate start command
C. Ignore physical feedback during reset
D. Permit reset from every unprotected network device
Correct Answer: B. Clear the fault only when the cause is absent and require a separate start command
Question 8
A raw input ranges from 4000 to 20,000 and represents 0–100 °C. What temperature corresponds to a raw value of 12,000?
A. 25 °C
B. 40 °C
C. 50 °C
D. 75 °C
Correct Answer: C. 50 °C
Question 9
Which statement about an emergency stop is correct?
A. Ordinary PLC ladder logic is always sufficient
B. It should be implemented and validated using suitable safety-related provisions
C. It should be bypassed in Manual mode
D. It should only generate an HMI message
Correct Answer: B. It should be implemented and validated using suitable safety-related provisions
Question 10
What is the main purpose of a timeout supervising actuator feedback?
A. To prove that the operator pressed Start
B. To detect that an expected physical action did not complete in time
C. To increase counter capacity
D. To eliminate the need for interlocks
Correct Answer: B. To detect that an expected physical action did not complete in time