Chapter 49

PLC

A PLC is a small, rugged computer that controls nearly all automated machines: it reads inputs from buttons and sensors, makes decisions based on a program, and activates motors, valves, and indicator lights. In this chapter, we’ll explore its design, how it works, how it’s connected, and how to program it using ladder logic—from the simplest contacts all the way to sequences using Grafcet—with plenty of diagrams and worked examples. Finally, we’ll take a look at the PLC inside every CNC machine.

49.1 From Relay Logic to PLC

An automatic control system, whether small or large, always does the same thing: it monitors input signals (buttons, limit switches, sensors), combines them according to a certain logic, and controls outputs (motor contactors, solenoid valves, indicator lights). Until the late 1960s, this logic was implemented solely using relays, contactors, and electromechanical timers connected to each other by wires: this is known as hardwired logic. The start-stop circuit with self-holding that you saw in Chapter 44 is an example of hardwired logic.

Hardwired logic works well and is still used for small circuits and safety circuits, but it has one major drawback: the logic is embedded in the wires. To change the machine’s cycle, you have to shut it down, disconnect it, and reconnect the wires; a control panel with a hundred relays takes up an entire cabinet, it wears out (the contacts wear down), and finding a fault means tracing the wires one by one with a tester.

In 1968, the American automotive industry—which was changing its systems with every new model—asked manufacturers for an electronic device that would replace relay cabinets, could be reprogrammed quickly, and that electricians could understand without having to become computer scientists. This led to the creation of the PLC, or Programmable Logic Controller. With a PLC, wires run only from the buttons and sensors to the inputs and from the outputs to the actuators; all the logic is contained in a program stored in memory. This is programmable logic.

hardwired logicprogrammable logicL+0 VS2S1K1K1K1H1The logic is in the files:To change it, you have to rewire itPLCprogramin memoryI0.0S1RunI0.1S2stopQ0.0K1Q0.1H1The files remain the same:To change the cycle, change the program
Figure 49.1 · On the left is a horizontal relay drawing for a start-stop circuit: S2 is the stop switch, S1 is the start switch, K1 is the relay with its self-holding contact, and H1 is the lamp. On the right is the same control system using a PLC: the wires connect only the buttons and loads; the logic is contained in the program.

To make it easy for electricians to understand, the first PLC language was drawn just like relay drawings: two vertical power supply lines and, in between, horizontal rows with contacts and coils. This is the ladder diagram, which we’ll cover starting in section 49.6.

AppearanceHardwired Logic (Relays)Programmable Logic Controller (PLC)
Where's the logic?in the files and relaysin the program stored in memory
Change the cyclerewire the control panelchange the program, even in just a few minutes
Timers and Countersone device for everyonehundreds, software only
Dimensionsgrows with complexityalmost fixed; only the input and output modules increase
Usurycontacts that wear out with every maneuverelectronic logic with no moving parts
Diagnosisusing the tester, strand by strandLEDs on the modules and the program's online status
Suitable forSmall circuits and safety featureseverything else

49.2 How a PLC Works

A PLC is a computer designed for the shop floor: it withstands vibrations, dust, electrical interference, and the temperatures found in an electrical panel; it mounts on a DIN rail and operates for years without being shut down. Its components are always the same, whether it’s a compact PLC (all in one enclosure) or a modular PLC (side-by-side modules that are selected one by one).

  • Power supply: It converts 230 V AC from the mains to 24 V DC for the CPU and modules. It is often a separate unit that also powers sensors and actuators.
  • CPU (central processing unit): the processor that executes the program, along with its operating system, clock, and error handling. It has a selector or a RUN/STOP command: in RUN mode, it executes the program; in STOP mode, it halts all outputs.
  • Memory: The program memory is not erased when the PLC is turned off; the data memory contains variables, timers, and counters. Some data can be declared as retained: it is preserved even when the PLC is turned off (for example, the daily piece counter).
  • Digital Input Modules (DI): These channels receive signals that can be either present or absent—usually 0 or 24 V DC—from buttons, limit switches, proximity sensors, and thermal relay contacts. Each channel has an LED that lights up when a signal is present.
  • Digital Output Modules (DO): They turn loads on or off, such as indicator lights, contactor coils, and solenoid valves. The outputs are relay-based o transistor-based (paragraph 49.4).
  • Analog Modules: Analog inputs (AI) measure continuously varying quantities, such as pressure or temperature, which are converted by the transducer into 0–10 V or 4–20 mA (Chapter 47); analog outputs (AO) provide a variable voltage or current, such as the speed reference for an inverter (Chapter 45).
  • Communication: the interface for the programming PC, industrial Ethernet networks, and fieldbuses to communicate with operator panels, inverters, remote modules, and other PLCs.
POWER SUPPLY24 V DCfor CPUsand modulesCPUprocessormemoryprogramdata memoryINPUTinputsdigital16 × 24 VDOdigitaldigitalrelay ortransistorAIanaloganalogAOanaloganalogCOMnetwork,busfieldInternal bus: the CPU reads from and writes to the modules230 V AC networkbuttonssensorslimit switchesindicator lightscontactorssolenoid valvestransducers4–20 mA0–10 Vinvertersvalvesproportionalpaneloperator,PC, networkStatus LED:green = signalpresent
Figure 49.2 · A modular PLC: power supply, CPU with memory, and input, output, and communication modules connected in parallel on the internal bus. Below: what is connected to each module and the direction in which the signal travels.

The inputs are almost always optically isolated: inside the module, the signal turns on a small LED that illuminates a phototransistor. Only light passes between the field and the CPU’s electronics, so any noise or voltage spike on the machine’s wires does not reach the processor.

Example 49.1 · How Many Modules Are Needed?

A machine has 22 input signals and 13 digital outputs. You want to leave a 20% margin for future modifications. The available modules have 16 channels. How many input and output modules are needed?

Inputs with reserve: 22 · 1.20 = 26.4 → 27 channels → 27 / 16 = 1.7 → 2 modules (32 inputs)
Outputs with reserve: 13 · 1.20 = 15.6 → 16 channels → 16 / 16 = 1 module (16 outputs)
2 modules with 16 inputs each and 1 module with 16 outputs; 10 inputs and 3 outputs remain available

49.3 The Scan Cycle

The PLC does not run the program “just once”: it repeats it in a continuous loop—called a scan cycle—hundreds of times per second. Each loop always consists of the same phases.

  • Reading the inputs: The CPU reads the status of all inputs and copies it into a memory area called the input process image. From this point on, throughout the entire cycle, the program uses this snapshot, not the actual terminals.
  • Program Execution: Instructions are executed in order, network by network, from top to bottom, and within each network, from left to right. The results are written to the output image.
  • Writing to the outputs: At the end of the cycle, the output image is copied to the modules, and only then do the relays and transistors change state.
  • Diagnostics and Communication: The CPU performs a self-check, responds to the operator panel and the PC, and then restarts.
Reading the inputsStates copied to the "inputs" imageRunning the programnetwork by network, from top to bottomWriting outputsoutput image copied to the modulesDiagnostics and communicationinternal checks, network, panelOne complete cycle= cycle time tcfrom 1 to a few tens of ms
Figure 49.3 · The scan cycle: reading inputs, executing the program, writing outputs, diagnostics, and communication. Then the cycle starts over.

The time for one complete cycle is the cycle time tc. It depends on the CPU speed and the length of the program: for a typical machine, it ranges from 1 to a few tens of milliseconds. The CPU monitors this using a watchdog: if a cycle lasts longer than a set limit—for example, because the program has entered an infinite loop—the CPU goes into STOP mode and turns off the outputs.

The Practical Consequences of the Cycle

  • A pulse that is too short may be missed: if an input turns on and off between two readings, the program will never detect it.
  • The PLC responds slowly: a change that occurs immediately after a read operation takes almost one cycle to be read and another cycle to reach the output.
  • The order of the rounds matters: a round uses the bits that have already been updated by previous rounds in the same cycle, while the bits from subsequent rounds are still the same as in the previous cycle.
  • Never use the same spool in two nets: The output takes the value of thelast the network that writes it, and the first one becomes useless. It's one of the most common errors made by beginners.
real inputreadingsimage I0.0output Q0.00102030405060 ms missed pulse ≈ 2 cycles later
Figure 49.4 · Cycle time 10 ms; the vertical marks represent the input readings. The pulse from 12 to 17 ms falls between two readings, and the program does not detect it. The signal that rises to 31 ms is read at 40 ms, and the output changes only at 50 ms, at the end of the next cycle.
Maximum response time and minimum pulse
tr,max = tf + 2 · tc + tu
timp = Lv > tc + tf    (basically timp ≥ 2 · tc)
tr,max worst-case response time, in ms · tf input filter delay, in ms · tc cycle time, in ms · tu output delay (relay approx. 10 ms, transistor less than 1 ms) · timp pulse duration, in s · L length of the part as seen by the sensor, in m · v workpiece speed, in m/s
Example 49.2 · The sensor detects a short tab

A sensor counts 4-mm-long tabs as they pass over a conveyor belt at 0.8 m/s. The PLC has a cycle time of 10 ms. Is the count reliable? What length would be required to ensure a pulse lasting at least two cycles?

timp = 0.004 m × 0.8 m/s = 0.005 s = 5 ms
5 ms < 10 ms: The pulse is shorter than one cycle; some tabs will not be counted
L = v · 2 · tc = 0.8 · 2 · 0.010 = 0.016 m = 16 mm
It's not certain: you need tabs that are at least 16 mm long, or a fast count input or an interrupt
Example 49.3 · How long does it take for the valve to move?

An input has a 3-ms filter; the cycle time is 12 ms. What is the maximum response time with a relay output (10 ms) and with a transistor output (0.5 ms)?

relay: tr,max = 3 + 2 × 12 + 10 = 37 ms
transistor: tr,max = 3 + 2 × 12 + 0.5 = 27.5 ms
37 ms with the relay output, 27.5 ms with the transistor output; at 0.8 m/s, the belt travels nearly 30 mm in 37 ms

49.4 Connecting Inputs and Outputs

The 24-volt inputs

The most common input module in Europe operates at 24 V DC and has its common terminal connected to 0 V (terminal M): an input is set to 1 when +24 V is applied to its terminal. A button is therefore connected between +24 V and the input terminal.

  • A NO (normally open) button outputs 0 when at rest and 1 when pressed: this is the case with run buttons.
  • An NC (normally closed) button outputs a 1 when at rest and a 0 when pressed: it is used for stopping, as we will see in section 49.7. The NC contact of the thermal relay is connected in the same way (terminals 95–96).
  • A three-wire PNP sensor has the brown (BN) wire connected to +24 V, the blue (BU) wire to 0 V, and the black (BK) wire to the input: when it detects an object, it connects the black wire to +24 V. For inputs with the common terminal at 0 V, PNP sensors are required; NPN sensors close toward 0 V and require modules with the common terminal at +24 V (Chapter 47).
L+ 24 V DCM 0 VS1Operating NOS2NC stopB1PNPBNBKBUI0.0I0.1I0.2M24 V DC digital input moduleper channel:resistor andoptocouplerAt rest: I0.0 = 0 (S1 open) · I0.1 = 1 (S2 closed) · I0.2 = 1 only if B1 detects the workpiece
Figure 49.5 · 24 V inputs with the common terminal at 0 V: S1 (NO) button on I0.0, S2 (NC) button on I0.1, B1 (three-wire PNP) sensor on I0.2. Terminal M of the module is connected to 0 V.

Outputs: Relays and Transistors

The relay outputs contain a small relay for each channel: the contact is voltage-free, so it can control both AC (230 V AC) and DC loads up to about 2 A. However, they are slow (about 10 ms) and wear out: a contact lasts for a few hundred thousand operations at full load. The transistor outputs operate only on 24 V DC, typically up to 0.5 A per channel, but they are extremely fast and do not wear out. For AC loads, triac outputs are also available.

Typical loads include indicator lights, contactor coils, and solenoid valves. The PLC never directly controls a motor: it controls the contactor coil, and it is the contactor’s power contacts that supply current to the motor (Chapter 45). For a load that requires more current than the output can provide, an interface relay is inserted.

Contactor coils, relays, and solenoid valves are inductive loads: when the output opens, the coil tries to maintain the current and produces a surge of hundreds of volts that can damage the transistor and disrupt the entire control panel. In direct current circuits, a recirculation diode is connected in parallel with the coil, mounted “backward” (cathode toward the + terminal): during operation, it does not conduct; when the circuit is turned off, it provides a closed path for the current in the coil, allowing the energy to discharge without spikes. In AC systems, however, an RC circuit or a varistor is used instead. The diode slows the coil’s discharge slightly, usually without any adverse effects.

relay outputstransistor outputs230 V ACN1LQ0.0Q0.1contactsof the relaysH1 lampKM1CoilL+ 24 V DCM 0 VL+transistorQ1.0Y1solenoid valverecirculationrecirculationWhen the power is turned off, the current flows through the diode
Figure 49.6 · On the left, relay outputs with common terminal 1L powered by 230 V AC: lamp H1 and the coil of contactor KM1. On the right, a 24 V DC transistor output that controls solenoid valve Y1, with the recirculation diode connected in parallel to the coil.
Current drawn by a DC load
I = PU
I: current in A · P: load power (as indicated on the coil or indicator label), in W · U: voltage, in V
Example 49.4 · Is the output group stable?

A group of 8 transistor outputs has a limit of 0.5 A per channel and 2 A in total. Four 4.8-W solenoid valves and two 1.2-W indicator lights, all rated at 24 V DC, are connected and can be turned on simultaneously.

Solenoid valve: I = 4.8 / 24 = 0.20 A < 0.5 A
indicator light: I = 1.2 / 24 = 0.05 A
Total: 4 × 0.20 + 2 × 0.05 = 0.80 + 0.10 = 0.90 A < 2 A
Yes: 0.90 A in total, less than half the group's limit
Example 49.5 · How long does a relay output last?

A solenoid valve activates 6 times per minute, 16 hours a day. The output relay is rated for 300,000 operations with that load (approximate value). How long will it last?

operations per day = 6 × 60 × 16 = 5,760
duration = 300,000 / 5,760 = 52.1 days
About 52 workdays: For a load that switches frequently, a transistor output is typically chosen

49.5 Addresses, Variables, and Languages

The Addresses

Every input, output, or internal bit has a address. In the notation most commonly used in Europe, the letter indicates what it is, and the numbers indicate where it is located: I0.3 is the entrance (Input) of byte 0, bit 3; Q1.0 This is the output of byte 1, bit 0. A byte has 8 bits, numbered from 0 to 7 (Chapter 46): after I0.7 comes I1.0.

  • I: digital inputs, in bits (I0.0), bytes (IB0), or 16-bit words (IW0); analog inputs are read as words (IW64).
  • Q: Digital and analog outputs follow the same rules.
  • M: Internal memory bits (M0.0), which are not associated with any terminals and are used to store intermediate results, such as the auxiliary relays in a control panel.
  • T and C: timers and counters (T1, C1), with their outputs T1.Q and C1.Q.
IB0I0.70bit 7I0.60bit 6I0.50bit 5I0.40bit 4I0.30bit 3I0.21bit 2I0.10bit 1I0.01bit 0IB1I1.7I1.6I1.5I1.4I1.3I1.2I1.1I1.0IW016 bitsIB0 = 0000 0101 in binary = 5: only inputs I0.0 and I0.2 are set to 1.The number after the decimal point ranges from 0 to 7: after I0.7 comes I1.0, not I0.8.
Figure 49.7 · Each input byte contains 8 bits. Two consecutive bytes form a 16-bit word (IW0 = IB0 + IB1).

Not all manufacturers write addresses this way. The IEC 61131-3 standard uses the percent sign: %IX0.0 for an input, %QX0.0 for an output, and %MX0.0 for a flag. Others number the inputs X0, X1… and the outputs Y0, Y1…, sometimes in base 8; still others use the module’s slot and channel. In the PMC of CNC machines (section 49.14), you’ll find the letters X (inputs from the machine), Y (outputs to the machine), F (signals from the CNC to the PMC), G (signals from the PMC to the CNC), and R (internal relays). The concept is always the same; only the notation changes.

The Table of Variables

No one remembers off the top of their head that I0.2 is the pump motor's thermal relay. That's why every program has a table of symbols (or variables): for each address, there is a symbolic name, the data type, and a comment. In the program, you write the name, and the software displays the address next to it.

TypeWhat's InsideValues
BOOLa bit: input, output, flag0 or 1 (FALSE or TRUE)
BYTE, WORDgroups of 8 or 16 bits0 to 255, 0 to 65,535
INT16-bit signed integer (raw analog values, counts)from −32,768 to 32,767
DINT32-bit signed integerapproximately ± 2.1 billion
REALnumbers with a decimal point (pressures, temperatures)about 7 significant digits
TIMEduration, for timersfor example, T#5s, T#500ms
Example 49.6 · The table of variables for a motor

We need to control a pump motor using a start button, a NC stop button, a thermal relay, a run indicator light, and a thermal trip indicator light. Here is the table of variables that we will also use in Example 49.15.

SymbolAddressTypeComment
MARCIAI0.0BOOLS1, NO run button
STOPI0.1BOOLS2, NC stop button (1 = not pressed)
THERMALI0.2BOOLF1, thermal relay contacts 95-96 (1 = everything is OK)
KM1Q0.0BOOLmotor contactor coil
H_MARCIAQ0.1BOOLGreen light, engine running
H_THERMALQ0.2BOOLYellow warning light, thermal protection activated
The comment always explains what status 1 means: for NC contacts, this detail helps prevent errors

The languages of the IEC 61131-3 standard

The international standard IEC 61131-3 defines PLC programming languages so that anyone who has learned one brand can easily adapt to others.

LanguageWhat's it like?When to use
LD · ladderdiagram, contacts, and coils, like a relay diagrambit logic, machines, maintenance: it's the most common in the workshop
FBD · Functional Blocksdiagram, logic gates, and blocks connected by linesthose with a background in electronics, control systems, and process systems
ST · Structured Texttext-based, similar to Pascal, with IF, CASE, and FORcalculations, formulas, data management, algorithms
IL · List of Instructionstext-based, similar to assemblerold programs; the current standard considers them obsolete
SFC · Sequential Function Chartgraph, phases, and transitions (derived from Grafcet)Step cycles: sequences of cylinders, automatic machines
LD · ladderABCLAMPFBD · functional blocks≥1&ABCLAMPThe circle indicates that entry is prohibited CST · Structured TextLAMPADA := (A OR B) AND NOT C;
Figure 49.8 · The same function, LAMP = (A OR B) AND NOT C, written in three languages. The PLC executes all three in the same way.

49.6 The Ladder Circuit: Contacts, Coils, Series and Parallel Connections

A ladder diagram has two vertical lines: the left one acts as the positive terminal, and the right one as the return. Between the two are the networks (in English rung, “rungs”): each one is a row with contacts on the left and one or more coils on the right. Imagine that a “logic current” flows from left to right: if it finds a closed path, it reaches the coil and activates it.

  • NA Contact --| |--: lets the signal pass when the bit above is set to 1.
  • NC Contact --|/|--: let it pass when the bit is set 0. It is negation, the "NOT" of logic (Chapter 46).
  • Coil --( )--: sets its bit to 1 if power is supplied to the network, and to 0 if it is not. The coil resets its bit every scan cycle.
  • Contacts in series they do theAND: It only works if they're all closed. Contacts in parallel they do theOR: It's enough if just one is closed.
💡
NA and NC in the program are not buttons. In ladder logic, “NA” and “NC” do not describe the physical configuration of the button on the machine; they merely indicate whether the contact closes when the bit is 1 or when it is 0. A physical NC button may very well appear in the program as an NA contact, and in fact, this is the rule (paragraph 49.7).
Network 1 · NO contactI0.0PULS_AQ0.0LAMP_1Circuit 2 · NC contactI0.0PULS_AQ0.1LAMP_2Network 3 · Logic = ANDI0.1AI0.2BQ0.2L_ANDNetwork 4 · parallel = ORI0.1AI0.2BQ0.3L_OR
Figure 49.9 · The four basic logic gates. LAMP_1 copies the button, LAMP_2 inverts it, L_AND turns on only when both A and B are on, and L_OR turns on when either A or B is on.
A (I0.1)B (I0.2)Series: A AND BParallel: A OR B
0000
0101
1001
1111

Some rules apply to almost all software: coils are always on the right, no contacts are placed after a coil, and each bit is written with a single coil in a single network. A contact, on the other hand, can be used as many times as you like: it’s not a real contact that wears out; it’s just the reading of a bit.

Example 49.7 · The Coolant Pump

A machine's coolant pump must run when the selector switch is set to AUTO and (the spindle speed is high or the operator presses the MANUAL button), provided that the level in the tank is not too low. The low-level sensor outputs a 1 when the fluid is low.

PUMP_REF = AUTO AND (MANDR_ON OR MANUAL) AND NOT LOW_LEVEL
AND → contacts in series; OR → two contacts in parallel; NOT → NC contact
A single circuit: AUTO in series with the MANDR_ON / MANUAL parallel circuit, in series with the LIV_BASSO NC contact (Figure 49.10)
Circuit 1 · Coolant PumpI0.4AUTOI0.5SPINDLE_ONI0.6MANUALI0.7LOW LEVELQ0.4PUMP_REF
Figure 49.10 · The circuit from Example 49.7. If the level is low (I0.7 = 1), the NC contact opens and the pump does not start, regardless of what happens on the left.

49.7 The self-holding function and the NC stop button

The run button is pressed and released; however, the motor must remain on. As in the wired logic, a contact from the motor itself—the NO contact of KM1—is connected in parallel with the run button. As soon as KM1 turns on, this contact closes and “holds” the power supply even when the button is released: this is the self-holding mechanism. To turn it off, the power supply must be interrupted with a contact in series: the stop contact.

Here’s the point that confuses almost everyone. The stop button on the machine is always an NC button: in the rest position, it is closed and sends 24 V to the input, so in the rest position I0.1 = 1; when pressed, the circuit opens and I0.1 goes to 0. In the program, we want the power to be supplied when the stop button is not pressed—that is, when I0.1 = 1—which is why we use the NO contact shown in the diagram. The same applies to contacts 95-96 of the thermal relay.

L+ 24 V DC S1 OnNO S2 StopNC F1 Thermal95-96 NC I0.0I0.1I0.2 At rest, without pressing anything: I0.0 = 0 (S1 open) I0.1 = 1 (S2 closed) I0.2 = 1 (F1 closed) In the program: NO contacts of I0.1 and I0.2 Circuit 1 · Run, self-holding, stop, and thermalI0.0RUNQ0.0KM1I0.1STOPI0.2THERMALQ0.0KM1
Figure 49.11 · Above the connection: S1 is an NO contact, S2 and the contact of thermal relay F1 are NC contacts; therefore, in the rest state, I0.1 and I0.2 are 1. Below the mains: the KM1 contact in parallel with RUN provides self-holding; the NO contacts of STOP and THERMAL remain closed until someone presses the stop button or the thermal relay trips.
SituationS2 ButtonBit I0.1NA Contact for I0.1Engine
Nobody touches anythingclosed1closed: traffic can pass throughstay as it was
Press the stop buttonopen0open: the network goes downstops
The S2 wire breaksopen circuit0openIt stops: definite malfunction
Press the start and stop buttons at the same timeopen0opensuspended: the stop takes precedence

Why does the stop button have to be NC? Because a broken wire, a corroded terminal, or a dirty contact will open the circuit—just as if someone had pressed the stop button: the machine stops, and the fault is detected immediately. If the stop button were NO, a broken wire would show no signs of a problem, and on the day you actually need to stop the machine, the button wouldn’t work. This is the principle of positive safety: the most likely failure must bring the machine to the safest state. Also note that the stop button is wired in series after the start button: if the start and stop buttons are pressed simultaneously, the stop button takes precedence (stop priority), which is always the right choice for a motor.

Example 49.8 · The Classic Error: The NC Contact for the NC Button

A beginner might think: “The stop button is NC, so I’ll put an NC contact in the program.” What happens with the circuit shown in Figure 49.12?

In the off state, I0.1 = 1 → the NC contact of I0.1 is open → the motor never starts, even when the RUN button is pressed
When the stop button is pressed, I0.1 = 0 → the NC contact closes → when the stop button is held down and the RUN button is pressed, the motor starts
When the I0.1 stop signal is released, it returns to 1 → the motor stops
The command works in reverse: for a physical NC button, the NO contact is used in the program
Network 1 · INCORRECT: NC contact for an NC buttonI0.0RUNQ0.0KM1I0.1STOPQ0.0KM1
Figure 49.12 · The incorrect circuit from Example 49.8: The NC contact of I0.1, connected to a physical NC button, is open precisely when no one is pressing the stop button.

49.8 Set, Reset, and Edges

Set and Reset Coils

In addition to the normal coil, there are two coils that store data. The set coil --(S)-- sets the bit to 1 when the circuit is powered on and then keeps it at 1 even when the circuit is powered off. The reset coil --(R)-- resets it to 0. It is an SR flip-flop (Chapter 46) implemented with two coils. The same bit can be set and reset in different circuits; if both the set and reset signals arrive in the same cycle, the circuit written lower down takes precedence, because it is the last to write the bit. To avoid dependence on order, the standard also specifies SR (set wins) and RS (reset wins) blocks.

Example 49.9 · Start and stop using set and reset

Rewrite the motor control using the set and reset coils, with the same inputs as shown in Figure 49.11. Which contacts are used for the stop and thermal protection?

Circuit 1: MARCH (NO contact) → S KM1
Network 2: The reset must be triggered when the stop button is pressed, i.e., when I0.1 = 0 → I0.1's NC contact; the same applies to the thermal switch: I0.2's NC contact
The two conditions occur simultaneously: either one is sufficient to trigger a stop; the stop network is below the set network, so the stop takes precedence
With the reset, the stop signal is triggered by the NC contact: the logic is the same, because now the circuit must close when the button is pressed
Network 1 · Mode: SetI0.0RUNSQ0.0KM1Network 2 · stop or thermal: reset (after the set, it takes precedence)I0.1STOPI0.2THERMALRQ0.0KM1
Figure 49.13 · Start and Stop Using Set and Reset. Caution: If KM1 were a latch bit, the motor would restart on its own after a power failure when power is restored. For this reason, bits for moving machines are never declared as latch bits.

Ascent face and descent face

Sometimes it’s not the fact that a signal is at 1 that matters, but the moment it becomes 1. The rising edge (P contact, R_TRIG block in the standard) outputs 1 for a single scan cycle when the signal changes from 0 to 1; the falling edge (contact N, F_TRIG block) does so when it changes from 1 to 0. To detect this, the PLC compares the current state with that of the previous scan cycle, which it stores in a memory bit. The edges are used for counting, to advance a sequence by one step with each press, and to start a cycle only once, even if the operator holds down the button.

I0.0P sideNorth facadehalldownupdown
Figure 49.14 · The P-edge is 1 for a single scan cycle when I0.0 rises; the N-edge is 1 when it falls. In the figure, the pulse has been widened for clarity: in reality, it lasts only a few milliseconds.
Example 49.10 · A single button that turns the light on and off

A lamp should turn on when you press a button and turn off when you press it again. Why do we need the front panel? How do you spell it?

Without a set state, as long as the button is pressed, the light would toggle on and off with each rotation, hundreds of times: eventually, it would remain on or off at random
Network 1: The P edge of the button triggers the M0.0 pulse, lasting one revolution
Network 2: LAMP = (PULSE AND NOT LAMP) OR (NOT PULSE AND LAMP): When a pulse is present, the lamp changes state; when there is no pulse, it remains as it is.
Two networks (Figure 49.15); Network 2 is an exclusive OR (XOR) between the pulse and the lamp
Network 1 · One cycle pulse on the rising edgePI0.0BUTTONM0.0PULSENetwork 2 · each pulse reverses the lampM0.0PULSEQ0.0LAMPM0.0PULSEQ0.0LAMPQ0.0LAMP
Figure 49.15 · Turning the light on and off with a single button: the rising edge generates a one-cycle pulse, which reverses the lamp.

49.9 Timers and Counters

The TON, TOF, and TP Timers

The IEC 61131-3 standard defines three timers, which are represented as blocks in ladder logic. All of them have an input IN, a time that was once set PT (preset time), an exit Q and the time that has passed ET (elapsed time).

  • TON, turn-on delay: Q goes to 1 when IN has remained at 1 for the PT duration. If IN returns to 0 first, the count is reset to zero. This is used for startup delays, sensor filters, and wait times.
  • TOF, de-excitation delay: Q goes to 1 immediately when IN is set to 1, and returns to 0 only when IN has remained at 0 for the duration of PT. This is used for a fan that continues to run after being turned off, or a light that stays on for a short while.
  • TP, pulse: On the rising edge of IN, Q generates a pulse exactly as long as PT, even if IN lasts longer or shorter. During the pulse, a new edge does not trigger it again.
INTON QTON ANDTOF QTP Q04812162024 s
Figure 49.16 · The same IN input applied to the three timers, with PT = 3 s. The TON filter out the 1-second pulse; the TOF extends each pulse by 3 s after the IN edge; the TP always produces 3-s pulses. The gray trace represents the elapsed time (ET) of the TON.

The CTU and CTD meters

The CTU forward counter increments the current value CV by 1 on each rising edge of the CU input; the Q output goes to 1 when CV reaches the preset value PV; the R input resets it. The CTD down counter decrements CV on every CD edge, loads to the PV value with the LD input, and sets Q = 1 when CV reaches 0. The CTUD performs both functions simultaneously, for example, to count the number of parking spaces as a lot fills up and empties. The counter counts the edges, not the duration that the input remains at 1: a stationary workpiece in front of the photocell counts as one.

CURCV123450Q (CV ≥ 3)1st2nd3rd4th5th pulsereset
Figure 49.17 · A CTU with PV = 3: CV increments by one with each CU edge; Q turns on at the third pulse and remains on through the fourth and fifth pulses as well, until R resets everything.
Example 49.11 · The Fan That Stays On

An engine's cooling fan must start when the engine starts and remain on for another 2 minutes after the engine has stopped. What timer is used, and what is the time setting?

Turns on immediately with the engine; turns off with a delay → turn-off delay: TOF
PT = 2 min = 2 × 60 = 120 s (on the PLC: T#120s or T#2m)
TOF with IN = KM1 and PT = 120 s; its output controls the fan (Figure 49.18)
Network 1 · The fan remains on for 120 seconds after the motor stopsQ0.0KM1T2 · TOFINPT 120 sQETQ0.3FAN
Figure 49.18 · The fan follows the motor and shuts off 120 seconds after it does, thanks to the TOF connected in series on the circuit.

49.10 Analog Values, Comparisons, and Calculations

An analog input converts a voltage or current into an integer using an analog-to-digital converter (Chapter 46). The number alone doesn’t mean anything: it must be converted back to the physical quantity, that is, scaled. The most commonly used signal in a workshop is 4–20 mA: 4 mA corresponds to the start of the scale, and 20 mA to the full scale. We start at 4 rather than 0 for a practical reason: if the wire breaks, the current drops to 0—well below 4 mA—and the PLC recognizes this not as zero pressure but as a fault (the so-called live zero). For the same reason, the current signal is not affected by the resistance of long wires, which, in contrast, causes a voltage signal to drop.

The relationship between current and magnitude is a straight line (Chapter 7): all you need to know are two points—the starting point and the full-scale point.

Scaling an Analog Signal (A Line Through Two Points)
y = ymin + (x − xmin) · ymax − yminxmax − xmin
For 4–20 mA:  p = pmin + (I − 4) · pmax − pmin16
x measured value (current in mA, voltage in V, or blank converter output) · xmin, xmax signal start and end points (4 and 20 mA) · y physical quantity · ymin, ymax transducer scale start and end points · p pressure in bar · I current in mA
481216202468100012 mA → 5 bar9.6 mA → 3.5 barFaultbroken wireI < 3.6 mACurrent I (mA)Pressure p (bar)p = (I − 4) · 10 / 16
Figure 49.19 · 0–10 bar pressure transducer with 4–20 mA output: the line passes through (4 mA; 0 bar) and (20 mA; 10 bar). If the current falls below 3.6 mA, the PLC signals a sensor or wire fault.
Example 49.12 · From Current to Pressure

A 0–10 bar transducer with a 4–20 mA output. What pressure corresponds to 12 mA and 9.6 mA? What current will it output at 6 bar? And what if the PLC reads 3.2 mA?

12 mA: p = 0 + (12 − 4) · 1016 = 8 × 0.625 = 5 bar
9.6 mA: p = (9.6 − 4) × 0.625 = 5.6 × 0.625 = 3.5 bar
6 bar: I = 4 + 6 · 1610 = 4 + 9.6 = 13.6 mA
3.2 mA: p = (3.2 − 4) · 0.625 = −0.5 bar: a pressure that is impossible for this sensor
5 bar; 3.5 bar; 13.6 mA; at 3.2 mA, the program must trigger a “sensor failure” alarm, not a pressure alarm
Example 49.13 · From the blank number to the pressure

The analog module of the same system converts 4 mA to 0 points and 20 mA to 27,648 points (a range used by many modules). The PLC reads 17,280 points. What is the pressure? What number corresponds to the 4-bar threshold?

p = 0 + (17 280 − 0) · 10 − 027 648 − 0 = 17,280 × 0.000 361 7 = 6.25 bar
N = 4 · 27 64810 = 11,059.2 → 11,059 points
6.25 bar; the 4-bar threshold corresponds to approximately 11,059 points

Once the physical value is obtained, it is compared against certain thresholds. Comparators (=, ≠, >, ≥, <, ≤) take two numbers and produce a bit: in ladder logic, they are drawn as special contacts or as blocks with two inputs. Similarly, there are arithmetic blocks (ADD, SUB, MUL, DIV) and the MOVE block, which copies a value. For calculations, however, structured text is much more convenient and readable: the scaling and alarm in the example can be written in just two lines. In the ST language, decimals are written with a period, just like in any programming language.

PRESS_BAR := (CORRENTE_MA - 4.0) * 10.0 / 16.0;  (* scalatura 4-20 mA in 0-10 bar *)
GUASTO_SENS := CORRENTE_MA < 3.6;                  (* filo rotto o sensore guasto *)
Example 49.14 · Low-Pressure Alarm

A machine's pneumatic system must trigger an alarm if the pressure drops below 4.0 bar. To avoid false alarms during brief drops caused by a valve opening, the alarm must trigger only if the pressure remains low for more than 2 seconds. How do you write this?

comparator: PRESS_BAR < 4.0 → bit set to 1 when the pressure is low
The bit enters a TON with PT = 2 s: the output goes to 1 only if the condition lasts for 2 s straight
The TON output controls the ALL_PRESS solenoid
2-second TON series comparator (Figure 49.20): The delay filters out short drops
Network 1 · Pressure below 4.0 bar for more than 2 seconds: alarmCMP <IN1 PRESS_BARIN2 4.0OUTT5 · TONINPT 2 sQETQ0.4ALL_PRESS
Figure 49.20 · The CMP block < returns 1 when PRESS_BAR is less than 4.0; the TON block only passes the signal if it lasts longer than 2 s.

49.11 Examples of ladder logic instructions

In this section, we’ll bring together the elements we’ve covered so far to solve the most common machine commands. For each one: what it’s supposed to do, the variables, and the solution we’ve drawn. It’s a good idea to try them out on your own before looking at the diagram.

Example 49.15 · Starting and Stop of a Motor with an Indicator Light and Thermal Protection

Using the table in Example 49.6: the engine starts when set to "RUN" and stops when set to "STOP" or if the thermal cut-off is triggered; a green light indicates that the engine is running, and a yellow light indicates that the thermal cut-off has been triggered.

Network 1: (MARCH OR KM1) AND STOP AND THERMAL → KM1 (self-holding, NO contacts for the two physical NC contacts)
Network 2: KM1 → H_MARCIA
Circuit 3: NOT THERMAL → H_THERMAL (now the NC contact is active: the indicator light turns on when I0.2 goes to 0)
Three networks (Figure 49.21). After the thermal cut-off is triggered, the engine does not restart on its own: a new RUN signal is required.
Network 1 · Run, Self-Hold, Stop, and ThermalI0.0RUNQ0.0KM1I0.1STOPI0.2THERMALQ0.0KM1Network 2 · Engine running indicatorQ0.0KM1Q0.1H_RUNNetwork 3 · Thermal protection indicatorI0.2THERMALQ0.2H_THERMAL
Figure 49.21 · The complete pump motor control system.
✅
It’s best to use the actual status. The H_MARCIA indicator copies the KM1 output bit—that is, the PLC command. On a properly designed machine, an auxiliary contact from the contactor is also connected to an input: if the command is present but the contactor does not close (burnt-out coil, blown fuse), the program detects this and triggers an alarm.
Example 49.16 · Reversing Direction with Interlock

A motor must run forward (contactor KM_AV, Q0.0) or backward (KM_IN, Q0.1). The two contactors must never close at the same time: if two phases were swapped, they would short-circuit the line. Inputs: STOP NC (I0.0), FORWARD (I0.1), REVERSE (I0.2), THERMAL NC (I0.3).

Each circuit is a self-holding gear, with STOP and THERMAL (NO contacts) in series
Electrical interlock: In the KM_AV series, the NC contact of KM_IN, and vice versa
Button interlock: In series with KM_AV, the NC contact of BACK, and vice versa; when BACK is pressed while moving forward, KM_AV opens first
Two symmetrical circuits (Figure 49.22); in addition, the interlock must be replicated in the wiring using the auxiliary NC contacts of the contactors
Network 1 · Forward, with interlocksI0.1FORWARDQ0.0KM_AVI0.0STOPI0.3THERMALI0.2BACKQ0.1KM_INQ0.0KM_AVNetwork 2 · Backward, with interlocksI0.2REVERSEQ0.1KM_INI0.0STOPI0.3THERMALI0.1FORWARDQ0.0KM_AVQ0.1KM_IN
Figure 49.22 · Direction reversal: Each contactor has the other contactor’s NC contact (interlock) and the NC contact of the opposite button connected in series.

Why repeat the interlock in the wiring? Because in the PLC, network 1 turns off KM_AV, and in the same cycle, network 2 can already turn on KM_IN: the two outputs change within a few milliseconds of each other, while a contactor takes tens of milliseconds to open and the electric arc persists for a little while longer. Furthermore, a faulty output transistor may remain closed on its own. The NC auxiliary contact of each contactor, wired in series with the coil of the other, makes the interlock independent of the program. On large motors, a brief pause with a TON is also added before the reversal.

Example 49.17 · Two-Hand Control with Simultaneity

A small press will lower only if the operator presses the two buttons P_SX (I0.0) and P_DX (I0.1) within 0.5 seconds of each other, and only as long as both are held down. If the operator releases one of them, to restart the press, they must release both buttons and press them again.

Network 1: As soon as either button is pressed, TON T1 sounds for 0.5 seconds; it resets only when both buttons are released.
Network 2: PRESS = P_SX AND P_DX AND (NOT T1.Q OR PRESS)
Press the second button within 0.5 s: T1.Q remains at 0, the NC contact closes, the PRESS turns on, and remains on as long as both buttons are held down
Second button pressed after 0.5 s: T1.Q is already 1, the NC contact is open, and there is no self-holding: the press does not start
Two circuits (Figure 49.23); if one button is released, T1 remains at 1 due to the other, and the press cannot restart
Channel 1 · The timer starts as soon as you press a buttonI0.0P_SXI0.1P_DXT1 · TONINPT 0.5 sQETNetwork 2 · approval only if the second signal arrives within 0.5 sI0.0P_SXI0.1P_DXT1.QTIME_SCQ0.0PRESSQ0.0PRESS
Figure 49.23 · Two-hand control: T1 measures the time between the first and second presses.
⚠️
Just as an exercise. On a real press, the two-hand control is a safety device: it is implemented using a certified module or a safety PLC, with monitored NO and NC-contact buttons, in accordance with the standards in Chapter 51. The ladder diagram of a standard PLC teaches logic, but it does not protect anyone’s hands.
Example 49.18 · Traffic Light with Timers

A traffic light at an internal crossing within a factory stays green for 20 seconds, yellow for 3 seconds, and red for 25 seconds, then repeats the cycle as long as the ON switch (I0.0) is closed. How long does a cycle last, and how do you write this using three TONs?

cycle time = 20 + 3 + 25 = 48 s
T1 (20 s) starts when the power is ON; T2 (3 s) starts when T1 ends; T3 (25 s) starts when T2 ends
When T3 turns off, its NC contact in network 1 resets T1, which resets T2, which resets T3: the cycle starts over
GREEN = NOT T1.Q · YELLOW = T1.Q AND NOT T2.Q · RED = T2.Q
48-second cycle with six nets (Figures 49.24 and 49.25)
Network 1 · Green TimeI0.0ONT3.QEND_CYCLET1 · TONINPT 20 sQETGoal 2 · Yellow card timeT1.QEND_GREENT2 · TONINPT 3 sQETNetwork 3 · Red TimeT2.QEND_YELLOWT3 · TONINPT 25 sQETNetwork 4 · green lightI0.0ONT1.QEND_GREENQ0.0GREENNetwork 5 · yellow lightT1.QEND_GREENT2.QEND_YELLOWQ0.1YELLOWZone 6 · red lightT2.QEND_YELLOWQ0.2RED
Figure 49.24 · The traffic light: three TONs in a chain; when the red light ends, the chain resets and the green light starts again.
GREENYELLOWREDT1.QT2.QT3.Q020234860 s
Figure 49.25 · The three lamps and the timer outputs over a 48-second cycle. T3.Q lasts only one scan cycle: that is enough to reset the chain.
Example 49.19 · Conveyor belt that counts 10 workpieces and stops

A conveyor belt starts with RUN (I0.0) and stops with NC stop (I0.1). A photoelectric sensor (I0.2) counts the workpieces that fall into a box: when the tenth workpiece is counted, the conveyor belt stops automatically and the H_LOTTO indicator light turns on. Pressing RUN again resets the count and fills the next box.

Network 1: CTU C1 with CU = PHOTOCELL, PV = 10, R = RUN; the counter counts only the rising edges
Network 2: (MARCH OR TAPE) AND STOP AND NOT C1.Q → TAPE
Network 3: C1.Q → H_LOTTO
The counter network takes precedence: pressing RUN resets the count during the same cycle in which the belt starts moving again
Three nets (Figure 49.26)
Network 1 · counts the workpieces; MARCIA resets the countI0.2PHOTOCELLC1 · CTUCUR RUNPV 10QCVNetwork 2 · tape: stops at the tenth workpieceI0.0RUNQ0.0TAPEI0.1STOPC1.QBATCH_OKQ0.0TAPENetwork 3 · Batch Complete IndicatorC1.QBATCH_OKQ0.1H_BATCH
Figure 49.26 · The tape with the counter: C1.Q, in a pack of 10 workpieces, opens the tape spool and turns on the indicator light.
Example 49.20 · Filling a Tank with Two Levels

A pump (Q0.0) fills a tank from which water is drawn. Two sensors output a value of 1 when wet: LIV_MIN at the bottom (I0.1) and LIV_MAX at the top (I0.2). With the AUTO switch (I0.0) set, the pump should start when the water level drops below the minimum and stop at the maximum; it should not continuously turn on and off around a single level.

Start: LIV_MIN = 0 (water level below minimum) → LIV_MIN NC contact
Maintenance between minimum and maximum: automatic hold with the PUMP contact
Stop: LIV_MAX = 1 → LIV_MAX NC contact in series
Plausibility check: a maximum wet reading and a minimum dry reading are impossible, so a sensor is faulty; if this condition lasts 2 seconds, the pump shuts off and the alarm sounds
The difference between the two levels acts as hysteresis; three grids (Figures 49.27 and 49.28)
B2 LIV_MAXInput I0.2B1 LIV_MINInput I0.1M1 pumpoutput Q0.0from the wellconsumptionthe pumpfills fromMIN to MAX
Figure 49.27 · The tank: B1 low-level sensor, B2 high-level sensor, M1 fill pump.
Circuit 1 · Pump: Starts below minimum, stops at maximumI0.0AUTOI0.1MIN_LEVELQ0.0PUMPI0.2MAX_LEVELM0.1FAULTQ0.0PUMPNetwork 2 · Maximum wet and minimum dry: faulty sensorsI0.2MAX_LEVELI0.1LIV_MINT1 · TONINPT 2 sQETM0.1FAULTNetwork 3 · alarm indicatorM0.1FAULTQ0.1H_ALARM
Figure 49.28 · Two-stage filling with sensor control. A physical overflow (overflow weir) is still necessary: the program does not replace safety measures.

49.12 Sequences and Grafcet

Many machines operate in steps: one cylinder extends, then another, then the first retracts, and so on. You’ve already seen pneumatic sequences such as A+ B+ B− A− in Chapter 42, along with the issue of interlock signals and the cascade method. With a PLC, the problem is solved more simply: the machine’s current phase is stored in a single bit.

Example 49.21 · A+ A− Cylinder with Limit Switch

A double-acting cylinder is controlled by a monostable 5/2-way valve (coil Y1, Q0.0): when Y1 is energized, the cylinder extends; when de-energized, it retracts. Limit switches a0 (I0.1, cylinder retracted) and a1 (I0.2, cylinder extended). When START (I0.0) is pressed, the cylinder must extend and retract once, even if START remains pressed.

Starting position: at the base of the START AND a0 climb (the cylinder must be retracted)
Y1 remains energized by the self-holding circuit until a1 is reached: a1's NC contact in series
When facing the front, if you hold down START, the cylinder does not restart when it returns to a0
A network (Figure 49.29): (↑START AND a0 OR Y1) AND NOT a1 → Y1
Set 1 · A+ on the front line for START with A back in; a1 brings him backPI0.0STARTI0.1a0Q0.0Y1I0.2a1Q0.0Y1
Figure 49.29 · The A+ A− cycle with a monostable valve: the START edge and limit switch a0 trigger the start, while a1 triggers the reset.

Grafcet

When there are more than two phases, a ladder diagram drawn “by intuition” becomes a tangled mess. In that case, one first draws the Grafcet (IEC 60848 standard), a diagram that describes the cycle in a way that the mechanical engineer, the electrician, and the programmer can all understand. In the IEC 61131-3 standard, this same method becomes the SFC language. There are three elements:

  • phases (or stages), represented as numbered squares; the initial phase has a double square. A phase is either active or inactive;
  • transitions, a solid dash indicating the connection between two phases, with the condition (known as receptivity) next to it that must be true in order to move on;
  • Actions, rectangles to the right of the phases: what the machine does while the phase is active.

The rule of evolution is simple: a transition is completed when the preceding phase is active and its condition is true; at that point, the next phase becomes active and the previous one becomes inactive. The cycle proceeds in this way, one step at a time, and at any given moment, we know exactly where the machine is in the process.

Example 49.22 · The Grafcet for the sequence A+ B+ B− A−

Two double-acting cylinders with 5/2-way bistable valves (A: YA+ and YA−; B: YB+ and YB−) and limit switches a0, a1, b0, and b1. When START is pressed, with the cylinders retracted, the machine performs A+, B+, B−, A−, and then stops.

SymbolAddressSymbolAddress
STARTI0.0YA+Q0.0
a0I0.1YB+Q0.1
a1I0.2YB−Q0.2
b0I0.3YA−Q0.3
b1I0.4X0 … X4 (phases)M10.0 … M10.4
Phase 0: Wait → Transition ↑START · a0 · b0 → Phase 1: YA+
a1 → phase 2: YB+ · b1 → phase 3: YB− · b0 → phase 4: YA− · a0 → return to phase 0
Five phases and five transitions (Figure 49.30)
0Waiting (initial phase)↑START · a0 · b01YA+ (A exits)a12YB+ (B exits)b13YB− (B re-enters)b04YA− (A returns)a0Aa0a15/2-way bistable valve: YA+ and YA−Bb0b15/2 bistable valve: YB+ and YB−square = phase (double = initial)thick line = transitionrectangle on the right = phase action↑START = rising edge of the button
Figure 49.30 · The Grafcet diagram for the sequence A+ B+ B− A−. After step 4, the cycle returns to the initial step 0. On the right are the two cylinders with their limit switches.
Example 49.23 · From Grafcet to Ladder Diagrams Using Phase Bits

Translate the Grafcet from Example 49.22 into ladder logic using the phase-bit method. Each phase is a marker (X0 … X4).

Initialization: On the first cycle after power-on, a system bit (here, PRIMO_CICLO) sets X0
Every transition is a network: previous phase AND condition → S next phase, R previous phase
Every action is a network: the phase bit controls the output using a standard coil
Outputs are written only once, in the action networks: if an output is needed in multiple phases, the phase bits are placed in parallel
Six transition goals and four open-play goals (Figures 49.31 and 49.32); the defensive signals in the Pneumatica system no longer exist
Network 1 · Phase 0 is activated during the first cycle after power-upM1.0FIRST_CYCLESM10.0X0Network 2 · transition 0 → 1M10.0X0PI0.0STARTI0.1a0I0.3b0SM10.1X1RM10.0X0Network 3 · Transition 1 → 2M10.1X1I0.2a1SM10.2X2RM10.1X1Network 4 · Transition 2 → 3M10.2X2I0.4b1SM10.3X3RM10.2X2Network 5 · Transition 3 → 4M10.3X3I0.3b0SM10.4X4RM10.3X3Network 6 · transition 4 → 0M10.4X4I0.1a0SM10.0X0RM10.4X4
Figure 49.31 · Transitions: Each network activates the next phase and deactivates the current one.
Network 7 · Phase 1 ActionM10.1X1Q0.0YA+Network 8 · Phase 2 actionM10.2X2Q0.1YB+Network 9 · Phase 3 actionM10.3X3Q0.2YB−Network 10 · Phase 4 actionM10.4X4Q0.3YA−
Figure 49.32 · The actions: each stage controls its own valve. With monostable valves, two outputs would suffice: YA+ = X1 OR X2 OR X3 and YB+ = X2.
✅
Because it always works. At any given moment, only one phase is active, and each transition network monitors only the limit switch that concerns it. Limit switch a1, which remains pressed for three phases in the sequence, does not cause any issues in the ladder diagram because it only matters in the 1 → 2 transition. This is exactly what the cascade required in Chapter 42.

49.13 Best Practices and Safety

A program is written by one person, but many people read it over the years: the night shift maintenance technician, the colleague who modifies it, and even you yourself in six months. A few good habits can make all the difference.

  • Symbols and comments: Each variable has a clear name and a comment explaining what it means; each network has a title (“tape run,” “pressure alarm”).
  • One coil per bit: each output is connected to a single point. If an output turns on for multiple reasons, those reasons are connected in parallel within the same network.
  • Program divided into blocks: The standard refers to these program components as POUs (program organization units): programs, functions, and functional blocks. Having one block for each machine group (conveyor, press, alarms) makes the code more readable and reusable.
  • Clear Alarms: A message on the panel is worth more than a hundred LEDs: “Air pressure below 4 bar” is immediately understandable.
  • Copies and versions: Before making any changes, save the program with the date and note what has been changed.

Safety cannot rely solely on the PLC

A standard PLC is reliable, but it is not designed for safety functions: a failure of the CPU, a transistor output, or an error in the program could cause an output to remain on. This is why the emergency stop is hardwired: the red pushbutton, with positively driven NC contacts, controls a safety relay that directly cuts power to the outputs and contactors. The PLC reads the emergency status solely for informational purposes, to stop the cycle in an orderly manner and display the message. After an emergency, the machine must not restart on its own: a manual reset command is required.

L+ 24 V DCM 0 VS0NC contactK0 safetysafety24 VmonitoredNormal PLCstatusI0.5 EMERG_OKreads the status andstops the cycleL+ outputsCPU power supplyQ0.0KM1When S0 is pressed, K0 removes the 24 V from the outputs:KM1 drops even if the PLC malfunctions
Figure 49.33 · The S0 pushbutton acts on the K0 safety relay, which powers the common terminal of the outputs: when S0 is pressed, the outputs remain de-energized regardless of what the program does. The PLC receives only a status signal on I0.5.

When there are many safety functions (light curtains, locked doors, two-hand control, reduced speed), a safety PLC is used: it has two processors that perform the same calculations and monitor each other, dual inputs that compare two contacts from the same button, self-checking outputs, and a certification indicating the level of safety achieved. Standards, safety levels, and risk assessment are covered in Chapter 51.

49.14 The PLC in a CNC Machine and Diagnostics

Every numerically controlled machine tool has a PLC inside it. The CNC (Chapter 50) handles the program for workpieces and the movement of the axes; everything else—that is, the “machine logic”—is managed by a PLC integrated into the control system, written by the machine manufacturer. On Fanuc controls, it is called a PMC (programmable machine controller); on Siemens controls, it is a PLC integrated into the control system; in all cases, it is programmed in ladder logic or in languages compliant with the IEC 61131-3 standard.

  • M codes: The CNC doesn't know what a pump is; when it reads "M08," it sends the number 08 to the PLC via a strobe signal, and the PLC turns on the coolant pump;
  • spindle: compatibility with M03, M04, M05; closed-jaw or collet control; orientation;
  • Tool change: Using the M06 command and the letter "T," the PLC controls the search in the tool magazine, the tool changer arm, and the sensors for unlocked and locked tools;
  • doors: door lock, authorization to operate with the door closed, reduced speeds when the door is open (in conjunction with the safety circuits);
  • centralized lubrication, coolant, chip conveyor, lights, along with their timers and level alarms;
  • operator panel: buttons, mode selectors, override potentiometers.
CNC (computer numerical control)reads the program, moves the axesIntegrated PMC/PLCmachine ladder programwritten by the manufacturerMachineSensors, pumps, doors, storageControl Panelbuttons, selectorscodes M, S, Tand strobe signalFIN (function complete),enable signals, alarmsoutputs: coolant,lubrication, lock, storageinputs: door closed,air, levels, limit switches
Figure 49.34 · The PMC acts as an intermediary: it receives the M, S, and T codes along with the strobe signal from the CNC, controls the machine, and sends the end-of-function (FIN) signal back to the CNC. The CNC does not proceed to the next block until it receives the FIN signal.
Example 49.24 · M08 and M09 in the machine's ladder diagram

The CNC reads M08 (coolant on) or M09 (coolant off). The PLC receives the code already decoded into bits (DEC_M08, DEC_M09, DEC_M30) and the STROBE_M signal. How do you write the logic, including the FIN?

Network 1: STROBE_M AND DEC_M08 → S PUMP_REF (the pump must remain on even after the block)
Network 2: (STROBE_M AND (DEC_M09 OR DEC_M30)) OR NOT EMERG_OK → R PUMP_REF
Network 3: FIN only if the action is actually completed: with M08 when the coolant pressure switch PRESS_REF confirms the pressure, with M09 when the pump is off
Three networks (Figure 49.35): If the pump does not provide pressure, the FIN signal does not arrive, and the workpiece program stops at that block
Network 1 · M08: Turns on the coolant pumpSTROBE_MDEC_M08SCOOLANT_PUMPCircuit 2 · M09, M30, or emergency: turns off the pumpSTROBE_MDEC_M09DEC_M30EMERG_OKRPUMP_REFNetwork 3 · END only when the pump is actually in the requested stateSTROBE_MDEC_M08PRESS_REFDEC_M09PUMP_REFEND
Figure 49.35 · Coolant management in the machine's PLC. The names are generic: each manufacturer uses its own addresses for strobes, codes, and FIN.

Simulation and Commissioning

You don't test a new program on the actual machine the first time. Programming software includes a simulator that runs the program on the PC: you force the inputs with the mouse and observe the outputs, checking even the most unusual sequences (two buttons pressed simultaneously, a sensor that doesn’t register, a power outage mid-cycle). Then, on the machine itself, commissioning follows a specific sequence.

  • First, the safety circuits: emergency circuits, doors, safety relays—tested one by one;
  • Next, check the wiring: press each button and activate each sensor while monitoring the LED and the bit in the software; test each output in an open-circuit condition, with the power disconnected or with the actuators free to move;
  • Forcing outputs must be used with great caution, because it actually sets the machine in motion and bypasses the logic: whoever forces the output must be able to see the machine, and no one should be in the danger zone;
  • Finally, the cycle—first step-by-step, then on automatic at reduced speed, and finally at full speed.

Diagnosis Using the Online Status

By connecting the PC to the running PLC, you can view the program in online mode: the contacts that are currently open and the energized coils are highlighted—usually in green—and the current values appear next to the timers and counters. To troubleshoot a fault, start with the output that isn’t activating and trace the circuit to the left until you reach the first contact that isn’t conducting: that’s the missing signal. Then check the machine to see why it’s missing.

Network 1 · Online status: The engine won't startI0.0RUNQ0.0KM1I0.1STOPI0.2THERMALQ0.0KM1
Figure 49.36 · Online status while the operator presses RUN: the live contacts are shown in green. RUN and STOP are energized, but THERMAL is not: the KM1 coil remains de-energized.
Example 49.25 · The engine won't start

The operator presses the RUN button, but the pump shown in Example 49.15 does not start. The online status displays the circuit shown in Figure 49.36. Where should the operator look for the fault?

What Can You See?What does that mean?What do you do?
Green MARCHThe button is connected to the PLCNothing: The button and its wire are in place
Green STOPI0.1 = 1, the stop button is not pressed, and the wire is intactnothing
THERMAL (not green)I0.2 = 0: Contact 95-96 is open or the file is brokenCheck the I0.2 LED and the F1 thermal relay: if it has tripped, determine why the motor drew too much current, then reset it
H_THERMAL indicator light is onConfirmation: Network 3 shows I0.2 = 0After the reset, the indicator light turns off and the engine restarts in DRIVE
The problem isn't with the PLC: the thermal protection kicked in. The program did exactly what it was supposed to do.
💡
The PLC is almost never the problem. In the vast majority of cases, the issue lies elsewhere: a dirty or misaligned sensor, a disconnected wire, a blown fuse, a burned-out contactor, or a lack of air pressure. The online status and the module LEDs are specifically designed to quickly distinguish between “the signal isn’t coming through” and “the signal is coming through but the logic isn’t giving the go-ahead.”

49.15 The Formulas in This Chapter

WhatFormula
Maximum response timetr,max = tf + 2 · tc + tu
Duration of the pulse from a passing objecttimp = L / v
Pulse Read with Confidencetimp > tc + tf; in other words, timp ≥ 2 · tc
Current Through a DC LoadI = P / U
Channels with a reservechannels = signals · (1 + reserve), rounded up
Linear scalingy = ymin + (x − xmin) · (ymax − ymin) / (xmax − xmin)
4–20 mA Scalep = pmin + (I − 4) · (pmax − pmin) / 16
Current for a given valueI = 4 + (p − pmin) · 16 / (pmax − pmin)

49.16 Exercises

For the programming exercises, the solution is written as a list of circuits; draw them in ladder diagram format on a sheet of paper, and if you can, test them using a simulator.

Exercise 1. A PLC has a cycle time of 20 ms, an input filter of 5 ms, and a transistor output with a 1 ms delay. What is the maximum response time?
Solution

tr,max = 5 + 2 × 20 + 1 = 46 ms.

Exercise 2. A 0–6 bar transducer with a 4–20 mA output reads 14 mA. What is the pressure? What current will it output at 4.5 bar?
Solution

p = (14 − 4) · 6 / 16 = 10 · 0.375 = 3.75 bar. I = 4 + 4.5 · 16 / 6 = 4 + 12 = 16 mA.

Exercise 3. A temperature transmitter with a 4–20 mA output has a range from −50 to +150 °C. What temperature corresponds to 10 mA? At what current should an alarm be set for 120 °C?
Solution

T = −50 + (10 − 4) · 200 / 16 = −50 + 75 = 25 °C. I = 4 + (120 + 50) · 16 / 200 = 4 + 13.6 = 17.6 mA.

Exercise 4. The cycle time is 15 ms, and the workpieces pass in front of the sensor at 1.2 m/s. What is the minimum length of the portion that the sensor detects in order to produce a pulse spanning two cycles?
Solution

L = v · 2 · tc = 1.2 · 2 · 0.015 = 0.036 m = 36 mm.

Exercise 5. A group of 24 V DC transistor outputs (0.5 A per channel, 2 A per group) is connected to 6 3 W solenoid valves and 3 2.4 W indicator lights. Can the group handle the load if they are all on?
Solution

Solenoid valve: 3 / 24 = 0.125 A; indicator light: 2.4 / 24 = 0.1 A. Total: 6 · 0.125 + 3 × 0.1 = 0.75 + 0.30 = 1.05 A < 2 A: it works, and each channel is below 0.5 A.

Exercise 6. A relay output has a lifespan of 400,000 operations. It controls a load that turns on 10 times per minute for 8 hours a day. After how many days of operation does it need to be replaced?
Solution

Operations per day: 10 · 60 · 8 = 4,800. Duration: 400,000 / 4,800 = 83.3 days. It’s better to use a transistor output or an interface relay that’s easy to replace.

Exercise 7. The value of input IB0 is 0010 1001 in binary. Which inputs are set to 1? What is the decimal value of IB0? How do you write the address of bit 5 of byte 2?
Solution

Bits 0, 3, and 5 are set to 1: I0.0, I0.3, I0.5. In decimal, 32 + 8 + 1 = 41. Bit 5 of byte 2 is I2.5 (in the standard notation %IX2.5).

Exercise 8. Write the following in ladder diagram notation: Lamp L turns on if A is pressed and B is not, or if C is pressed.
Solution

L = (A AND NOT B) OR C. A circuit: a branch with the NO contact of A in series with the NC contact of B, in parallel with a branch containing the NO contact of C; the coil L is on the right.

Exercise 9. In the start-and-stop circuit shown in Figure 49.11, what happens if the wire from the stop button comes loose from the terminal while the motor is running? What if the button had been connected as a NO contact, with the NC contact in the program?
Solution

With the NC button: I0.1 goes to 0, the NO contact opens, and the motor stops; the fault is immediately apparent. With the NO button: the disconnected wire would leave I0.1 at 0 indefinitely; the NC contact would remain closed, and no one would notice until the stop button was pressed and the motor stopped.

Exercise 10. Use two 0.5-second TON signals to make an indicator light flash (on for 0.5 seconds, off for 0.5 seconds).
Solution

Circuit 1: T2.Q’s NC contact → TON T1, PT 0.5 s. Circuit 2: T1.Q’s NO contact → TON T2, PT 0.5 s. Circuit 3: T1.Q’s NO contact → indicator coil. T1 counts for 0.5 s with the indicator light off; then T1.Q turns on the indicator light and starts T2; after another 0.5 s, T2.Q resets T1, the indicator light turns off, T2 resets, and the cycle restarts. Period: 1 s.

Exercise 11. A company parking lot has 50 spaces. With a CTUD counter (CU = entry photocell, CD = exit photocell, PV = 50), the “FULL” sign lights up. Starting from 0, 38 cars enter, 6 leave, and 18 enter. Is the sign lit? What if 3 cars then leave?
Solution

CV = 38 − 6 + 18 = 50 = PV: Q = 1, FULL on. After 3 outputs, CV = 47 < 50: FULL off.

Exercise 12. Write the phases, transitions, and transition networks for the sequence A+ A− B+ B− using the same limit states as in Example 49.22.
Solution

States: 0 (idle), 1 (YA+), 2 (YA−), 3 (YB+), 4 (YB−). Transitions: 0 → 1 with ↑START · a0 · b0; 1 → 2 with a1; 2 → 3 with a0; 3 → 4 with b1; 4 → 0 with b0. Networks: X0 AND ↑START AND a0 AND b0 → S X1, R X0; X1 AND a1 → S X2, R X1; X2 AND a0 → S X3, R X2; X3 AND b1 → S X4, R X3; X4 AND b0 → S X0, R X4. Actions: X1 → YA+, X2 → YA−, X3 → YB+, X4 → YB−. Note: The transition 2 → 3 uses a0, which is also in the initial state, but there is no confusion because each network also considers its own phase bit.

Exercise 13. A centralized lubrication system is designed to run the pump for 10 seconds every 15 minutes when the machine is in AUTO mode. Draw the networks using two TONs. How many complete lubrication cycles does it perform during an 8-hour shift?
Solution

Network 1: AUTO AND NOT T2.Q → TON T1, PT 15 min (900 s). Network 2: T1.Q → TON T2, PT 10 s. Network 3: T1.Q → LUB_PUMP. A cycle lasts 900 + 10 = 910 s; in 8 hours: 8 · 3600 / 910 = 31.6 → 31 complete lubrications.

Exercise 14. In the two-hand control example 49.17, the operator presses P_SX, waits 1 s, and then presses P_DX. What happens? What must the operator do to lower the press?
Solution

After 0.5 s, T1.Q goes to 1; when P_DX arrives, the NC contact of T1.Q is open and the PRESS has no hold function: the press remains stationary. You must release both buttons (T1 resets) and press them again within 0.5 seconds of each other.