Ladder Logic Programming: Language, Programs & Examples
Learn ladder logic programming from scan semantics to a tested motor program, timers, counters, sequences, troubleshooting, and vendor translation.
Ladder logic programming: the direct answer
Ladder logic is a graphical PLC programming language that represents Boolean conditions as contacts, results as coils, and reusable operations as functions or function blocks arranged in networks or rungs. The standardized language name is Ladder Diagram (LD). In ordinary engineering conversation, ladder language, ladder logic, ladder program, and ladder diagram program usually refer to the same family of work, not four separate languages.
The fastest sound way to learn it is to specify one small control requirement, name its inputs and outputs, predict its behavior scan by scan, implement it with vendor-neutral tags, and test normal, boundary, restart, and fault cases before translating it into a particular controller's instructions. The visible drawing matters, but the program's real contract is the state it produces for every input history.
| Question | Practical answer | Evidence to retain |
|---|---|---|
| What does a contact do? | It examines a Boolean expression; it does not necessarily represent a physical contact | tag definition and truth table |
| What does a coil do? | It writes a Boolean result according to the platform's coil semantics | cross-reference and single-writer review |
| How does a rung execute? | According to the configured task and editor/runtime rules, commonly left-to-right within an ordered network list | task configuration and scan trace |
| How should a first program be built? | From an I/O contract, state requirements, rung logic, and acceptance tests | versioned source and signed test record |
| Can a simulator prove the machine is safe? | No; it can test logic behavior but not the entire field, process, safety, or timing system | hardware and site validation plan |
Review and version boundary (29 August 2026): this tutorial uses the current IEC 61131-3:2025 programming-language boundary and PLCopen's current logic overview. IEC defines the language model; it does not make every vendor instruction, timer member, address, task schedule, online-edit rule, or file format identical. Verify behavior in the manual for the exact controller, firmware, engineering tool, task configuration, and safety architecture used on the project.

Ladder language, ladder logic, and ladder diagram terminology
The standard term is Ladder Diagram
IEC 61131-3 names the graphical language Ladder Diagram, abbreviated LD. PLCopen describes LD and Function Block Diagram as graphical languages within the IEC programming-language family. A vendor editor may label a project object LAD, LD, or Ladder, while a technician may call the finished artifact a ladder program or ladder logic. Those labels can change the search words without changing the core programming task.
Use the terms precisely in a specification:
| Term | Useful meaning in this guide | Common source of confusion |
|---|---|---|
| Ladder Diagram (LD) | the standardized graphical PLC language | confused with an electrical ladder wiring drawing |
| ladder logic | common name for LD logic and its relay-like notation | can also mean a vendor's extended instruction set |
| ladder program | one controller program or POU implemented wholly or partly in LD | not necessarily the complete controller application |
| rung or network | an ordered unit of graphical logic | execution and layout rules differ by editor |
| contact | an instruction that evaluates a Boolean condition | symbol state is not the same as the field device's physical normal state |
| coil | an instruction that writes or modifies a Boolean variable | ordinary, set, reset, negated, and transitional coils do not behave identically |
A ladder program is software, not energized wiring
The rails and continuity metaphor came from relay control, but the controller evaluates data. A contact associated with GuardClosed asks whether the program value satisfies the contact's condition. It does not conduct physical current. A coil associated with MotorRequest changes a variable according to the instruction semantics; a separate output mapping may later send that state to an output module.
This distinction prevents a common error: choosing an examine-if-open or examine-if-closed instruction because a field pushbutton is physically normally open or normally closed. First document the electrical signal meaning—such as StopCircuitHealthy = TRUE—then select the contact instruction that makes the Boolean requirement readable. Physical de-energize-to-trip design and safety diagnostics must be established by the electrical and safety design, not inferred from a slash drawn in ladder.
Ladder is portable in concepts, not copy-and-paste syntax
IEC alignment gives engineers a shared model for programs, function blocks, contacts, coils, timers, and other elements. It does not promise source compatibility. A Rockwell XIC instruction, Siemens LAD contact, CODESYS LD contact, Beckhoff LD element, Omron contact, Schneider LD contact, and Mitsubishi ladder contact may express a similar Boolean test while differing in tag model, data scope, edge behavior, tasking, online monitoring, project structure, and supported extensions.
Treat vendor translation as a small migration project. Write the intended state rule, identify every stateful instruction, map each construct to current target documentation, compile, simulate, and repeat the test matrix on the target runtime. Never translate only by matching icons.
What a PLC ladder program contains
Application, task, program, and rung are different levels
A complete controller application may contain hardware configuration, tasks, programs, function blocks, data types, communication mappings, alarm logic, diagnostics, and multiple programming languages. Ladder Diagram is one implementation language inside that system. One page of rungs is not necessarily the entire PLC program.
| Level | Responsibility | Review question |
|---|---|---|
| controller application | device, I/O, network, security, retention, task and deployment configuration | can the exact approved target run and recover this version? |
| task | schedule, priority, trigger, watchdog, period or event | when can this logic execute relative to I/O and other tasks? |
| program/POU | cohesive control responsibility | is ownership narrow enough to test and maintain? |
| routine/network group | ordered portion of the implementation | is execution order documented where it matters? |
| rung/network | one understandable state transformation or call | can a maintainer explain its conditions and result? |
| instruction/function block instance | Boolean, timing, counting, data or reusable behavior | what state persists, and how is it reset? |
Separate input meaning, control state, and output command
Raw addresses are useful at the hardware boundary, but control logic is easier to audit when tags express meaning. A maintainable pattern separates:
- Input conditioning: map and validate raw channels, diagnostic quality, polarity, debounce, range, and simulation ownership.
- Control state: calculate permissives, interlocks, requests, modes, sequence states, timers, and fault latches.
- Output arbitration: decide which owner may request an actuator and what happens during faults, manual mode, communication loss, or controller restart.
- Physical output mapping: write the approved command to the configured channel and expose command/feedback mismatch diagnostics.
That separation makes a simulated input explicit and helps prevent a maintenance override from being scattered through production rungs. It also gives the HMI a stable state contract instead of raw bits with ambiguous meanings.
Prefer one writer for each state variable
If five rungs write ConveyorRun, online monitoring may show the final value without making the winning writer obvious. Ordinary coil instructions can overwrite earlier writes in the same scan; set/reset instructions introduce retained state and ordering dependencies. The exact semantics are vendor-specific, but the design risk is universal.
Use one output-arbitration rung or one program owner per command when practical. When multiple writers are unavoidable, document the precedence and verify it with a cross-reference report and tests. A comment such as “last rung wins” is not a substitute for an explicit state policy.
How ladder logic executes during a PLC scan
Use the scan model as a diagnostic hypothesis
A useful introductory model is: acquire inputs, execute scheduled logic, update outputs, and perform communications or housekeeping. It helps a learner reason about why an input change may not appear at an output instantly. It is not a universal hardware specification. Some systems update I/O asynchronously, use multiple tasks, support immediate I/O instructions, execute event tasks, or distribute logic across controllers and networks.

When timing matters, replace the cartoon with evidence: task periods and priorities, measured execution time, I/O update behavior, producer/consumer timing, network update rates, and a trace showing the relevant transition.
Rung order can change the same-scan result
Consider two networks in one cyclic task:
Network 1: RequestAccepted := StartRequest AND Available
Network 2: RunLamp := RequestAccepted
If the runtime evaluates Network 1 before Network 2 and exposes the written state immediately to later networks, RunLamp can see the new value in that execution. Reverse the networks and it may see the previous value until the next execution. The exact rule must come from the target platform, but the lesson is stable: order is part of the program whenever one write feeds another read.
| Observation | Possible layer | Evidence to inspect |
|---|---|---|
| input LED changes but tag does not | module mapping, input image, task update, quality | module diagnostics and raw mapped tag |
| tag changes but rung path does not | contact polarity, wrong instance, task not scheduled | online rung and task monitor |
| rung result changes but output command does not | later writer, arbitration, force, inhibit | cross-reference and output-owner state |
| command changes but device does not | output module, wiring, protection, device mode or fault | electrical measurement and device feedback |
| behavior changes only under load | task overrun, network jitter, race, asynchronous update | time-stamped trace and task statistics |
State survives scans only when designed to
An ordinary combinational rung recalculates its result each execution. A seal-in branch, set/reset pair, timer, counter, edge detector, sequence state, or retained variable introduces memory. For every stateful element, define:
- what event sets or advances it;
- what clears or resets it;
- what happens if the enabling condition disappears;
- whether it is retentive across task stop, download, controller restart, or power loss;
- what startup state is safe and operationally correct;
- which diagnostic exposes a stuck or impossible state.
Never infer retentive behavior from an instruction name alone. Firmware and project configuration can affect persistence.
Contacts, coils, branches, and Boolean truth
Read a contact as a test of a value
For a positive contact, continuity is true when its Boolean expression is true. For a negated contact, continuity is true when the expression is false. Vendor mnemonics such as XIC and XIO often lead learners to talk about “open” and “closed” in ways that conflate the instruction, the tag, and the field device. State all three layers when troubleshooting.
| Field condition | Program tag | Positive contact | Negated contact |
|---|---|---|---|
| signal maps to false | 0 | false path | true path |
| signal maps to true | 1 | true path | false path |
| channel quality bad | depends on input-conditioning policy | never assume healthy | never use inversion as a quality check |
For deeper contact and coil semantics, use the dedicated contacts and coils guide. This tutorial owns the complete programming workflow; that guide owns the instruction-level truth detail.
Series implements AND; parallel implements OR
Two positive contacts A and B in series give continuity only when both are true. Two branches in parallel give continuity when at least one branch is true. Negation changes the examined expression, not the underlying field device.
| A | B | A AND B |
A OR B |
A AND NOT B |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 0 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |

Trace a complex rung from the left rail through each required series condition and every available parallel path. If an output is false, find the first false condition along the path that should have been true. If an output is unexpectedly true, identify which complete branch supplied continuity. This is more reliable than toggling bits until the symptom disappears.
Know which kind of coil you are using
| Coil form | General purpose | Main review risk |
|---|---|---|
| ordinary assignment coil | recompute a Boolean result while the network executes | later writers and task order |
| negated coil | write the inverse of rung continuity where supported | obscured intent and translation differences |
| set/latch coil | retain a true state after the initiating condition ends | missing reset and restart behavior |
| reset/unlatch coil | clear a retained state | set/reset precedence and multiple writers |
| edge/pulse coil | create a transition-limited result where supported | first-scan and re-enable semantics |
Choose the simplest state mechanism that expresses the requirement. A seal-in circuit can be easier to read for a maintained run request; an explicit state machine is often clearer for a multi-step sequence. Avoid set/reset pairs scattered across routines merely because they are convenient to add.
Build a first ladder logic program step by step
Step 1: write the control narrative
Use a motor run request as a learning example. It is not a motor starter wiring drawing or a safety function. The requirement is:
When the stop path and non-safety permissives are healthy, a momentary start request may latch a motor run request. A stop request, lost permissive, controller initialization, or diagnosed fault removes the request. Independent field feedback proves whether the motor actually ran.
The wording identifies permission, memory, reset events, startup behavior, and feedback. It also refuses to imply that the PLC tutorial replaces an emergency stop, guard system, overload protection, isolation, or risk assessment.
Step 2: define the tag contract
| Tag | Type | Source/owner | Meaning | Initial test state |
|---|---|---|---|---|
StartRequest |
BOOL | conditioned input/HMI contract | momentary operational request | false |
StopPathHealthy |
BOOL | conditioned input | operational stop path is healthy | false |
PermissivesOK |
BOOL | control program | all documented non-safety start conditions true | false |
FaultActive |
BOOL | diagnostic program | blocking equipment fault exists | false |
MotorRunRequest |
BOOL | motor-control owner | request to the approved drive/starter interface | false |
MotorRunningFeedback |
BOOL | conditioned field feedback | independent evidence of running state | false |
StartTimeout |
BOOL | motor-control owner | request did not produce feedback in allowed time | false |
Use a safe default for test initialization. On real equipment, the risk assessment and control philosophy determine safe state, energy isolation, stop categories, and restart prevention.
Step 3: express the Boolean requirement
MotorRunRequest :=
StopPathHealthy
AND PermissivesOK
AND NOT FaultActive
AND (StartRequest OR MotorRunRequest);
In LD, place the three required conditions in series. Put StartRequest in parallel with a positive MotorRunRequest contact before the ordinary MotorRunRequest coil. The feedback does not belong in the sealing branch: command and proof are separate states.

The figure is conceptual. Verify the target editor's branch execution, contact, coil, and startup behavior before implementation.
Step 4: add command-to-feedback diagnostics
When MotorRunRequest becomes true, start a non-retentive on-delay timer whose preset comes from the equipment specification. If MotorRunningFeedback arrives, the mismatch condition clears. If the timer completes first, raise StartTimeout and apply the documented equipment response. A real project may also diagnose “feedback on without command,” contactor disagreement, drive state, or process proof such as flow.
Do not turn a tutorial timeout into an unreviewed trip. The appropriate alarm, inhibit, shutdown, reset, and retry policy depends on the machine and hazard analysis.
Step 5: execute a complete acceptance matrix
| Case | Initial state/action | Expected request | Expected diagnostic |
|---|---|---|---|
| safe initialization | all inputs false; start task | 0 | no false running indication |
| blocked start | start true, permissive false | 0 | unavailability reason visible |
| accepted start | healthy, permissive, no fault, start pulse | 1 | feedback timer begins |
| seal-in | release start after accepted request | 1 | no timeout if feedback arrives |
| operational stop | stop path becomes unhealthy | 0 | expected stopped transition |
| permissive loss | permissive becomes false while requested | 0 | reason recorded according to design |
| blocking fault | fault becomes true | 0 | fault state and reset policy apply |
| missing feedback | request true; feedback withheld | design-specific | timeout after documented preset |
| false feedback | feedback true while request false | 0 | mismatch diagnostic if required |
| controller restart | restart in every relevant phase | documented initial state | no unintended restart |
| HMI/network loss | disconnect request source | controller-owned state policy | stale command is not replayed |
Record actual values, timestamps, software version, tester, and result. “The rung turned green” is useful observation, not an acceptance record.
Timers, counters, and edge detection
Choose from the physical question
Use a timer when the requirement concerns elapsed time: “feedback must arrive within three seconds.” Use a counter when it concerns qualified events: “ten accepted parts complete the batch.” Use edge detection when one physical or logical transition must generate one event despite remaining true for multiple scans.

| Requirement | Likely construct | Boundary tests |
|---|---|---|
| delay an action while condition remains true | on-delay timer | before preset, exactly at completion, condition drops, restart |
| keep an indication after condition drops | off-delay or explicit state | short pulse, reassertion, restart, mode change |
| measure runtime | accumulating timer or timebase calculation | pause, reset, overflow, retention, clock behavior |
| count parts | counter driven by qualified rising events | held sensor, bounce, simultaneous reset, rollover |
| accept one button press | edge or command sequence | long hold, rapid presses, reconnect, first scan |
Timer semantics are platform-specific
An IEC-style TON function block commonly has an input IN, preset PT, elapsed time ET, and output Q. A Rockwell TON instance exposes a different structure and platform-specific status members. Other editors use their own names, time literal syntax, resolution, retentive variants, and enable/reset behavior.
Do not copy a numeric preset such as 50 between systems. One system may interpret a time literal; another may use a configured base; another may reject the value. Use explicit documented time types where available and test the transition before, at, and after the preset.
Counters count transitions, not meaningful products
A sensor held true for 100 scans should normally represent one part event, not 100 parts. Qualify the signal with edge detection, debounce or minimum-on/off rules where required. Define whether rejected parts count, how direction reversal behaves, who can reset the batch, what happens at rollover, and whether the accumulator survives power loss.
| Counter defect | Likely cause | Better evidence |
|---|---|---|
| counts continuously while sensor is high | level used instead of qualified edge | trace source and one-shot state |
| misses close events | task/update rate or filter exceeds pulse spacing | measured pulse width and task timeline |
| doubles intermittently | bounce/noise or duplicated event path | timestamped raw and conditioned signals |
| batch returns after restart | retentive accumulator without startup policy | retention configuration and restart test |
| reset races with count | order or two writers | execution trace and single-owner design |
Edge detectors have startup state
An edge detector compares current and previous state. Therefore its behavior depends on how the previous-state memory initializes, whether the instruction executes every scan, and what happens when a routine is disabled and re-enabled. Test an input already true at startup, an input that changes while the routine is not executing, and a download or warm restart. Never assume “one shot” means the same lifecycle across platforms.
Sequence control and state machines in ladder
Use named states for multi-step behavior
Scattered latch bits can make a sequence work while hiding which combinations are legal. An explicit state model gives each phase one name, defines allowed transitions, and assigns timeouts and recovery rules. The state can be an enumerated value, an integer with named constants, or mutually exclusive bits with an invariant test; the best representation depends on the platform and team.

For a simple conveyor cell:
| State | Entry condition | Actions | Exit/timeout |
|---|---|---|---|
Idle |
initialization or completed reset | outputs off; ready condition evaluated | start request while available |
Starting |
accepted start | command conveyor; wait for feedback | feedback true → Running; timeout → Faulted |
Running |
running feedback proven | permit product sequence; monitor faults | stop → Stopping; fault → Faulted |
Stopping |
stop requested | remove run request; wait for stopped proof | feedback false → Idle; timeout → Faulted |
Faulted |
diagnosed blocking condition | hold documented operational state; expose cause | reset allowed only when conditions satisfied |
Recovery |
authorized reset accepted | re-establish known state without automatic restart | successful checks → Idle; failure → Faulted |
Separate permissives, interlocks, trips, and reset conditions
These words are used inconsistently between sites, so define them in the project glossary. A practical, non-safety convention is:
- permissive: a condition required to start or enter a state;
- interlock: a condition that blocks an action or transition;
- trip or fault response: an action taken when a diagnosed condition occurs;
- reset condition: evidence required before clearing a latched fault;
- safety function: a risk-reduction function implemented and validated in the appropriate safety-related control system.
Do not bury all conditions in one AllOK bit. A summary may drive the final decision, but reason bits or codes must remain available for diagnostics. The HMI should tell an operator why a start is unavailable instead of showing only a grey button.
Define every transition as a testable contract
For each transition, record source state, trigger, guards, action, destination, timeout, fault response, reset authority, and evidence. Then test illegal as well as legal transitions. If Running can become Idle without passing through the commanded stopping behavior, either the design permits that path or the implementation has an unreviewed shortcut.
Add invariants to the test plan. Only one exclusive state should be active. A faulted state must not issue a new automatic run request. Recovery must not silently re-enter production. Every transient state needs a timeout or an evidence-based reason why it cannot stall. These invariants catch defects that individual happy-path examples miss.
Data, analog values, math, and function blocks
Ladder can call more than Boolean instructions
Modern LD networks can call functions and function blocks for comparison, arithmetic, scaling, timing, motion, communication, and reusable equipment behavior. CODESYS and Beckhoff documentation describe networks that can contain expressions and program, function, or function-block calls. This does not mean every calculation is clearest in ladder.
Use the language that makes the responsibility easiest to review on the target team. Boolean equipment interlocks often read well in LD. Array processing, parsing, loops, and complex calculations may read better in Structured Text. Continuous signal flow may fit FBD. Sequential Function Chart may fit a formal sequence. Mixed-language applications are normal when interfaces and ownership are explicit.
Scale analog signals with engineering evidence
A generic linear scaling equation is:
EngineeringValue =
EngineeringLow
+ (RawValue - RawLow)
* (EngineeringHigh - EngineeringLow)
/ (RawHigh - RawLow)
The arithmetic is only one part of the block. A production implementation also handles data type and overflow, divide-by-zero configuration, underrange/overrange, channel diagnostic quality, substitute-value policy, units, calibration evidence, alarm limits, and simulation ownership.
| Scaling test | Inject | Expected evidence |
|---|---|---|
| lower endpoint | RawLow |
EngineeringLow within tolerance |
| upper endpoint | RawHigh |
EngineeringHigh within tolerance |
| midpoint | halfway raw value | calculated midpoint within rounding rule |
| underrange | below valid raw threshold | bad/underrange status, not a plausible healthy number |
| overrange | above valid raw threshold | bad/overrange status |
| invalid configuration | RawHigh = RawLow |
explicit configuration fault; no divide-by-zero |
Encapsulate repeated equipment behavior
A reusable motor or valve function block can expose commands, mode, availability, state, feedback, alarm, and diagnostic reason consistently. Reuse is valuable only when the block's interface, versioning, tests, and instance data are controlled. Copying one giant “universal device” block into every project can create as much coupling as duplicated rungs.
Create a narrow interface, document defaults and retention, simulate failure states, and version changes. Use composition—such as a standard motor block plus project-specific permissive calculation—when one block would otherwise accumulate every site exception. Require a migration note when a library version changes stored instance data or execution behavior.
Vendor dialect map without false equivalence
Concepts that usually translate
| Concept | Rockwell Logix | Siemens | CODESYS / Beckhoff | Other IEC ecosystems | Translation caution |
|---|---|---|---|---|---|
| positive Boolean test | XIC-style instruction | LAD contact | LD contact | contact | naming says little about field-device normal state |
| negative Boolean test | XIO-style instruction | negated contact | negated contact | negated contact | test the tag value, not the symbol nickname |
| Boolean write | OTE-style coil | coil assignment | coil | coil | multiple writers and task order differ |
| retained set/reset | latch/unlatch family | set/reset coil | set/reset coil | set/reset coil | precedence, retention, and first-scan policy |
| on-delay timing | TON instance | IEC/vendor timer form | TON function block | timer instruction/block | member names, time syntax, and reset behavior |
| one transition | one-shot instruction/storage | edge detector | R_TRIG or editor element | vendor edge form | startup and enable semantics |
This table is an orientation map, not a compatibility matrix. Rockwell's Logix Designer ladder manual, Siemens' S7-1200 system manual, the CODESYS Ladder editor overview, and the TwinCAT Ladder Diagram reference are starting points. Always navigate to the documentation version for the installed tool and CPU.
Execution order is a migration risk
CODESYS documents left-to-right and top-to-bottom processing and a normalization change for branches in a specific Ladder editor version. That is exactly why a migrated project needs behavioral tests: even within one ecosystem, editor evolution can affect how an existing network is interpreted or normalized.
Inventory every feedback path, branch, set/reset pair, stateful function block, indirect reference, jump, subroutine call, and multi-task shared tag. Freeze a baseline test on the source system, translate, then compare state traces on the target. A clean compilation proves syntax and type consistency, not equivalent behavior.
Online edits, forces, and downloads need a procedure
Vendor tools differ in how edits are staged, tested, assembled, downloaded, and rolled back. Forces can outlive the troubleshooting moment or mask a logic result. Downloads can initialize state or affect running equipment. Treat these as controlled operational changes:
- identify the exact controller and current source version;
- obtain authorization and establish communication ownership;
- back up and compare the online project;
- understand affected tasks, state, outputs, and redundancy;
- prepare rollback and stop criteria;
- apply the smallest approved change;
- run the acceptance tests and remove all forces;
- archive the as-left version and evidence.
A professional ladder programming workflow
Start with requirements and cause/effect, not rungs
Before opening the editor, collect the control narrative, I/O list, P&ID or electrical drawings, equipment manuals, operating modes, alarm philosophy, cause-and-effect requirements, network architecture, safety requirements specification where applicable, and site programming standard. Resolve ambiguous verbs such as “stop,” “reset,” “available,” and “fault” into observable states.
| Requirement field | Example | Acceptance implication |
|---|---|---|
| trigger | operator start request | pulse/level and ownership are defined |
| guards | auto mode, upstream ready, no blocking fault | each unavailable reason is visible |
| action | issue conveyor run request | command is separate from feedback |
| success | running feedback within approved time | timeout boundary is tested |
| abnormal response | feedback lost while requested | alarm/state response is specified |
| restart policy | no automatic restart after controller power cycle | startup test is mandatory |
Design tag ownership and program structure
Draw a small responsibility map: which routine conditions inputs, which owns each equipment state, which sequence requests the equipment, which function writes the physical output, and which interface exposes HMI state. Use naming that communicates equipment, signal, and role. Avoid embedding addresses in every rung; retain the I/O mapping separately and cross-reference it.
Choose task placement from response and determinism requirements, not convenience. Document data shared between tasks and controllers. If a fast task produces a pulse that a slow task consumes, use a handshake or retained event representation instead of hoping the slow task observes one execution.
Review the design before commissioning
A peer review should challenge failure behavior, not just style. Ask:
- Can any output have more than one uncontrolled writer?
- Can a restart energize an output without a fresh approved request?
- Does every latched state have a reachable reset and a visible reason?
- Are command and feedback separate?
- Are timers and counters tested at their boundaries?
- What happens when a routine is not scheduled or a device is unavailable?
- Are simulations and forces obvious, authorized, and removable?
- Does the program expose actionable diagnostics without bypassing protection?
- Are safety functions isolated in the required safety-related architecture?
Build tests from the requirement rows
Turn every “shall” into one or more tests. Include normal, negative, boundary, sequence, restart, communication-loss, quality, permissions, and recovery cases. Where feasible, automate simulator tests and retain deterministic inputs and expected states. Hardware FAT and SAT should add physical I/O, device mode, wiring, timing, network, and process evidence.
Testing a ladder program before the real machine
Use layers of evidence
| Layer | What it can establish | What it cannot establish alone |
|---|---|---|
| static review | naming, ownership, cross-references, unreachable-looking logic | runtime timing or physical behavior |
| unit/function-block test | deterministic input/output/state behavior | controller/application integration |
| software simulation | sequences, timers, faults, restarts within the model | actual module, network, drive, field and process behavior |
| controller emulator | closer runtime/task semantics where supported | every target firmware and I/O condition |
| hardware-in-the-loop/FAT | controller, selected I/O/devices, communications and timing | final installation and process conditions |
| site acceptance | installed wiring, devices, networks, process and operators | future changes or every rare condition |
The free ladder simulator can exercise learning rungs and input matrices in a browser. Ownership disclosure: PLC Programming operates PLC Simulation Software. The browser tool uses a learning-oriented dialect and is not Studio 5000, TIA Portal, CODESYS, TwinCAT, Sysmac Studio, EcoStruxure Machine Expert, GX Works, a production PLC, or a safety controller. Confirm current capabilities and access boundaries in the versioned product facts.
Test histories, not only input combinations
Stateful logic can produce different outputs for the same current inputs because the history differs. A truth table is enough for purely combinational logic. Timers, counters, latches, and state machines need event sequences.
| Test history | Why it matters |
|---|---|
| input already true when task starts | exposes edge and initialization behavior |
| brief input shorter than task period | exposes missed-event risk |
| enable disappears just before timer preset | verifies reset/pause behavior |
| reset and count occur together | exposes precedence |
| fault occurs during each sequence state | verifies state-specific response |
| controller restarts during each state | verifies retention and restart policy |
| network disconnects after request but before acknowledgement | detects stale/replayed command risk |
Add mutation-style fault injection
A strong test should fail when the logic is wrong. Deliberately negate a contact, remove a permissive, change a timer boundary, swap a state destination, retain a bit across restart, or force missing feedback in a test copy. If the test suite still passes, it does not protect that requirement.
For physical testing, inject faults through approved simulators, test panels, or documented procedures. Do not create hazardous field conditions merely to demonstrate a rung response.
Troubleshoot ladder logic from evidence
Start at the symptom boundary
Describe the symptom as an observable disagreement: “MotorRunRequest is true, but MotorRunningFeedback remains false for five seconds,” not “the PLC is broken.” Record time, mode, controller state, sequence state, active faults, I/O quality, network condition, and recent change. A precise boundary prevents random edits.
Then trace one direction at a time:
- Was the initiating request present and fresh?
- Which permissive or interlock blocked acceptance?
- Did the expected program and task execute?
- Which rung or owner last wrote the command?
- Did the output module receive and energize the channel?
- Did the field device accept the command?
- Did independent feedback or the process respond?
Use a failure matrix
| Symptom | Likely hypotheses | Best first evidence |
|---|---|---|
| rung never becomes true | wrong tag, negative contact, unavailable condition, routine not executing | online tag path and task/routine status |
| coil flashes but does not remain | missing seal-in, later writer, mode arbitration | cross-reference and scan trace |
| timer never completes | enable drops, preset/timebase wrong, reset path active | enable, elapsed, preset and reset states together |
| counter increments too many times | level counted, noisy input, duplicate event path | raw/conditioned signal trace and cross-reference |
| sequence skips a state | overlapping transitions, order, retained state | transition trace with source and destination |
| output tag true, channel off | mapping, inhibit, force, module/device diagnostic | module tree, force table, channel measurement |
| device runs, feedback false | feedback wiring, mapping, sensor/device fault | physical feedback and raw input diagnostics |
| only fails intermittently | timing, race, network update, vibration/noise, resource load | synchronized trace and environmental context |
Treat forcing as a controlled diagnostic tool
Forcing an input can isolate a logic path; forcing an output can bypass layers of program protection and move equipment. Follow the site's authorization, isolation, communication, and force-removal procedure. Prefer simulation or a test bench. Before leaving a controller, verify the force table, overrides, temporary code, simulation flags, and bypass register are clear and recorded.
Prove the repair against the original failure
A repair is not complete when the symptom disappears once. Reproduce the original test, run adjacent boundary cases, confirm no new writer or bypass was introduced, remove diagnostic changes, compare the approved source, and retain the trace. If the root cause was timing or noise, demonstrate the result under the conditions that previously triggered it.
Common ladder programming mistakes
Confusing physical normal state with Boolean meaning
Fix this at the input contract. Name the conditioned tag for the state the logic needs—GuardClosed, PressureHealthy, StopPathHealthy—and document what raw voltage, channel value, diagnostic quality, and failure mode produce that Boolean. Then the rung can read like the requirement.
Showing command as if it were feedback
An HMI lamp driven by MotorRunRequest proves only that software requested operation. It does not prove contactor closure, drive running state, shaft motion, or process flow. Display command and verified feedback separately, with a mismatch timer and actionable reason where the application requires it.
Hiding every reason behind one permissive bit
AllPermissivesOK can keep the final rung short, but maintenance needs the failed contributors. Preserve a reason mask, structured status, or individual diagnostic tags. Test that each unavailable condition produces the expected operator message and does not leave a stale reason after recovery.
Using latch instructions instead of defining state
A latch is an implementation tool, not a requirement. If no one can answer who sets, who resets, what survives restart, and which state combinations are illegal, rewrite the behavior as an explicit state contract. Retentive instructions should be deliberate and reviewed.
Leaving timer, counter, and numeric boundaries implicit
Specify units, ranges, signedness, overflow, rounding, rollover, retention, and reset. Test one value below, at, and above every important boundary. Values from an HMI or network must still be validated by the controller owner.
Solving a wiring or device problem with code
If the output channel is energized but the contactor does not pull in, changing a rung may hide rather than repair the fault. Keep the diagnostic layers distinct. Inspect module diagnostics, approved electrical measurements, device status, protection, wiring, and feedback. Qualified personnel must follow electrical safe-work practices.
Commissioning and change control
Prepare an as-left evidence package
Before commissioning, establish controller identity, firmware, engineering-tool version, application checksum or revision, I/O and network configuration, safety validation boundary, test plan, backup, rollback procedure, and responsible people. After commissioning, archive the exact as-left source and generated artifacts, completed tests, unresolved deviations, force and override check, and change approvals.
| Gate | Minimum evidence |
|---|---|
| source identity | controller comparison and approved version |
| I/O checkout | channel, polarity, range, quality and device feedback |
| logic FAT | normal, negative, boundary, sequence, restart and communication tests |
| safety boundary | approved risk assessment and separate safety validation records |
| security | named access, least privilege, protected engineering path and logging per site plan |
| recovery | tested backup, restore and rollback procedure |
| release | deviations accepted, operators briefed, overrides clear, as-left archive complete |
A good commissioning sheet distinguishes expected, actual, result, tester, time, version, and evidence reference. It also states which tests were simulated, bench-tested, or witnessed on the installed equipment. That provenance prevents a software-only test from later being mistaken for a complete machine acceptance test.
Keep standard control separate from functional safety
This motor example is standard control education. A safety function includes sensors, logic, final elements, diagnostics, architecture, response time, lifecycle, verification, validation, proof testing, and change control selected from a machine- or process-specific risk assessment. A standard ladder rung, simulator result, or normally closed graphic does not establish SIL, PL, category, or legal compliance.
Emergency stops, guard functions, burner management, overpressure protection, and other consequential functions require the appropriate standards, certified products where required, safety manuals, competent engineering, and witnessed validation. The standard PLC may receive safety status for coordination but must not override the safety system's safe state.
Protect the engineering workflow
NIST SP 800-82 Rev. 3 treats PLCs and engineering workstations as operational-technology assets whose availability, integrity, architecture, access, remote connectivity, patching, and recovery require risk-based controls. Use named accounts, least privilege, segmented and monitored engineering paths, protected remote access, application allowlisting where appropriate, backups, change logs, and incident procedures according to the site's OT-security program.
Do not expose a controller directly to the public internet for convenience. A simulator or lab should use synthetic data and isolated equipment unless the approved architecture explicitly provides a controlled integration. A source file downloaded from an unknown forum is not a trusted commissioning artifact: review its provenance, scan it according to site procedure, compare every instruction, and never execute it on a connected plant merely because the extension opens in the vendor tool.
How to choose ladder programming software
Start from the target controller
For production work, the controller family and firmware usually determine the approved engineering environment. Evaluate exact CPU support, license, operating system, communication driver, simulator or emulator, online edit, source comparison, library management, version control, safety edition, and lifecycle support. Product names and entitlements change; verify the current vendor matrix.
| Need | Evaluation proof |
|---|---|
| first-time learning | build contacts, branches, timers, counters, states and tests without hardware |
| existing plant maintenance | upload and compare the exact installed controller safely |
| new machine development | configure exact CPU, I/O and network and complete a matched pilot |
| team reuse | create, version, test and migrate a reusable block |
| troubleshooting | cross-reference, online state, trace, force governance and diagnostics |
| controlled deployment | backup, compare, download, rollback and audit workflow |
The PLC programming software guide owns broad tool selection. This tutorial explains how to build and verify the program, not which commercial package is universally “best.”
Run a proof-of-fit project
Use the same representative task on each shortlisted platform: condition one input, execute the motor request and feedback timeout, count qualified events, run a small state sequence, expose diagnostics, restart the runtime, compare versions, and restore a backup. Score the actual target versions. Marketing screenshots cannot prove engineering workflow, migration effort, or runtime semantics.
Include the people who will maintain the system. Measure how long they need to locate the last writer, explain an unavailable start, trace a timer reset, compare online and offline source, remove a force, and recover from an interrupted engineering session. A platform is not a good fit merely because the original developer can use it quickly.
Know what a browser simulator can and cannot prove
A browser lab is useful for Boolean reasoning, scan traces, timer and counter exercises, state transitions, and deterministic test matrices. It cannot by itself reproduce the target compiler, CPU scheduler, I/O module, firmware fault handling, industrial network, drive, electrical system, process dynamics, cybersecurity architecture, or safety lifecycle. Transfer the concept, then revalidate on the approved platform.
Use the simulator's limits as part of the lesson. If its timer model or instruction name differs from the target, document the difference and translate from the requirement. That habit is safer than memorizing one vendor's shapes without understanding state.
A four-week ladder logic learning plan
Week 1: Boolean and scan reasoning
Build only combinational rungs. Translate ten written requirements into series, parallel, and negated conditions. Predict the result before running each case. Trace why a false condition blocks the path. End the week with a truth-table test for a three-input permissive and an explanation of why a contact is a test of program data rather than a physical conductor.
Week 2: state and time
Build a seal-in request, on-delay feedback timeout, qualified event counter, and edge detector. Test startup, release, reset, simultaneous events, and values just before and at the preset. Explain where each instruction stores memory and what happens when the routine stops executing.
Week 3: equipment and sequences
Create a motor or valve state block, then a five-state conveyor sequence with explicit transitions, timeouts, and recovery. Add reason codes for unavailable starts. Inject one fault in every state and verify the resulting destination. Demonstrate that command and independent feedback are not the same state.
Week 4: troubleshooting and deployment discipline
Break the program deliberately: negate a contact, add a second writer, alter a timer, withhold feedback, restart mid-sequence, and disconnect a simulated client. Diagnose from evidence. Finish with a source comparison, clean force table, backup restore, and signed acceptance matrix.
Progress is demonstrated by repeatable tests and clear explanations, not the number of rungs drawn. The ladder logic examples library provides additional application patterns; keep each example inside its stated learning and safety boundary.
Diagnostic answer map for search and AI-assisted learning
| Expanded question | Direct answer surface |
|---|---|
| What is a ladder language program in a PLC? | it is a PLC program or POU written in IEC 61131-3 Ladder Diagram using networks of contacts, coils and blocks |
| Are ladder logic and ladder diagram the same? | usually yes in PLC work; Ladder Diagram is the standardized language name, while ladder logic is the common name |
| How do I write my first ladder logic program? | define a tag contract, express the state rule, draw the rung, predict scan behavior, and run normal, fault and restart tests |
| How does a PLC execute a ladder program? | according to configured task and runtime rules, often through ordered networks within a cyclic scan; exact I/O and task semantics are vendor-specific |
| What do contacts and coils mean in ladder logic? | contacts evaluate Boolean conditions; coils write or modify Boolean variables according to their instruction form |
| Why does a ladder output turn on for only one scan? | inspect seal-in or state ownership, later writers, edge logic, task enable and reset conditions with a scan trace |
| Should I use a timer or counter? | use timers for elapsed time and counters for qualified event edges; test reset, retention and boundary behavior |
| How do I program a sequence in ladder logic? | use explicit named states, allowed transitions, guards, timeouts, fault destinations and recovery tests |
| Is IEC ladder logic identical across vendors? | the concepts are shared, but syntax, project model, timing, instruction state, retention and online workflow are not identical |
| Can ladder logic be tested without a PLC? | much program behavior can be tested in simulation, but target hardware, I/O, networks, process and safety still require approved validation |
| How do I troubleshoot a ladder program? | state the mismatch, trace request to output to feedback, inspect the last writer and task, reproduce the fault, then prove the repair |
| When should I use Structured Text instead of ladder? | use the language that makes the task clearest to implement and maintain; complex arrays and algorithms often favor ST, while Boolean equipment logic often favors LD |
Continue from Boolean structure to tested practice
Use the ladder branches and Boolean-logic guide when series/parallel grouping, evaluation order or translation is the main task, and the set/reset ladder guide when state retention, reset priority and startup behavior must be explicit. Use the Omron ladder-logic guide for CX-Programmer/Sysmac translation, or the online ladder-logic simulator guide when the decision is how to practise contacts, coils, timers, counters and fault cases in a browser before repeating them in the exact vendor toolchain.
Frequently asked questions
What is a ladder language program in a PLC?
A ladder language program is controller software implemented in Ladder Diagram (LD), the graphical PLC language standardized within IEC 61131-3. It uses ordered networks or rungs containing contacts, coils, functions, and function blocks. A complete controller application can also include hardware configuration, tasks, data, communications, and programs written in other languages.
Are ladder logic and ladder diagram the same thing?
In most PLC conversations, yes. Ladder Diagram is the formal language name, while ladder logic is the common engineering name. Vendors may label an editor LD, LAD, or Ladder. An electrical ladder drawing is related historically but is not the same artifact as executable PLC software.
How do I write my first ladder logic program?
Write one observable requirement, define meaningful Boolean tags, choose a safe initial state, translate AND conditions into series contacts and OR conditions into branches, assign one result coil, and predict every test case before simulation. Then test blocked starts, accepted operation, reset, missing feedback, controller restart, and communication loss before moving to hardware.
How does a PLC execute a ladder logic program?
The controller executes ladder inside configured tasks. A common teaching model reads inputs, solves ordered logic, updates outputs, and performs housekeeping, but real systems can use asynchronous I/O, multiple cyclic or event tasks, and platform-specific scheduling. Use the exact controller manual and a trace whenever execution order or response time affects behavior.
What is the difference between a contact and a coil?
A contact examines a Boolean expression and passes logical continuity when its condition is satisfied. A coil writes or modifies a Boolean variable when the network is evaluated. Positive, negated, set, reset, and pulse forms have different semantics. Neither symbol by itself proves the physical state or safety behavior of a field device.
Why does my ladder logic output not stay on?
Common causes are a momentary input without a defined state mechanism, a seal-in condition that becomes false, a later rung or task writing the same tag, a reset instruction, mode or output arbitration, or a routine that is no longer executing. Use a cross-reference and scan trace to identify the final writer and the first condition that changes; do not add a latch blindly.
Should I use a timer or a counter in ladder logic?
Use a timer for elapsed-time requirements and a counter for qualified event transitions. A part sensor normally needs edge qualification so one held signal counts once. For both constructs, define preset units, reset, retention, startup behavior, rollover or overflow, and tests just before, at, and after the boundary.
How do I program a sequence in ladder logic?
Represent each operational phase as an explicit named state. For every transition, define the source, trigger, permissives, destination, timeout, abnormal response, and recovery authority. Test every legal transition, every blocking condition, a fault in each state, and a restart in each state. This is easier to validate than unrelated latch bits scattered through routines.
Is ladder logic identical on Allen-Bradley, Siemens, CODESYS, Beckhoff, Omron, Schneider, and Mitsubishi PLCs?
No. The systems share IEC-style concepts, but instruction names, tasking, tags, timer and counter structures, retention, branch processing, project organization, online edits, and supported extensions differ. Translate the intended behavior, not just the symbols, and rerun the complete test matrix on the exact target runtime and firmware.
Can I learn and test ladder logic without a real PLC?
Yes. A simulator can teach Boolean paths, scan reasoning, timers, counters, state machines, and fault injection. It cannot validate the exact target compiler, CPU, I/O module, network, drive, wiring, process, cybersecurity controls, or safety function. Treat simulation as an early evidence layer followed by target-platform and site testing.
Sources, review scope, and limitations
Official primary sources reviewed
- IEC 61131-3:2025 — Programmable controllers, Part 3: Programming languages, accessed 2026-08-29. Used for the current standard and Ladder Diagram language boundary.
- PLCopen — Logic, accessed 2026-08-29. Used for the current IEC 61131-3 version context and language family.
- PLCopen — IEC 61131-3, accessed 2026-08-29. Used for standardization and language-orientation context.
- PLCopen — Downloads, accessed 2026-08-29. Used for the available Ladder Diagram introductions and technical resources.
- PLCopen — Recognizing an IEC 61131-3 programming system, accessed 2026-08-29. Used for conformance and portability boundaries.
- PLCopen — IEC 61131-10 XML exchange format, accessed 2026-08-29. Used to distinguish exchange standards from assumed behavioral identity.
- Rockwell Automation — Logix 5000 Controllers Ladder Diagram Programming Manual, accessed 2026-08-29. Used for Logix ladder, routine, branch and instruction workflow boundaries.
- Rockwell Automation — Logix Designer Instruction Set, accessed 2026-08-29. Used for current vendor-family instruction-reference context; match the installed release.
- Siemens — S7-1200 Programmable Controller System Manual, accessed 2026-08-29. Used as an official LAD and controller-behavior reference; verify the exact current CPU and firmware manual.
- CODESYS — Overview of the Ladder Editor, accessed 2026-08-29. Used for current network-based editor, monitoring and conversion boundaries.
- CODESYS — Branch processing and normalization, accessed 2026-08-29. Used for the documented processing-order and migration caution.
- Beckhoff — TwinCAT 3 Ladder Diagram, accessed 2026-08-29. Used for the current Ladder editor and IEC language boundary.
- Schneider Electric — Programming languages in IEC 61131-3, accessed 2026-08-29. Used for LD contact, coil, network and wired-OR orientation.
- Omron — Sysmac Studio Version 1 Operation Manual, accessed 2026-08-29. Used for Sysmac ladder-programming workflow context; verify the current manual revision and controller support.
- Mitsubishi Electric — MELSEC iQ-R Programming Manual (Program Design), accessed 2026-08-29. Used for ladder, ST, FBD/LD and program-structure context.
- NIST SP 800-82 Rev. 3 — Guide to Operational Technology Security, published 2023-09, accessed 2026-08-29. Used for PLC, engineering-workstation, access, architecture, recovery and change-control security context.
- OSHA — Control of Hazardous Energy, 29 CFR 1910.147, accessed 2026-08-29. Used for the lockout/tagout and hazardous-energy boundary; jurisdiction and application must be determined by the responsible employer and professionals.
Scope and implementation limits
This tutorial is vendor-neutral education and a verification framework. It is not paste-ready production code, an electrical drawing, a risk assessment, a safety requirements specification, a certified safety function, a cybersecurity architecture, or authorization to connect to or modify equipment. The example state names, timer behavior, sequence, and tests must be adapted to the actual control narrative and target documentation.
Vendor products, manuals, licenses, editor behavior, firmware, instruction sets, compatibility, and online-change workflows evolve. Confirm the exact version and retain a tested backup before work. Qualified personnel must design electrical protection and functional safety, perform safe isolation, approve network access, execute FAT and SAT, resolve deviations, and authorize deployment. The six generated editorial figures are conceptual teaching visuals, not vendor screenshots, wiring references, or evidence that a real controller or machine passed a test.


