Advisory Schedule a Technical Discovery Call — Book your session today! »

· Industrial Programming  · 2 min read

PLC Clean Code Guide: Programming for Tomorrow

Writing code that works is easy; writing code that is maintainable in a plant at 50°C is the real challenge. CASE, State Machines, and Naming Conventions.

Writing code that works is easy; writing code that is maintainable in a plant at 50°C is the real challenge. CASE, State Machines, and Naming Conventions.

In industry, 80% of software cost is not in development, but in maintenance. If your code is only understood by you when you write it, and three months later even you don’t know what that “Timer_1” or “Bit_432” does, you have failed as an industrial programmer.

Programming a PLC (whether in TIA Portal, CODESYS, or Studio 5000) requires discipline. Here are the best practices for writing professional code in Structured Text (ST).

1. Naming Conventions: The End of “Aux_1”

Don’t cut corners. Variables must be self-descriptive. Following a prefix convention (simplified Hungarian style) helps anyone understand the data type without looking at the declaration.

PrefixTypeExample
xBOOLxMotorRunning
iINTiPartCounter
rREAL (Float)rActualPressure
tTIMEtDelayOpen

[!TIP] If a variable is a physical sensor, name it according to the electrical diagram: xLS_Home_Position (LS = Limit Switch).

2. State Machines (CASE): Order in the Chaos

Avoid “Spaghetti Rungs” of interlocking bit logic. For sequences, always use the CASE statement. It’s readable, easy to debug, and ensures that only one state is active at a time.

CASE iState OF
    0: // IDLE
        IF xStart THEN iState := 10; END_IF
    10: // STARTING
        xValveOpen := TRUE;
        IF xSensorLimit THEN iState := 20; END_IF
    20: // RUNNING
        xMotorRun := TRUE;
    999: // FAULT
        xFaulted := TRUE;
END_CASE

I have created a repository with professional state machine templates:

👉 GitHub: plc-clean-code-templates

3. Modularity: Less Copy and Paste

If you have 4 identical motors, don’t copy the logic 4 times. Create a Function Block (FB).

  • Encapsulation: All motor logic lives in one place.
  • Instantiation: If you find a bug, you fix it only once in the FB and it updates in all motor instances.

4. Comments: Explain “Why”, not “What”

  • Bad: xMotor := TRUE; // Motor turns on (Obvious).
  • Good: xMotor := TRUE; // Started by initial lubrication sequence (Useful).

Conclusion

“Clean” code in a PLC saves lives and money. It drastically reduces machine downtime because the technician on shift can understand the failure in minutes.


Technical Sources:

Back to Blog

Related Posts

View All Posts »