Industrial automation: PLCs, Grafcet and ladder

← Robot list · The basics

How the machines of a factory are controlled: what a PLC is and how its scan cycle works, wiring 24 V sensors and stop buttons, ladder logic and the latch, memories and edges, timers and counters, describing a sequence with a Grafcet and turning it into a program, the brands and their software, safety, 4–20 mA signals and commissioning. Every idea has a live lab, and the course ends on six real installations to program.

How to use this course

Each lesson gives the idea in one sentence, then the wiring or the program with real addresses (Siemens, Schneider, Omron, Mitsubishi, Allen-Bradley), a worked example from a real machine, and a lab: press the buttons, cut a wire, change the cycle time, and watch what the PLC does. Then do the exercises. Prerequisite: the electronics course is useful (voltage, current, a switch), nothing else. When you finish, the automation projects page lets you program six complete installations.

1

The PLC: an industrial computer that never stops

25 min
You will learn

what a programmable logic controller (PLC) is and why factories use it rather than a PC or an Arduino, its parts (power supply, CPU, input and output modules), the scan cycle and the process image, the cycle time and the response time, and the main brands you will meet.

In one sentence

A PLC reads its sensors, runs its program and drives its actuators again and again, every few milliseconds, for years, in a dusty and electrically noisy cabinet.

1.1 Why not a PC or an Arduino?

PLCArduinoPC
Inputs and outputs24 V DC isolated, 0.5–2 A outputs, screw terminals5 V, 20 mA per pin, fragilenone: needs I/O cards
Environment0–55 °C, vibrations, EMC tested (IEC 61131-2)lab benchoffice
Behaviourdeterministic cycle, restarts by itself after a power cutloop(), no diagnosticsOS updates, unpredictable delays
Life and support10–20 years, spare parts, standard languageshobby3–5 years

The PLC was invented in 1968 for General Motors (the Modicon 084, by Dick Morley) to replace cabinets full of relays: changing the production meant rewiring hundreds of relays, while a PLC only needs a new program. That is why its first language, ladder, looks like a relay drawing.

1.2 The parts of a PLC

  • Compact PLC (Siemens S7-1200, Schneider M221, Omron CP2E, Allen-Bradley Micro850, Mitsubishi FX5U): CPU and 14 to 40 I/O in one box, for a machine.
  • Modular PLC (S7-1500, Modicon M580, ControlLogix): a rack of cards, hundreds of I/O, remote I/O on PROFINET or EtherNet/IP, for a line or a plant.
  • Logic module (Siemens LOGO!, Schneider Zelio): 8 inputs, 4 outputs, a small screen, for a gate, lights or a pump.

1.3 The scan cycle and the process image

The CPU does not read a sensor in the middle of the program. At the start of each cycle it copies all the inputs into a table, the process image of the inputs (PII). The program works only on that copy, from the first rung to the last, and writes into the process image of the outputs (PIQ). At the end of the cycle the PIQ is copied to the real outputs. Then it starts again.

Two consequences. First, during one cycle an input never changes value, so the program sees a coherent picture. Second, the PLC is blind between two reads: a pulse shorter than the cycle can be missed, and the reaction to an input can take up to two cycles.

response time (worst case) ≈ input filter + 2 × cycle time + output delay

Worked example

An S7-1200 runs a 6 ms cycle, its inputs filter for 6.4 ms (factory setting) and a relay output closes in 10 ms. Worst case: 6.4 + 2 × 6 + 10 = 28.4 ms. A part on a conveyor at 0.5 m/s moves 14 mm in that time: fine for stopping on a stop plate, too slow to cut it at ± 1 mm. For that you use a fast counter (HSC), a hardware interrupt or a cam module, which do not wait for the cycle.

A watchdog checks the cycle: if one cycle lasts longer than its limit (150 ms by default on an S7-1200), for example because of an endless loop, the CPU goes to STOP and sets the outputs to 0. A PLC also has the modes RUN and STOP, and LEDs RUN, ERROR and MAINT that are the first thing you look at in front of a stopped machine.

The essentials
  • A PLC is a rugged computer with 24 V isolated I/O, made to run the same cycle for years.
  • Cycle: read the inputs into the image, run the program, write the outputs.
  • A pulse shorter than the cycle can be missed; the response can take two cycles.
  • Fast events: fast counter, interrupt, or a faster task, not the main cycle.

Key terms

  • PLC (API in French)
  • CPU, I/O module, rack
  • compact, modular, logic module
  • scan cycle, cycle time
  • process image (PII, PIQ)
  • response time
  • watchdog, RUN / STOP
  • fast counter (HSC), interrupt

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

In which order does a PLC run its cycle?

  1. read inputs → run the program → write outputs
  2. run the program → read inputs → write outputs
  3. each input is read when the program needs it
  4. write outputs → run the program → read inputs

Solution

Rule used the process image is filled at the start of the cycle and copied out at the end lesson 1 — 1.3 The scan cycle

  1. The inputs are copied into the PII.
  2. The program uses only that copy and writes the PIQ.
  3. The PIQ is copied to the outputs.

Answer A

Level 2 · Intermediate2

Cycle time 8 ms, input filter 3 ms, transistor output 0.1 ms. Worst-case response time, in ms?

Solution

Rule used filter + 2 × cycle + output delay lesson 1 — 1.3 (formula)

  1. The input changes just after a read: it waits almost one cycle to be read, then one more cycle to be written.
  2. 3 + 2 × 8 + 0.1 = 19.1 ms.

Answer 19.1 ms

Level 3 · Professional3

A cam gives a 4 ms pulse every 50 ms. The cycle time is 10 ms. Which solution is right?

  1. Wire the cam to a fast counter (HSC) or a hardware interrupt input
  2. Increase the input filter to 20 ms
  3. Use a rising edge –|P|– in the main program
  4. Nothing: the PLC sees every pulse

Solution

Rule used a pulse shorter than the cycle can fall between two reads lesson 1 — 1.3 and the worked example

  1. 4 ms < 10 ms: some pulses are never in the image.
  2. An edge only detects what was read: it does not help. A longer filter would erase the pulse.
  3. A fast counter counts in hardware, an interrupt runs a small program at once.

Answer A

Check yourself
  1. In what order does a PLC do the three parts of its cycle?

    Read the inputs into the image, run the program, write the outputs.

  2. Why can a 3 ms pulse be missed by a PLC with a 10 ms cycle?

    Inputs are read only once per cycle; the pulse can start and end between two reads.

  3. What does the watchdog do?

    It stops the CPU (outputs to 0) if a cycle lasts longer than the allowed time.

2

Wiring the inputs and outputs: 24 V, PNP and NPN, NC stops

30 min
You will learn

how a 24 V DC digital input works, sink and source inputs, 3-wire PNP and NPN sensors and how to match them, relay and transistor outputs, why a stop button is always wired normally closed (positive safety), and how to read a terminal plan.

In one sentence

An input sees a 1 when a current of a few milliamps flows through it, from the sensor to the common or the other way; the sensor and the common must therefore be on opposite polarities.

2.1 A digital input

Inside, a digital input is an optocoupler LED with a resistor: about 3 to 7 mA at 24 V. The standard IEC 61131-2 (type 1 and type 3 inputs) says: above about 15 V (11 V for type 3) it is a 1, below 5 V it is a 0, in between the state is not guaranteed. The inputs share a common terminal (1M on Siemens, COM on Schneider, S/S on Mitsubishi).

SensorWhat its output doesCommon of the inputsName of the input
PNP (Europe, most common)switches +24 V to the inputto 0 Vsink (the input takes current in)
NPN (Asia, older machines)switches 0 V to the inputto +24 Vsource (the input gives current out)

Colours of a 3-wire sensor (IEC 60947-5-2): brown = +24 V, blue = 0 V, black = output. Many PLC inputs (S7-1200, FX5U, CP2E) work both ways: it is only the wiring of the common that decides. Mixing PNP and NPN sensors on the same common is impossible: use two groups.

Worked example

Input resistance 4 kΩ, supply 24 V: I = 24 / 4000 = 6 mA. A 2-wire sensor that leaks 1.5 mA when it is off puts 1.5 mA × 4 kΩ = 6 V on the input: above 5 V, in the undefined zone. The input may flicker. Fix: a load resistor in parallel with the input, or a 3-wire sensor.

2.2 Outputs: relay or transistor

Relay outputTransistor output
SwitchesAC or DC, up to 2 A, isolated contact24 V DC only, 0.5 A
Speed≈ 10 ms, about 1 Hz maxµs: PWM, pulse train for a stepper (100 kHz)
Life≈ 100 000 operations at full loadunlimited
Typical usecontactor coils 230 V AC, lampssolenoid valves 24 V, relays, drives

A PLC output never drives a motor directly: it drives the coil of a contactor (KM1), and the contactor switches the 400 V of the motor. A DC coil needs a freewheeling diode (or the module's internal clamp), an AC coil an RC snubber, otherwise the voltage spike at switch-off wears the output.

2.3 Positive safety: stop buttons are NC

A Start button is NO (normally open): pressing it closes the circuit. A Stop button is NC (normally closed): the input is at 1 when all is well, and pressing it opens the circuit. Why? If the wire breaks or the terminal works loose, an NC stop gives a 0, exactly as if it were pressed: the machine stops. An NO stop with a broken wire gives 0 forever, and pressing Stop does nothing. The same rule holds for limit switches of safety, thermal overload contacts (F1, 95-96) and pressure switches: every signal whose loss is dangerous is wired so that its loss means "stop".

On a real machine

Before you wire: power off, padlock the isolator (lockout), check the absence of voltage with a tester. Use ferrules, 0.75–1.5 mm² wires, the colour code of your plant (often dark blue for 24 V DC control, red for AC control), and mark both ends of each wire with the terminal plan.

Wire a real PLC yourself on the wiring bench →

The essentials
  • PNP sensor → common to 0 V (sink input); NPN sensor → common to +24 V (source input).
  • Brown +24 V, blue 0 V, black output.
  • Relay outputs: AC, slow, wear; transistor outputs: DC, fast, last forever.
  • Stop buttons and safety contacts are NC: a broken wire must stop the machine.

Key terms

  • digital input (DI)
  • common (1M, COM, S/S)
  • sink, source
  • PNP, NPN sensor
  • relay, transistor output
  • contactor, coil
  • freewheeling diode, RC snubber
  • NO, NC contact
  • positive safety

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

You wire a PNP sensor. Where does the common 1M of the inputs go?

  1. to 0 V
  2. to +24 V
  3. to the earth (PE)
  4. it stays unconnected

Solution

Rule used the sensor and the common must be on opposite polarities lesson 2 — 2.1 A digital input

  1. A PNP output gives +24 V when active.
  2. For a current to flow through the input, the other side must be at 0 V.

Answer A: 1M to 0 V (sink input)

Level 2 · Intermediate2

An input has a resistance of 4.7 kΩ under 24 V. What current does it draw, in mA?

Solution

Rule used Ohm's law I = U / R lesson 2 — 2.1 (worked example)

  1. 24 / 4700 = 0.00511 A.
  2. = 5.1 mA, in the usual 3–7 mA range.

Answer ≈ 5.1 mA

Level 2 · Intermediate3

Why is the thermal overload contact F1 (95-96) wired NC to the PLC?

  1. so that a broken wire is seen as a fault and stops the motor
  2. because NO contacts do not exist on overload relays
  3. to save an input
  4. to make the program simpler

Solution

Rule used positive safety: the loss of a signal must mean "stop" lesson 2 — 2.3 Positive safety

  1. NC: input = 1 when all is well.
  2. Trip OR broken wire → 0 → the program stops the motor.

Answer A

Check yourself
  1. A PNP sensor is wired to an input whose common goes to +24 V. What does the input see?

    Always 0: both sides are at +24 V when the sensor is on, so no current flows.

  2. Why must a PLC output not switch the motor directly?

    It switches 0.5–2 A at 24 V or 230 V; a motor needs 400 V and much more current: the output drives a contactor coil.

  3. What happens if the wire of an NO stop button breaks?

    Nothing visible, but pressing Stop no longer works: a hidden danger.

3

Ladder logic: contacts, coils and the latch

30 min
You will learn

how a ladder rung is read (power flows from the left rail to the right one), NO and NC contacts, series = AND and parallel = OR, coils, the classic start/stop latch, why the NC stop button is programmed with an NO contact, and the rule "one coil per output".

In one sentence

A ladder rung is an electrical drawing of a logic equation: contacts in series make an AND, contacts in parallel make an OR, and the coil at the right takes the result.

3.1 The symbols

A contact does not test a button, it tests a bit of memory. An NO contact –| |– passes when the bit is 1; an NC contact –|/|– passes when the bit is 0. A coil –( )– writes 1 in its bit if power reaches it, 0 otherwise, at every cycle.

LogicLadderEquationStructured text
ANDtwo contacts in seriesQ = a · bQ := a AND b;
ORtwo contacts in parallelQ = a + bQ := a OR b;
NOTone NC contactQ = /aQ := NOT a;
Exclusive ORa · /b in parallel with /a · bQ = a ⊕ bQ := a XOR b;

3.2 The start/stop latch (self-holding)

A Start button is only pressed for a moment, but the motor must keep running. The trick of relay cabinets: put a contact of the contactor itself in parallel with Start. Once KM1 is on, its own contact keeps the rung alive. The Stop contact in series breaks it.

KM1 = (S1 + KM1) · S0   with S0 wired NC: Stop has priority

The classic trap: S0 is wired NC, so its input bit I0.1 is 1 when nobody touches it. In the program you must therefore use an NO contact on I0.1: it passes while the bit is 1 (all is well) and opens when Stop is pressed (bit 0). Drawing an NC contact "because the button is NC" gives a motor that never starts. Think "bit", never "button".

// the same latch in structured text (IEC 61131-3)
"KM1" := ("S1_Start" OR "KM1") AND "S0_Stop";   // S0_Stop = 1 when not pressed (NC)
"F1_Overload" in series too: "KM1" := ("S1_Start" OR "KM1") AND "S0_Stop" AND "F1_OK";

3.3 The rules that avoid bugs

  1. One coil per output. If Q0.0 is written by two rungs, only the last one counts (the image is copied at the end of the cycle): the first rung seems dead. Combine the conditions in one rung, or use Set/Reset (lesson 4).
  2. The program runs from top to bottom. A bit written on rung 5 is already new for rung 6, but rung 4 sees it only at the next cycle.
  3. Interlock both directions in software AND in hardware. Forward KM1 and reverse KM2 of a motor: /KM2 in series with KM1, /KM1 in series with KM2, plus the NC auxiliary contacts in the coil wiring, because a welded contactor is invisible to the program.
Worked example

A press runs only if both hands press (S1 AND S2) and the guard is closed (B1), or if the setter key is in "jog" (S3) and the guard is closed. Equation: Q = B1 · (S1 · S2 + S3). Ladder: B1 in series with a parallel block {S1–S2 in series} ∥ {S3}. (A real two-hand control must also check that both hands press within 0.5 s, ISO 13851: done by a safety module, not by this rung.)

The essentials
  • Contacts test bits: NO passes on 1, NC passes on 0.
  • Series = AND, parallel = OR, the coil takes the result at every cycle.
  • Latch: KM1 = (Start + KM1) · Stop, Stop wired NC and programmed with an NO contact.
  • One coil per output; interlock in software and in hardware.

Key terms

  • rung, rail, power flow
  • NO contact, NC contact
  • coil
  • series (AND), parallel (OR)
  • latch, self-holding
  • interlock
  • double coil

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

The Stop button is wired NC on I0.1. Which contact do you draw in the latch rung?

  1. an NO contact –| |– on I0.1
  2. an NC contact –|/|– on I0.1
  3. a P edge on I0.1
  4. no contact: the wiring is enough

Solution

Rule used a contact tests a bit, not a button lesson 3 — 3.2 The trap

  1. Not pressed: the NC button is closed → I0.1 = 1.
  2. We want the rung to pass when I0.1 = 1: NO contact.

Answer A

Level 2 · Intermediate2

Q = B1 · (S1 · S2 + S3) with B1 = 1, S1 = 1, S2 = 0, S3 = 0. What is Q (0 or 1)?

Solution

Rule used series = AND, parallel = OR lesson 3 — 3.3 (worked example)

  1. S1 · S2 = 1 · 0 = 0.
  2. 0 + S3 = 0.
  3. B1 · 0 = 0: one hand is not enough.

Answer Q = 0

Level 3 · Professional3

Q0.0 is a coil on rung 3 (condition true) and on rung 8 (condition false). What is the output at the end of the cycle?

  1. 0: rung 8 wrote last
  2. 1: rung 3 was true
  3. it flickers at half the cycle frequency
  4. the PLC goes to STOP

Solution

Rule used one coil per output: the last write wins lesson 3 — 3.3 Rule 1

  1. Rung 3 writes 1 into the image.
  2. Rung 8 overwrites it with 0.
  3. The image (0) is copied to the output.

Answer A: fix it with one rung Q0.0 = cond3 + cond8

Check yourself
  1. The Stop button is wired NC on I0.1. Which contact do you use in the program?

    An NO contact on I0.1: the bit is 1 while nobody presses.

  2. Start and Stop are pressed together on KM1 = (S1 + KM1) · S0. What happens?

    The motor stays off: S0 in series has priority.

  3. Q0.0 is a coil on rung 2 and on rung 7. Which one wins?

    Rung 7, the last one written before the outputs are copied.

4

Memories, Set/Reset and edges

25 min
You will learn

internal memory bits and words, Set and Reset coils and the SR/RS blocks (which input wins), rising and falling edges (R_TRIG, F_TRIG, the P and N contacts) and why counting without an edge counts cycles instead of parts, and retentive memory after a power cut.

In one sentence

A Set coil writes 1 and leaves it, a Reset coil writes 0 and leaves it, and an edge is true for exactly one cycle when a signal changes.

4.1 Internal memory

BrandBitWord (16 bits)Remark
Siemens%M10.3%MW20or tags in a data block (DB)
Schneider%M5%MW12
OmronW0.03D100W = work bits
MitsubishiM10D100
Allen-Bradleya BOOL tagan INT tagtags by name only

Some memory is retentive: it keeps its value through a power cut (a counter of parts produced, a recipe). The rest restarts at 0. On a Siemens you choose it per tag ("Retain"), on a Mitsubishi by range (M500 and above on an FX). Forgetting it is a classic: after a weekend power cut, the counter of the day is gone.

4.2 Set, Reset and who wins

–(S)– writes 1 when its rung is true and does nothing otherwise; –(R)– writes 0 when its rung is true. The bit keeps its value between them. When both rungs are true in the same cycle, the last one in the program wins. IEC 61131-3 gives two blocks to make that choice clear:

BlockEquationS = R = 1Typical use
SRQ = S + /R · QQ = 1 (set dominant)an alarm that must not be cleared while the fault is present
RSQ = /R · (S + Q)Q = 0 (reset dominant)a motor: stop wins

4.3 Edges

A bottle stays in front of a sensor for 200 ms; the cycle is 10 ms. The rung "IF B1 THEN count := count + 1" runs 20 times: you count 20 bottles. What you want is the instant B1 goes from 0 to 1: the rising edge. The PLC keeps the value of the previous cycle and compares:

rising edge P = B1 · /B1previous   falling edge N = /B1 · B1previous

// IEC function blocks: one instance per signal (it stores the previous value)
R_Bottle(CLK := B1);          // R_TRIG
IF R_Bottle.Q THEN
    Count := Count + 1;       // once per bottle
END_IF;
F_Release(CLK := S1);         // F_TRIG: true one cycle when S1 is released

In Siemens ladder the edge is the contact –|P|– with its own memory bit (the "edge bit"), and each edge needs a different one: reusing the same edge bit for two signals is a famous bug. Schneider uses –|P|– too, Mitsubishi LDP / PLS, Omron @ (differentiated up), Allen-Bradley ONS (one-shot).

Worked example

One button to start and stop a light (toggle, "télérupteur"): on each rising edge of S1, invert the lamp. In ST: R1(CLK := S1); IF R1.Q THEN Lamp := NOT Lamp; END_IF;. Without the edge, the lamp would flip every cycle as long as the button is held: it would end up on or off at random.

The essentials
  • Memory bits and words: %M / M / W / D depending on the brand; retentive ones survive a power cut.
  • Set and Reset keep the value; if both are true, the last one in the program wins, or choose SR (set wins) or RS (reset wins).
  • An edge lasts one cycle: always count and toggle on edges.

Key terms

  • memory bit, memory word
  • retentive memory
  • Set, Reset coil
  • SR, RS bistable
  • rising edge, falling edge
  • R_TRIG, F_TRIG, one-shot
  • toggle (impulse relay)

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

On an SR block (set dominant), S = 1 and R = 1. What is Q?

Solution

Rule used SR: Q = S + /R · Q lesson 4 — 4.2 Set, Reset

  1. S = 1, so Q = 1 whatever R.

Answer Q = 1

Level 2 · Intermediate2

A box stays 240 ms in front of a sensor, cycle time 6 ms. A rung adds 1 to a counter at every cycle where the sensor is 1. How many counts for one box?

Solution

Rule used without an edge, you count cycles lesson 4 — 4.3 Edges

  1. 240 / 6 = 40 cycles with the sensor at 1.
  2. With R_TRIG: 1.

Answer 40 (instead of 1)

Level 2 · Intermediate3

Which block makes a "toggle" light (one button: on, then off)?

  1. R_TRIG, then Lamp := NOT Lamp on its output
  2. TON with PT = 1 s
  3. an RS block with S = R = button
  4. Lamp := NOT Lamp at every cycle while pressed

Solution

Rule used invert once per press: on the rising edge lesson 4 — 4.3 (worked example)

  1. Without the edge, the lamp inverts every cycle: random result.
  2. RS with S = R = button: reset wins, the lamp never lights.

Answer A

Check yourself
  1. S and R are both 1 on an RS block. What is Q?

    0: reset dominant.

  2. A part stays 150 ms in front of a sensor, cycle 5 ms. How many counts without an edge?

    30 (150 / 5), instead of 1.

  3. Why must each –|P|– contact have its own edge bit?

    The edge bit stores the previous value of one signal; shared by two, it stores a mix and edges are lost or doubled.

5

Timers and counters

30 min
You will learn

the three IEC timers TON (on-delay), TOF (off-delay) and TP (pulse) with their inputs and outputs IN, PT, Q and ET, what each is used for on real machines, the counters CTU, CTD and CTUD, and how to write them on each brand.

In one sentence

A timer turns a duration into a bit, a counter turns a number of edges into a bit; both are function blocks with an instance that keeps their state.

5.1 The three timers

TimerQ becomes 1…Q becomes 0…Used for
TONwhen IN has stayed 1 for PTas soon as IN = 0star-delta changeover after 6 s, filtering a bouncing level float (2 s), a fault confirmed only if it lasts
TOFas soon as IN = 1PT after IN went back to 0a cooling fan that runs 3 min after the motor, stair lights
TPon the rising edge of INafter exactly PT, whatever IN doesa 0.5 s pulse to a solenoid valve, a horn for 3 s

ET (elapsed time) counts from 0 to PT. The type is TIME: T#5s, T#1m30s, T#250ms. Each timer is an instance with its own memory: two motors need two TON, never one shared.

// star-delta start: delta 6 s after the star (S7, Codesys, TwinCAT, CCW)
T_Star(IN := KM1_Line AND NOT KM3_Delta, PT := T#6s);
KM2_Star  := KM1_Line AND NOT T_Star.Q AND NOT KM3_Delta;
KM3_Delta := KM1_Line AND T_Star.Q AND NOT KM2_Star;
BrandHow a 5 s on-delay is written
Siemens S7-1200/1500IEC TON with an instance DB, PT = T#5s
Schneider M221%TM0, type TON, base 1 s, preset 5
Omron CP / CJTIM 0 #50 (base 0.1 s) or TIMX
Mitsubishi FXOUT T0 K50 (T0 counts 100 ms)
Allen-BradleyTON with a TIMER tag, Preset 5000 (ms)

5.2 Counters

CTU (count up) adds 1 on each rising edge of CU; its output Q = (CV ≥ PV); R resets CV to 0. CTD (count down) removes 1 on each edge of CD; LD loads PV; Q = (CV ≤ 0). CTUD does both, for example the places of a car park: up at each entry, down at each exit. The counter takes the edge itself: you give it the raw sensor.

Worked example

Bottles go into boxes of 12. A CTU counts B1 with PV = 12; when Q = 1, the box is full: a TP of 1.5 s drives the conveyor that pushes the box out, and the same Q resets the counter. After 30 bottles: 2 full boxes and CV = 30 − 24 = 6. The total of the day is another CTU, retentive, never reset by the box.

The essentials
  • TON delays the 1, TOF delays the 0, TP gives a fixed pulse on an edge.
  • A TON with an input shorter than PT never switches: a filter.
  • CTU: Q = CV ≥ PV, R resets; CTD: Q = CV ≤ 0, LD loads; CTUD: both.
  • One instance per use, and retentive counters for totals.

Key terms

  • TON, TOF, TP
  • IN, PT, Q, ET
  • TIME literal (T#5s)
  • instance (of a function block)
  • CTU, CTD, CTUD
  • CV, PV, R, LD
  • time base

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

Which timer for a horn that must sound exactly 3 s when a fault appears, even if the fault disappears at once?

  1. TP
  2. TON
  3. TOF
  4. CTU

Solution

Rule used TP: a fixed pulse on the rising edge, whatever IN does after lesson 5 — 5.1 The three timers

  1. TON would wait 3 s before sounding.
  2. TOF would sound while the fault lasts, then 3 s more.

Answer A: TP, PT = T#3s

Level 2 · Intermediate2

A TOF with PT = 90 s drives the fan of a motor. The motor stops at t = 400 s. When does the fan stop, in s?

Solution

Rule used TOF: Q falls PT after IN falls lesson 5 — 5.1

  1. 400 + 90 = 490 s.

Answer 490 s

Level 3 · Professional3

A CTU with PV = 12 counts bottles; its Q resets it (box full). How many does CV show after 50 bottles?

Solution

Rule used CV restarts at 0 after each full box lesson 5 — 5.2 (worked example)

  1. 50 = 4 × 12 + 2.
  2. 4 full boxes, 2 bottles in the current one.

Answer CV = 2

Check yourself
  1. A TON has PT = 5 s; IN stays 1 for 3 s then goes to 0. What does Q do?

    Nothing: it stays 0 (ET went to 3 s, then back to 0).

  2. Which timer for a fan that must run 10 s after the motor stops?

    TOF with PT = 10 s and IN = motor running.

  3. On a Mitsubishi FX, OUT T0 K30: how long is the delay?

    3 s (30 × 100 ms).

6

Grafcet: describing a sequence

35 min
You will learn

the elements of a Grafcet (IEC 60848): steps, transitions, receptivities, actions; the five evolution rules; sequences, OR and AND divergences and convergences; timed receptivities; continuous and stored actions; and how to write the Grafcet of a real machine from its specification.

In one sentence

A Grafcet cuts the life of a machine into steps; a token moves from step to step when the condition written on the transition becomes true, and the active steps decide the outputs.

6.1 The elements

  • Step (a square, numbered): a stable situation. Active or not; we write its state Xn. The initial step (double square) is active at start-up.
  • Action (a rectangle to the right of a step): what is done while the step is active: KM1, "open valve Y2".
  • Transition (a short bar on the link) with its receptivity: a logic condition on inputs, times or steps: dcy · p, ↑b1, 5s/X3 (5 s after X3 became active).

6.2 The five evolution rules

  1. Initial situation: at start-up, only the initial steps are active.
  2. Fireable transition: a transition is enabled when all the steps just before it are active; it is fired when it is enabled AND its receptivity is true.
  3. Firing activates all the following steps and deactivates all the previous ones, at the same time.
  4. Simultaneous firing: transitions fireable at the same time are fired at the same time.
  5. Conflict: a step activated and deactivated at the same time stays active.

6.3 Divergences and convergences

OR divergence (single line): one branch or the other, chosen by the receptivities. Make them exclusive (a and b · /a), otherwise both branches start, which the drawing does not mean. AND divergence (double line): all branches start together (two stations working in parallel); the AND convergence waits until the last step of every branch is active, which is why each branch usually ends with an empty "wait" step.

6.4 Actions

KindWritingMeaning
continuousKM1KM1 = 1 while the step is active (the normal case)
conditionalKM1 if bonly while the step is active AND b
delayed / limitedKM1 delayed 2 sstarts 2 s after the activation
storedKM1 := 1 (on activation)set when the step becomes active, kept until a later step resets it
Worked example

Water tower. Specification: start the pump when the level falls below the low float NB, stop it above the high float NH, never if the thermal relay F1 tripped; alarm if the very high float NTH is reached. Grafcet: step 0 (wait) — transition /NB · F1 — step 1 (KM1) — transition NH + /F1 — back to 0. The alarm is not a step: it is a combinational output H1 = NTH, outside the sequence. This is the first project of the automation page, where it runs on an S7-1200.

A real Grafcet has more than the normal cycle: an initialisation sequence (bring the machine back to its rest position), a production cycle, and the modes and stops (GEMMA: stop requested at end of cycle, emergency stop, manual mode, fault). The good practice is a hierarchy: a safety Grafcet that can force the production Grafcet into its initial step, as the "forcing" of the projects of the automation page.

The essentials
  • Step = situation, transition + receptivity = condition, action = output while active.
  • A transition fires when all previous steps are active AND its receptivity is true.
  • OR divergence: exclusive receptivities. AND divergence: parallel branches, the AND convergence waits for all.
  • Timed receptivity: t/Xn/5s or 5s/Xn.

Key terms

  • step, initial step
  • transition, receptivity
  • action (continuous, stored)
  • evolution rules
  • OR / AND divergence and convergence
  • timed receptivity (5s/X3)
  • forcing, GEMMA

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

When is a transition fired?

  1. when all its previous steps are active AND its receptivity is true
  2. as soon as its receptivity is true
  3. when one of its previous steps is active
  4. at every cycle

Solution

Rule used enabled + receptivity true lesson 6 — 6.2 Rule 2

  1. Enabled = all previous steps active.

Answer A

Level 2 · Intermediate2

An AND divergence starts 3 branches. How many steps are active just after it fires (one step per branch)?

Solution

Rule used rule 3: firing activates all the following steps lesson 6 — 6.3

  1. The first step of each branch becomes active.

Answer 3

Level 3 · Professional3

Step 5 is deactivated by one transition and activated by another, in the same instant. What is it?

  1. active (rule 5)
  2. inactive
  3. it blinks
  4. the Grafcet is wrong and stops

Solution

Rule used rule 5: activation has priority lesson 6 — 6.2 Rule 5

  1. This happens in loops: a step that leads back to itself.

Answer A

Check yourself
  1. Steps 4 and 6 end two branches of an AND divergence, followed by "= 1". When does it fire?

    As soon as 4 AND 6 are both active.

  2. Why write a and b · /a after an OR divergence instead of a and b?

    If a and b are true together, both branches would start; b · /a makes the choice exclusive.

  3. What does 5s/X3 mean?

    True 5 s after step 3 became active (and as long as it stays active).

7

From the Grafcet to the program: ladder, ST and the brands

35 min
You will learn

the systematic translation of a Grafcet into ladder with Set/Reset (initialisation, transitions, actions), the trap of a token crossing two steps in one cycle, the five languages of IEC 61131-3, the same program in structured text, the addressing of each brand, and the software you will use.

In one sentence

Each step becomes a memory bit, each transition becomes a rung "previous steps AND receptivity → Set the next steps, Reset the previous ones", and each output becomes one rung that ORs the steps that drive it.

7.1 The method, in three blocks

  1. Initialisation: on the first cycle (Siemens "FirstScan", Mitsubishi SM402, Omron A200.11, Schneider %S13), Set the initial steps and Reset all the others.
  2. Transitions: for each transition, one rung: X(previous) · receptivity → S X(next), R X(previous).
  3. Actions: at the end, one coil per output: KM1 = X2 + X4. Never Set an output from a step: it would stay on after an emergency stop forces the Grafcet.
// water tower: 2 steps, S7-1200 structured text
IF "FirstScan" THEN  "X0" := TRUE;  "X1" := FALSE;  END_IF;
// transitions
IF "X0" AND NOT "NB" AND "F1" THEN  "X1" := TRUE;  "X0" := FALSE;  END_IF;
IF "X1" AND ("NH" OR NOT "F1") THEN  "X0" := TRUE;  "X1" := FALSE;  END_IF;
// actions
"KM1" := "X1";
"H1"  := "NTH";

The trap: with this method, if the receptivity of the next transition is already true, the token crosses two steps in one cycle (rung 2 activates X1, rung 3 sees X1 at once and moves on). Usually harmless, sometimes a bug (an action that never runs, a loop that turns forever). The strict method computes all the transitions first into bits (T1, T2…) and only then does the Set/Reset; the projects of the automation page use the simple method and their order of rungs.

7.2 The five languages of IEC 61131-3

LanguageLooks likeBest for
LD — Ladder diagramrelay drawinglogic, interlocks, maintenance staff can read it online
FBD — Function block diagramlogic gates and blocks wired togetheranalog, regulation, process industry
ST — Structured textPascal: IF, CASE, FORcalculations, loops, recipes, state machines
SFC — Sequential function chartthe Grafcet, run by the PLCsequences (S7-GRAPH, Codesys SFC)
IL — Instruction listassemblerremoved from the standard in 2013 (3rd edition)

7.3 Addresses and software of each brand

BrandInputOutputSoftware
Siemens S7-1200/1500%I0.0%Q0.0TIA Portal (STEP 7)
Siemens LOGO!I1Q1LOGO!Soft Comfort
Schneider M221 / M241%I0.0%Q0.0EcoStruxure Machine Expert
Omron CP2E / NX0.00100.00CX-Programmer, Sysmac Studio
Mitsubishi FX5UX0 … X7, X10 (octal!)Y0GX Works3
Allen-Bradley Micro850_IO_EM_DI_00_IO_EM_DO_00Connected Components Workbench
Allen-Bradley ControlLogixLocal:1:I.Data.0Local:2:O.Data.0Studio 5000 Logix Designer
Beckhoff, Wago, Codesysa variable mapped AT %IX0.0%QX0.0TwinCAT, e!COCKPIT, Codesys

Always work with symbols (tag names: "S1_Start", "KM1_Pump") rather than raw addresses: the program reads like the specification, and if a wire moves to another terminal you change one line of the tag table. Mitsubishi numbers X and Y in octal: after X7 comes X10, so X12 is the 11th input. A classic of commissioning.

Worked example

The same latch in four brands. Siemens: "KM1" := ("S1" OR "KM1") AND "S0";. Mitsubishi ladder: LD X0 / OR Y0 / AND X1 / OUT Y0. Omron: LD 0.00 / OR 100.00 / AND 0.01 / OUT 100.00. Allen-Bradley: XIC(S1) in parallel with XIC(KM1), then XIC(S0) OTE(KM1). Same logic, four dialects: once you think in bits and rungs, you can read them all.

Now program six real installations: fill the blanks of their ladder and run them →

The essentials
  • Grafcet → ladder: initialisation, one rung per transition (S next, R previous), one coil per output.
  • Outputs are combinational on the steps; never Set an output from a step.
  • Five languages: LD, FBD, ST, SFC (and IL, now removed).
  • Program with symbols; know your brand's addresses (Mitsubishi in octal).

Key terms

  • first scan bit
  • step bit (X1)
  • IEC 61131-3
  • LD, FBD, ST, SFC, IL
  • tag, symbol table
  • octal addressing
  • TIA Portal, GX Works3, Studio 5000

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

Which rung translates the transition X3 → X4 with receptivity "a1"?

  1. X3 · a1 → S X4, R X3
  2. a1 → S X4
  3. X3 · a1 → X4 (normal coil)
  4. X4 · a1 → S X3, R X4

Solution

Rule used previous step AND receptivity → Set next, Reset previous lesson 7 — 7.1 The method

  1. Without X3 the transition is not enabled.
  2. A normal coil would drop X4 as soon as a1 falls.

Answer A

Level 2 · Intermediate2

On a Mitsubishi FX, X0 is the 1st input. Which input number is X14 (counting from 1)?

Solution

Rule used X and Y are numbered in octal lesson 7 — 7.3

  1. 14 in octal = 1 × 8 + 4 = 12 in decimal.
  2. X0 is the 1st, so X14 (12) is the 13th.

Answer the 13th input

Level 2 · Intermediate3

Which IEC 61131-3 language would you choose to compute the average of 20 measurements in a loop?

  1. ST (structured text)
  2. LD (ladder)
  3. SFC
  4. IL

Solution

Rule used ST for calculations and loops lesson 7 — 7.2 The five languages

  1. FOR i := 1 TO 20 DO sum := sum + m[i]; END_FOR; avg := sum / 20;

Answer A

Check yourself
  1. Write the rung for the transition X2 → X3 with receptivity b1.

    X2 · b1 → S X3, R X2.

  2. KM1 is driven by steps 2 and 5. Write its rung.

    KM1 = X2 + X5 (two contacts in parallel, one coil).

  3. Which IEC 61131-3 language was removed in 2013?

    IL, instruction list.

8

Safety, analog signals and commissioning

35 min
You will learn

why the emergency stop is not in the standard program, stop categories, safety relays and safety PLCs, ISO 13849 performance levels; 4–20 mA and 0–10 V signals, the raw value of the card and the scaling, broken-wire detection; and how to commission and diagnose a machine.

In one sentence

The standard PLC runs the machine, but safety is done by certified hardware that cuts the power whatever the program does; analog signals arrive as raw numbers that the program must scale and check.

8.1 The emergency stop

A standard PLC can crash, be in STOP, be programmed wrong, or have a welded output transistor. So the emergency stop (red mushroom on a yellow background, ISO 13850) must remove the energy by hardware: its two NC channels go to a safety relay (Pilz PNOZ, Phoenix PSR, Schneider XPS, Siemens 3SK) that opens two contactors in series. The PLC only reads a contact to know that the E-stop was pressed and to show it on the HMI.

Stop category (IEC 60204-1)What happensAllowed for E-stop?
0immediate removal of power: the motor coastsyes
1controlled braking by the drive, then removal of power (STO)yes
2controlled stop, power kept (holding torque)no

ISO 13849-1 asks for a required performance level PLr (a to e) from a risk analysis (severity, exposure, possibility of avoiding), then checks that the chain (sensor, logic, actuator) reaches it: architecture (category B, 1, 2, 3, 4), reliability of the parts (MTTFD), diagnostics (DC). An E-stop with two channels, a safety relay and two monitored contactors typically reaches category 3 or 4, PL d or e. On big machines a safety PLC (S7-1500F, GuardLogix, Pilz PNOZmulti) runs the safety logic in a separate, certified program, with a signature checked at every change.

On a real machine

Resetting the E-stop must never restart the machine by itself: release the mushroom, press the blue reset button (it arms the safety relay), then press Start. Test the E-stop at every commissioning and at the interval given by the risk analysis, and write the result in the logbook.

8.2 Analog signals: 4–20 mA

A pressure, level or temperature transmitter sends a current: 4 mA at the bottom of its range, 20 mA at the top. A current does not drop along a 300 m cable, and noise hardly changes it. The 4 mA "live zero" lets the PLC tell "0 bar" (4 mA) from "broken cable" (0 mA). The NAMUR NE 43 recommendation: below 3.6 mA or above 21 mA, the measure is a fault.

value = low + (raw − rawmin) / (rawmax − rawmin) × (high − low)

The card converts the current into a raw integer. On Siemens S7, 4 mA → 0 and 20 mA → 27 648 (values up to 32 511 mean over range, 32 767 an overflow or a broken wire when diagnostics are on); in TIA Portal you scale with NORM_X then SCALE_X. Schneider and Omron let you set the range in the card configuration, Mitsubishi and Allen-Bradley use 0–32 000 or engineering units depending on the module.

Worked example

A 0–10 bar transmitter reads 12 mA: (12 − 4) / 16 = 0.5 → 5 bar. On an S7-1200 the raw value is 13 824. Another reading: raw 20 736 → 20 736 / 27 648 = 0.75 → 7.5 bar (16 mA). If the raw value jumps to 32 767, do not compute anything: raise the alarm "transmitter PT101 broken wire" and put the regulation in a safe state.

8.3 Commissioning and diagnostics

  1. Simulate the program first (PLCSIM, GX Simulator, Codesys simulation, or the automation page of this site).
  2. Check the I/O point by point, power on, outputs not yet connected to the power: press each button, trip each sensor and see the right LED and the right tag change; force each output (force table) and see the right contactor pull in. Tick the I/O list line by line.
  3. Test the safety functions (E-stop, guards, overloads) before any motion.
  4. Run the cycle step by step, then in automatic, then with faults on purpose; this is the FAT (factory acceptance test) at the builder and the SAT (site acceptance test) at the customer.

In front of a stopped machine: look at the LEDs of the PLC (RUN, ERROR), read the diagnostic buffer, go online and look at which step of the Grafcet is active and which receptivity is missing. Nine times out of ten it is a sensor that did not switch (badly adjusted, dirty, a cable crushed), not the program. Never force an output to get a machine running without understanding why, and remove every force before leaving.

The essentials
  • The E-stop removes the energy by hardware (safety relay or safety PLC, two channels, monitored contactors); the standard PLC only reads it.
  • Stop categories 0 and 1 for the E-stop; ISO 13849 gives the required PL.
  • 4–20 mA: live zero, below 3.6 mA = broken wire; scale the raw value (S7: 0…27 648).
  • Commissioning: simulate, check I/O point by point, test safety, then the cycle; remove all forces.

Key terms

  • emergency stop (E-stop)
  • safety relay, safety PLC
  • stop category 0, 1, 2
  • STO (safe torque off)
  • performance level (PL), ISO 13849
  • 4–20 mA, live zero
  • raw value, scaling
  • force table, diagnostic buffer
  • FAT, SAT

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

A 0–10 bar transmitter sends 12 mA. What is the pressure, in bar?

Solution

Rule used value = (I − 4) / 16 × range lesson 8 — 8.2

  1. (12 − 4) / 16 = 0.5.
  2. 0.5 × 10 = 5 bar.

Answer 5 bar

Level 2 · Intermediate2

On an S7-1200, a 0–6 m level transmitter (4–20 mA) gives a raw value of 9216. What is the level, in m?

Solution

Rule used value = raw / 27 648 × range lesson 8 — 8.2 (worked example)

  1. 9216 / 27 648 = 0.333.
  2. 0.333 × 6 = 2 m (and the current is 4 + 0.333 × 16 = 9.33 mA).

Answer 2 m

Level 2 · Intermediate3

Which stop category is NOT allowed for an emergency stop?

  1. category 2
  2. category 0
  3. category 1
  4. all are allowed

Solution

Rule used category 2 keeps the power on the motor lesson 8 — 8.1 (table)

  1. 0: immediate cut. 1: braking then cut. Both remove the energy.
  2. 2: power kept: not an emergency stop.

Answer A

Check yourself
  1. Why is the E-stop not wired only to a PLC input?

    A standard PLC can fail or be wrong; the energy must be removed by certified hardware.

  2. A 0–100 °C transmitter gives 8 mA. What temperature?

    (8 − 4) / 16 × 100 = 25 °C.

  3. A machine is stopped. What do you check first?

    The LEDs and the diagnostics of the PLC, then online, the active step and the missing receptivity (usually a sensor).

Glossary

All the words of the course in one place.

TermMeaning
PLC (programmable controller)Programmable logic controller: a rugged computer with isolated 24 V inputs and outputs that runs a cyclic program.
Scan cycleRead the inputs, run the program, write the outputs, again and again (1 to 20 ms).
Process imageThe copy of the inputs (and outputs) that the program uses during one cycle.
Sink / source inputInput whose common is at 0 V (for PNP sensors) or at +24 V (for NPN sensors).
PNP / NPN sensor3-wire sensor whose output switches +24 V (PNP) or 0 V (NPN).
Positive safetyWiring stops and safety contacts NC so that a broken wire stops the machine.
ContactorAn electrically driven switch for the power of a motor; its coil is driven by a PLC output.
Ladder (LD)Graphical language that looks like a relay drawing: contacts in series (AND) and in parallel (OR) drive coils.
Latch (self-holding)KM1 = (Start + KM1) · Stop: the output keeps itself on after Start is released.
Set / ResetCoils that write 1 or 0 and keep it; SR = set wins, RS = reset wins.
EdgeTrue during one cycle when a signal goes from 0 to 1 (rising, R_TRIG) or 1 to 0 (falling, F_TRIG).
TON, TOF, TPOn-delay, off-delay and pulse timers of IEC 61131-3.
CTU, CTDUp and down counters: Q = CV ≥ PV, or CV ≤ 0.
GrafcetGraphical description of a sequence (IEC 60848): steps, transitions, receptivities, actions.
ReceptivityThe logic condition written on a transition.
AND / OR divergenceParallel branches that all start (double line), or a choice of one branch (single line).
IEC 61131-3The standard of PLC languages: LD, FBD, ST, SFC (and IL, removed).
Structured text (ST)Textual PLC language like Pascal: IF, CASE, FOR, :=.
Safety relayCertified module that checks a two-channel E-stop and opens the power contactors.
Performance level (PL)Reliability class a to e of a safety function (ISO 13849-1).
4–20 mAAnalog current loop: 4 mA = bottom of range, 20 mA = top; below 3.6 mA = fault.
ScalingTurning the raw value of an analog card into a physical value (bar, m, °C).
ForcingImposing the value of an I/O from the programming software, for tests.

Sources and references

This course was written from these books, papers, standards and documentation. They are also the best way to go further.

  1. IEC 61131-3:2013, Programmable controllers — Part 3: Programming languages (LD, FBD, ST, SFC; timers, counters, edges); IEC 61131-2:2017 (digital input types). used for: the languages, timers, counters and edges
  2. IEC 60848:2013, GRAFCET specification language for sequential function charts. used for: Grafcet: elements and evolution rules
  3. ISO 13849-1:2023, Safety of machinery — Safety-related parts of control systems; IEC 60204-1:2016 (electrical equipment of machines, stop categories); ISO 13850:2015 (emergency stop). used for: emergency stop, stop categories and performance levels
  4. NAMUR NE 43, Standardization of the signal level for the failure information of digital transmitters (4–20 mA fault levels). used for: 4–20 mA fault levels
  5. Siemens, S7-1200 Programmable controller — System Manual (scan cycle, process image, input filters, analog value representation 0–27 648). used for: scan cycle, process image and analog values on a real PLC

You can now read, wire and program a machine!

Next: program six real installations (water tower, transfer switch, compressor, lift station, traffic lights, car park) on the automation page, then the communication course to link PLCs, drives and sensors with Modbus and industrial networks.

Go to the automation projects → Home page