TExcelTAD
Home › Control Systems & Automation › PLCs and the Scan Cycle

PLCs and the Scan Cycle

A conveyor in a packaging line stops when a light barrier sees a box, a pump starts when a tank is low, a heater loop holds a die at temperature, and a stop button must work every time. In factories these jobs run on a programmable logic controller (PLC): an industrial computer built to read switches and sensors, run a control program in a fixed, repeating cycle, and drive contactors, valves and drives, for decades, in dust, vibration and electrical noise. Most of what a control engineer designs ends up as a PLC program or a PID block inside one. This lesson explains how a PLC executes a program, because the scan cycle decides what the program can and cannot see; the next lesson covers the languages.

The hardware in one paragraph

A PLC is a CPU module plus input and output modules on a rack or DIN rail, usually powered from 24 V24\ \text{V} DC. Digital inputs read 24 V24\ \text{V} signals from push-buttons, limit switches and proximity sensors (with input filters of a few milliseconds against contact bounce and noise); digital outputs switch 24 V24\ \text{V} loads through transistors or drive relay contacts; analog modules read and write 4–20 mA4\text{–}20\ \text{mA} or 0–10 V0\text{–}10\ \text{V} (Sensors and Actuators). Remote I/O and drives connect over an industrial network. Larger loads (motors, heaters on mains) are switched by contactors and drives that the PLC only commands: those power circuits are designed by qualified people to electrical-installation standards and are calculation and concept only in this course.

The scan cycle

1 read inputs input image 2 execute program top to bottom 3 write outputs output image 4 comms, diag. watchdog one scan = scan time (typically 1 to 50 ms) scans read 1 read 2 read 3 read 4 read 5 read 6 input short pulse: missed long pulse: seen at read 5 output set at end of scan 5

A PLC runs its main program cyclically:

  1. Read inputs: copy every physical input into the input process image (a memory table).
  2. Execute the program from top to bottom, reading only the process image and writing only the output process image.
  3. Write outputs: copy the output image to the physical outputs.
  4. Housekeeping: communication, diagnostics, and a watchdog check: if the cycle takes longer than a set limit (for example 150 ms150\ \text{ms}), the CPU stops and the outputs go to their safe state.

Three consequences follow directly:

  • Consistency. An input cannot change halfway through the program, so two rungs that test the same input always agree.
  • Response time. An input change waits up to one scan to be read and then up to one more scan to reach the output. With input filter tft_f and output delay tot_o, the worst case is about tf+2tscan+tot_f + 2t_\text{scan} + t_o; the best case about tf+tscan+tot_f + t_\text{scan} + t_o (program execution plus output write).
  • Missed pulses. A pulse shorter than one scan can start and end between two reads and never be seen. Fast signals (encoder pulses, short sensor flashes) go to hardware counters or interrupt inputs instead.

Modern PLCs also run several tasks: the free-running main cycle, cyclic interrupts at a fixed interval (where PID blocks belong, because a PID needs a constant sample time: Discrete PID), and hardware event tasks.

Worked example: response time and missed pulses

Given: a PLC with a scan time of 10 ms10\ \text{ms}, 3 ms3\ \text{ms} input filter, 1 ms1\ \text{ms} output delay; a reflective sensor that sees each passing label for 8 ms8\ \text{ms}.

Find: the worst and best response times from a sensor edge to the output; the fraction of labels missed.

Solve:

  • Worst case: the edge arrives (after filtering) just after an input read: 3+10+10+1=24 ms3 + 10 + 10 + 1 = 24\ \text{ms}. Best case: just before a read: 3+10+1=14 ms3 + 10 + 1 = 14\ \text{ms} (execution and output write still take the rest of that scan).
  • An 8 ms8\ \text{ms} pulse is seen only if a read falls inside it; reads come every 10 ms10\ \text{ms} at random phase, so the probability of a hit is 8/108/10: 20 % of the labels are missed. (The input filter delays both edges equally and does not shorten the pulse in this simple model.)

Check: the program simulates both with random arrival times.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
scan, t_filter, t_out = 10.0, 3.0, 1.0           # ms
reads = np.arange(0.0, 200000.0, scan)            # input reads at the start of each scan

# response time: an input edge at a random time, output written at the end of the scan that read it
edges = rng.uniform(0, 199000.0, 20000)
seen = edges + t_filter
k = np.searchsorted(reads, seen)                  # first read at or after the filtered edge
resp = reads[k] + scan + t_out - edges
print(f"response time: min {resp.min():.1f} ms, mean {resp.mean():.1f} ms, max {resp.max():.1f} ms")

# missed pulses: 8 ms pulses at random times
for width in (8.0, 12.0):
    start = rng.uniform(0, 199000.0, 20000) + t_filter
    k = np.searchsorted(reads, start)
    hit = reads[k] < start + width
    print(f"{width:4.1f} ms pulses with a {scan:.0f} ms scan: {100 * (1 - hit.mean()):5.1f} % missed")
response time: min 14.0 ms, mean 19.0 ms, max 24.0 ms
 8.0 ms pulses with a 10 ms scan:  19.9 % missed
12.0 ms pulses with a 10 ms scan:   0.0 % missed

The fix for the labels is not a faster main program (scan times vary with the program) but a hardware counter input, or an input module that latches short pulses.

A program as the PLC sees it

The classic first program is a motor start/stop with seal-in (latching): pressing Start runs the motor and keeps it running after the button is released; pressing Stop, or a tripped motor overload, stops it. In IEC 61131-3 Structured Text (shown, not run: there is no PLC runtime here):

text
(* Start/stop with seal-in. Stop and Overload_OK are normally-closed contacts,
   so their inputs are TRUE when everything is healthy (wire-break safe). *)
Motor := (Start OR Motor) AND Stop AND Overload_OK;

The same logic, executed the way a PLC executes it (read image, run, write image) in Python:

python · try it yourself
def scan(inputs, image):
    """One PLC scan: inputs read into an image, program runs, outputs returned."""
    I = dict(inputs)                              # 1. read inputs
    Q = image                                     # outputs keep their value between scans
    Q["Motor"] = (I["Start"] or Q["Motor"]) and I["Stop"] and I["Overload_OK"]   # 2. execute
    return Q                                      # 3. write outputs

Q = {"Motor": False}
events = [
    ("idle",                 dict(Start=False, Stop=True,  Overload_OK=True)),
    ("press Start",          dict(Start=True,  Stop=True,  Overload_OK=True)),
    ("release Start",        dict(Start=False, Stop=True,  Overload_OK=True)),
    ("press Stop",           dict(Start=False, Stop=False, Overload_OK=True)),
    ("release Stop",         dict(Start=False, Stop=True,  Overload_OK=True)),
    ("Start again",          dict(Start=True,  Stop=True,  Overload_OK=True)),
    ("overload trips",       dict(Start=False, Stop=True,  Overload_OK=False)),
    ("overload reset",       dict(Start=False, Stop=True,  Overload_OK=True)),
    ("Stop wire breaks",     dict(Start=True,  Stop=False, Overload_OK=True)),
]
for name, inp in events:
    Q = scan(inp, Q)
    print(f"{name:18s} -> Motor {'ON ' if Q['Motor'] else 'off'}")
idle               -> Motor off
press Start        -> Motor ON
release Start      -> Motor ON
press Stop         -> Motor off
release Stop       -> Motor off
Start again        -> Motor ON
overload trips     -> Motor off
overload reset     -> Motor off
Stop wire breaks   -> Motor off

Two details are deliberate. The stop button is a normally-closed contact, read as TRUE when healthy, so a broken wire looks like a pressed Stop and the motor stops (fail-safe). And after the overload is reset the motor stays off: it needs a new Start, so a machine never restarts by itself after a fault.

Guided lab: a scan cycle on a microcontroller

Hand calculation. With a main loop of 10 ms10\ \text{ms} and 8 ms8\ \text{ms} button pulses from a function generator, expect about 20 % missed; with 12 ms12\ \text{ms} pulses, none.

Simulation. Change scan and width in the first program; check that the miss rate is 1−w/tscan1 - w/t_\text{scan} for w<tscanw < t_\text{scan}.

What you would measure. A USB-powered microcontroller board running a PLC-style loop (read all inputs into variables, run the logic, write outputs, then wait until 10 ms10\ \text{ms} have passed). Feed a digital input from a function generator (0/3.3 V0/3.3\ \text{V} pulses through a 1 kΩ1\ \text{k}\Omega series resistor) and count detected pulses over a minute. Toggle a spare output at each scan start and watch it on a scope: the scan-time jitter is visible directly. Expect the miss rate within a few percent of the prediction.

Hazards and safe setup. Logic-level signals only; set the generator to the board's logic level before connecting; no mains, no real contactors. Real machine control and emergency stops are designed to the machinery-safety standards discussed in Interlocks and Safety PLCs.

Pitfalls

  • Reading physical inputs directly in the middle of the program on platforms that allow it: two rungs can see different values in one scan.
  • Writing the same output in two places: the last write wins, silently.
  • Putting a PID block in the free-running main cycle: its sample time then varies with the program.
  • Using a normally-open stop button: a broken wire then disables Stop without any sign.

Practice

  1. A PLC has a 20 ms20\ \text{ms} scan, a 6 ms6\ \text{ms} input filter and a 2 ms2\ \text{ms} output delay. Give the worst-case response.
  2. Which fraction of 15 ms15\ \text{ms} pulses does a 20 ms20\ \text{ms} scan miss?
Answer
  1. 6+2×20+2=48 ms6 + 2 \times 20 + 2 = 48\ \text{ms}.
  2. 1−15/20=25 %1 - 15/20 = 25\,\%.

Test yourself

In a PLC scan, the program reads inputs from

  1. the physical terminals at the moment each rung runs
  2. the input process image captured at the start of the scan
  3. the HMI
  4. the output image

Worst-case input-to-output response of a cyclic PLC program is about

  1. one scan
  2. two scans plus input filter and output delays
  3. half a scan
  4. the watchdog time

Why is a stop push-button wired as a normally-closed contact?

  1. it is cheaper
  2. a broken wire then reads as Stop, so the fault is safe
  3. PLC inputs only accept NC contacts
  4. it debounces the button

Where should a PLC run a PID block?

  1. in the free-running main cycle
  2. in a cyclic interrupt task with a fixed interval
  3. only in the HMI
  4. in a hardware event task triggered by the setpoint