PLC Learning Notes: Basic Introduction (3)

Detailed Explanation of Ladder Diagram Programming and Simulation Debugging

Have you ever wondered how those large and precise automated production lines in factories achieve synchronized and accurate operations? The “brain” behind all this is the PLC (Programmable Logic Controller). Ladder diagrams, as the most classic and intuitive programming language for PLCs, are the key for every automation engineer to open this door. They transform complex logical control into a clear circuit diagram format, making the code not cold, but full of flowing “energy”.

This note will guide you from the most basic components to gradually build classic control circuits, master the magic of debugging programs in a virtual world, and ultimately establish a structured and modular programming mindset. Whether you are a novice entering this field or an engineer looking to solidify your foundation, you will surely find your gains here. Let us unveil the mystery of PLC ladder diagram programming together.

The Language of Ladder Diagrams: Deconstructing the Foundation of Industrial Control

The reason ladder diagrams (LD) have stood the test of time is that they perfectly inherit the “genes” of relay control diagrams familiar to electrical engineers. They simulate the logic of hardware circuits in a software manner, making programming as intuitive as building blocks.

From Relays to Virtual Logic: The Past and Present of Ladder Diagrams

Before the advent of PLCs, industrial control relied on a large number of physical relays, timers, and counters, which formed control cabinets through complex wiring to achieve automation logic. This method was not only costly and bulky but also made maintenance extremely difficult, as modifying logic was almost equivalent to rewiring. The emergence of ladder diagrams “virtualized” these physical components. As pointed out in a technical article, the contacts and coils in ladder diagrams are no longer real physical devices but rather “bits” in the PLC memory, 0 represents OFF, and 1 represents ON. This transformation made modifying logic as simple as editing a document.

The Three Core Elements: Contacts, Coils, and “Power Flow”

To understand ladder diagrams, one must first grasp its three core elements and imagine a “power flow” starting from the left bus trying to reach the right bus.

·Normally Open Contact (NO): Symbolized as `—| |—`. It acts like a “normally open door”, blocking power flow by default. Only when the associated variable (such as an external input signal I0.0) is 1 (ON) does this door close, allowing power flow to pass through.

·Normally Closed Contact (NC): Symbolized as `—|/|—`. It acts like a “normally closed door”, allowing power flow to pass by default. Only when the associated variable is 1 (ON) does this door open, blocking power flow.

·Coil: Symbolized as `—( )—`. It is located at the far right of the rung and represents the result of logical execution. When power flow successfully reaches the coil, the coil is “energized”, and its associated variable (such as an output signal Q0.0) is set to 1 (ON), thereby driving external devices like indicator lights and contactors.

A rung is a line of ladder diagram program, representing an independent logical expression. Whether power flow can pass from left to right determines the final state of the coil.

The Master of Time: Timer On-Delay (TON)

In automation control, delay operations are ubiquitous, such as a motor starting only 3 seconds after a button is pressed. TON (Timer On-Delay) was created for this purpose. You can think of it as a referee with a stopwatch.

·IN (Input): This is the start signal. When there is power flow input at the IN terminal (turning ON), the referee starts timing. If the IN terminal is interrupted midway, the timer will immediately reset to zero.

·PT (Preset Time): This is the target time you set, such as 3 seconds (usually written as T#3s in software).

·Q (Output): This is the state bit of the timer. When the timing reaches the PT value, the Q bit becomes ON and remains so until the IN terminal is interrupted.

·ET (Elapsed Time): Displays the current elapsed time.

In simple terms, the logic of TON is: “When IN is ON, start timing; when timing reaches PT, Q is ON; when IN is OFF, everything resets.” This feature is widely used in various delay start and process control scenarios. Major PLC manufacturers like Siemens and Rockwell Automation provide TON instructions that comply with IEC standards.

The Recorder of Quantity: Count-Up (CTU)

When it is necessary to record the number of occurrences of events, such as how many products have passed on a conveyor belt, CTU (Count-Up) comes into play. It is a faithful counter.

·CU (Count Input): This is the counting signal. Each time the signal at the CU terminal changes from OFF to ON (detecting a rising edge), the current value of the counter increases by 1.

·R (Reset): This is the reset signal. When the R terminal is energized, the current value of the counter is immediately reset to zero.

·PV (Preset Value): This is the target count value, such as 100.

·CV (Current Value): Displays how many times have been counted so far.

·Q (Output): When the CV value is greater than or equal to the PV value, the Q bit becomes ON.

The core logic of CTU is: “When CU receives a rising edge, I add 1; when R is ON, I reset to zero; when the current value reaches the preset value, Q is ON.” It is worth noting that even if CV exceeds PV, as long as it is not reset, Q will remain ON.

From Zero to One: Writing Your First Classic PLC Circuit

Having mastered the basic components, we can start combining them to achieve some classic control functions. These small program segments form the foundation of complex automation projects.

Motor Start-Stop and Self-Locking: The Classic “Seal” Circuit

Imagine if a momentary button is used to start the motor, and the motor stops as soon as you release the button; this is clearly impractical. What we need is “press once to start, press again to stop”. This is where the “self-locking circuit” (also known as the “seal circuit”) comes into play.

The logic breakdown is as follows:

1.A normally open contact (I0.0) acts as the “start button”.

2.A normally closed contact (I0.1) acts as the “stop button”.

3.A coil (Q0.0) represents “motor running”.

4.A key step: connect a normally open contact associated with the “motor running” coil (Q0.0) in parallel with the “start button”.

When the “start button” (I0.0) is pressed, power flows through it and the “stop button” (I0.1) to the coil, starting the motor (Q0.0). At this point, the normally open contact associated with the motor in parallel also closes, forming a new path. Even if you release the start button, power can still flow through this new path to keep the coil energized; this is “self-locking”. When the “stop button” (I0.1) is pressed, its normally closed contact opens, cutting off all power paths, stopping the motor and releasing the self-lock. This design is called “stop priority” because even if the start signal is stuck, pressing stop still ensures the device stops, ensuring safety.

Motor Forward and Reverse Control: The Art of Interlocking Logic

To control the motor’s forward and reverse rotation, two contactors are usually needed, one for forward (e.g., Q0.0) and one for reverse (e.g., Q0.1). However, they must never be energized simultaneously, or it will cause a short circuit! This requires “interlocking”.

The implementation method is simple: in the rung controlling forward rotation, connect a normally closed contact associated with the reverse coil (Q0.1) in series; similarly, in the rung controlling reverse rotation, connect a normally closed contact associated with the forward coil (Q0.0) in series.

In this way, when the forward coil Q0.0 is energized, its normally closed contact in the reverse rung will open, preventing reverse from starting under any circumstances. The same applies in reverse. This design, which uses the state of the opposite to constrain its own starting conditions, is called “interlocking” and is one of the basic principles of safe programming.

Flashing Circuit: Creating Rhythm with Timers

Making an indicator light (e.g., Q0.0) flash in a rhythm of “ON for 1 second, OFF for 1 second” is an excellent case for learning timer combinations. Here is a commonly used dual-timer method:

1.Start: Use a system start bit or a button to start the entire logic.

2.Timer T1 (Light OFF Timing): When the indicator light Q0.0 is OFF (using the normally closed contact of Q0.0), start T1, setting the time to 1 second.

3.Timer T2 (Light ON Timing): When the indicator light Q0.0 is ON (using the normally open contact of Q0.0), start T2, setting the time to 1 second.

4.Core Logic: When T1 timing ends (T1.Q is ON), light up the indicator light Q0.0. When T2 timing ends (T2.Q is ON), extinguish the indicator light Q0.0 (by resetting or cutting off its path).

To keep this cycle going, the completion signal of T2 (T2.Q) is usually connected in series before the start condition of T1, using its normally closed contact to reset T1, thus forming a continuous oscillator. This seemingly simple circuit embodies the core idea of driving logical changes with state and time.

The Virtual World’s Practice Field: The Art of Simulation and Debugging

After writing the program, directly downloading it to a real PLC for operation is extremely dangerous. If there is a logical error, it may lead to equipment damage or even personal injury. Therefore, simulation debugging is an indispensable key step.

Why Simulation is Needed? Rehearsing Everything in a “Sandbox”

PLC simulation software, such as Siemens’ PLCSIM and Mitsubishi’s GX Simulator, creates a “virtual PLC” on your computer. In this safe environment, you can:

·Verify Logic: Test your program to see if it works as expected without connecting any physical devices.

·Save Costs: Avoid hardware damage and production downtime caused by programming errors.

·Improve Efficiency: Complete most debugging work in the office, significantly reducing on-site debugging time.

·Simulate Faults: Create various abnormal situations (such as sensor signal loss) to test the program’s fault tolerance and alarm capabilities.

Practical Exercise: Taking Mitsubishi GX Simulator as an Example

For Mitsubishi PLC users, GX Simulator is a powerful tool, usually part of the GX Works2 or GX Developer programming software. The usage process is very simple:

1.Write the ladder diagram program in the programming software.

2.Click the “Simulation” or “Start Ladder Logic Test” button on the toolbar.

3.The software will automatically call GX Simulator and “download” your program to this virtual PLC.

4.The virtual PLC enters RUN mode, and your program starts executing in the background on the computer.

At this point, you can begin the next debugging operation.

Three Debugging Tools: Online Monitoring, Forcing, and Watch Table

Once in simulation mode, you have three powerful tools to gain insight into the internal world of the program:

·Online Monitoring: This is the most intuitive function. In the ladder diagram editing interface, you will see the lines through which power flows highlighted (e.g., in green), and the opening and closing states of contacts and the energizing status of coils are clear at a glance. You can “see” the execution flow of the program in real-time.

·Forcing: You can manually change the state of a variable to simulate external signals. For example, right-click on an input contact I0.0 and select “Force ON” or “Force OFF” to simulate pressing or releasing a button and observe the program’s response. This is a core means of testing different operating conditions.

·Watch Table: This is a customizable variable list. You can add all the variables of interest (inputs, outputs, current values of timers/counters, etc.) to this table to observe their real-time changing data. As emphasized in a blog by an expert, the watch table is crucial for diagnosing complex logic and tracking data changes.

Common Troubleshooting: When the Program “Misbehaves”

Encountering issues during simulation is common; here are some common “bugs” and their troubleshooting ideas:

·The Motor Fails to Start: Check the start circuit. In online monitoring mode, see where the power flow is stuck. Is the start button not signaling? Or is the stop button or interlock contact open?

·Self-Locking Failure: Check if the self-locking contact is correctly connected in parallel and whether its address matches the output coil exactly.

·Timer/Counter Not Working: Check if their IN or CU terminals have reliable trigger signals. For timers, the IN terminal must remain ON to time. For counters, the CU terminal needs a complete “OFF -> ON” rising edge. Also, check if the reset condition has been triggered unexpectedly.

·Output Opposite to Expectation: Check if normally open/closed contacts are misused. A common mistake is using “AND” logic (series) where “OR” logic is needed, and vice versa.

Debugging Philosophy: Like a detective, work backward from the result. If an output is incorrect, trace back along its rung to see which condition is not met. Use online monitoring and forcing functions to verify your hypotheses one by one.

Farewell to “Spaghetti Code”: Building a Structured Program World

As projects become complex, if all logic is piled into a long ladder diagram, the program will resemble a bowl of spaghetti, chaotic and difficult to read and maintain. This is known as “spaghetti code”. To become an excellent PLC engineer, one must master the concept of structured programming.

IEC 61131-3 Standard: The Cornerstone of Modern PLC Programming

To unify and standardize PLC programming, the International Electrotechnical Commission (IEC) introduced the IEC 61131-3 standard. It not only defines five programming languages (LD, FBD, ST, IL, SFC) but also introduces a modern software architecture model, the core of which is the Program Organization Unit (POU).

This standard encourages us to break down a large program into multiple independent, manageable small units, fundamentally changing the traditional model of a single main program.

Main Program and Subroutines: The “Conductor” and “Special Forces” of Code

In structured programming, programs are divided into different types of blocks, each with its own responsibilities:

·Main Program: In Siemens PLCs, this is usually OB1 (Organization Block 1). It is the entry point and “conductor” of the program, responsible for cyclic scanning and calling other function blocks as needed. Its task is to maintain the clarity of the overall process without getting bogged down in specific execution details.

·Subroutine/Function (FC): These are the “special forces”, responsible for executing a specific, stateless task, such as a mathematical calculation formula. Each time it is called with the same input, it always produces the same output. It has no “memory” of its own.

·Function Block (FB): This is the essence of structured programming. It is also a “special force”, but it has its own “memory” (static variables). As we discussed earlier, timers (TON) and counters (CTU) are typical function blocks. Each time an FB instance is called, it can remember its last state. This makes FBs very suitable for encapsulating the complete control logic of a device (such as a motor or a valve).

Modular Programming: Simplifying Complexity with “LEGO” Thinking

Modular programming involves breaking down complex systems into independent modules based on functionality, and then combining them like LEGO blocks. For example, a conveyor control system can be divided into:

·Motor Control Module (FB): Encapsulates the logic for starting, stopping, forward and reverse rotation, speed control, and fault detection of the motor.

·Sensor Processing Module (FC): Responsible for reading and processing signals from material detection sensors.

·Alarm Handling Module (FB): Manages all possible alarms and drives audible and visual alarms.

The benefits of this approach are enormous:

·High Readability: The main program logic is clear, requiring only a few function block calls, with specific implementations contained within their respective modules.

·Easy Maintenance: If the motor control logic needs modification, only the motor module needs to be changed, without affecting other parts.

·High Reusability: This motor control module can be copied to any other project that requires motor control without rewriting. As emphasized in an article on advanced programming practices, code reuse can greatly enhance development efficiency.

Best Programming Practices: Making Your Code “Speak”

Good code is self-explanatory. Following some simple rules can elevate your program quality:

·Meaningful Naming: Variable names should not be vague like `Temp1`, `Flag2`, but should be clear descriptions like `Motor_Start_Button`, `Conveyor_Running_Status`.

·Detailed Comments: Clearly state the purpose of each rung and each function block. Explaining “why” it is written this way is more important than explaining “what” it is.

·Keep Rungs Simple: Ideally, a rung should accomplish only one core task. If the logic is too complex, consider breaking it into multiple rungs or encapsulating it into a function.

·Establish Documentation: Create a simple document for your project that outlines the overall structure of the program, I/O allocation, and the functions of key modules. This is crucial for team collaboration and long-term maintenance.

Conclusion: From Learner to Creator

From a simple normally open contact to a clearly structured, modular complex program, PLC ladder diagram programming is a journey filled with the beauty of logic. What we learned today is just the starting point of this journey. True mastery comes from continuous practice, debugging, and summarizing.

Do not be afraid of making mistakes, as every failure in simulation debugging is an opportunity to avoid an expensive cost in the future on real devices. Integrate structured and modular thinking into every programming practice, and over time, you will no longer be just a “writer” of code, but an “architect” of elegant, efficient, and reliable automation systems. Now, open your programming software and start creating!

Leave a Comment