Clean Code vs. Dirty Code in PLC Programming – Part Three

Ibrahim Elkhatib
0

Clean Code vs. Dirty Code in PLC Programming – Part Three



Introduction

In the previous articles of this series, we explored the fundamentals of clean code in PLC programming, focusing on naming conventions and effective commenting. If you haven’t read those yet, check out [Part One] and [Part Two] for a solid foundation.

Today, we move further into the practical side of clean PLC code: core programming rules and best practices. These guidelines are essential for building reliable, maintainable, and scalable automation systems, especially as project complexity grows.


Article Contents

  • Introduction
  • Why Coding Rules Matter in Industrial Automation
  • Essential Programming Rules for PLCs
  • Advanced Professional Tips
  • Conclusion


Why Coding Rules Matter in Industrial Automation

As industrial automation projects become larger and more complex, the quality of your code directly impacts system reliability, maintainability, and lifecycle cost. Modern PLC programs often represent a significant portion of project investment and are subject to frequent updates, troubleshooting, and expansion.

Poor code leads to:

  • Increased downtime and troubleshooting costs
  • Difficult upgrades and modifications
  • Higher risk of undetected bugs and production losses

Well-structured, clean code mitigates these risks, making your automation systems robust and future-proof.


Essential Programming Rules for PLCs

1. Eliminate Dead Code

Dead code refers to any logic or instructions that are no longer used or needed.

  • Why remove it?
    • It clutters the program, confuses maintainers, and can introduce hidden bugs.
  • Best practice:
    • If you temporarily disable code, clearly comment why it’s there.
    • Once the program is finalized, delete all unused code and tags.



2. Avoid Overlapping Memory Assignments

  • Never assign multiple variables to the same memory address or register, even if the compiler allows it.
  • Why?
    • Overlapping assignments can cause unpredictable behavior, especially with word/byte/bit splits or system-reserved memory.
  • Pro Tip:
    • Use a memory map (Excel or project sheet) to track memory usage and avoid conflicts.

3. Design Before Coding

  • Invest time in designing your application logic, flow, and data structures before writing code.
  • Use arrays, structs, and function blocks to group related data and logic.
  • Result:
    • Less time spent debugging, more robust and modular code.

4. Restrict Operator Access to Critical Functions

  • Do not expose critical or hazardous functions on the HMI unless absolutely necessary.
  • Limit operator options to what’s required for safe and efficient operation.
  • Why?
    • Reduces risk of accidental misoperation and protects process integrity.

5. Avoid Equality Comparisons for Real/Analog Values

  • Do not use == or != to compare floating-point (REAL) or analog values.
  • Instead, use greater than/less than comparisons or check if values are within an acceptable tolerance (epsilon).
  • Why?
    • Due to scan time and floating-point rounding, exact matches are rare and can cause logic errors.

6. Limit Code Complexity

  • Keep each Program Organization Unit (POU), function, or block under 25 lines where possible.
  • If a section grows too large, split it into smaller, logical modules.
  • Why?

    • Simpler code is easier to test, debug, and maintain.


7. Write to Physical Outputs Only Once per Scan

  • Each output should be assigned a value only once per scan cycle, unless there is a deliberate, well-documented reason.
  • Multiple assignments can cause unpredictable output behavior.


8. Initialize Variables Before Use

  • Always assign initial values to variables before using them in logic.
  • If your platform doesn’t support default initialization, add explicit code to do so at startup.


9. Prevent Mathematical and Overflow Errors

  • Check for possible overflows, divide-by-zero, and ensure variables are sized appropriately for calculations.
  • Use constants and scaling for analog and engineering units.


10. Modularize and Reuse Code

  • Use function blocks, libraries, and templates for repeated logic.
  • Modular code is easier to test, update, and share across projects.


Advanced Professional Tips

  • Prioritize Code Readability:
    • Code is read far more often than it’s written. Use logical names, clear structure, and comments to tell the “story” of your process.
  • Document Everything:
    • Good code is self-documenting, but clear external documentation is invaluable for large teams and future upgrades.
  • Use Version Control:
    • Even for PLC projects, use version control tools or manual changelogs to track modifications.
  • Test in Simulation and Real Hardware:
    • Simulate, peer review, and field test your code before full deployment to catch edge cases and ensure reliability.
  • Review and Refactor Regularly:
    • Schedule code reviews and refactor as needed to keep your codebase clean and efficient.
  • Leverage Platform-Specific Features:
    • Explore advanced features in your PLC platform (e.g., Siemens TIA Portal, Rockwell Studio 5000) like data blocks, user-defined types, and diagnostic tools.


Conclusion

Clean PLC code is not just about style—it’s about delivering reliable, maintainable, and safe automation solutions. By following these essential rules and professional tips, you’ll reduce downtime, speed up troubleshooting, and future-proof your industrial systems.
Remember: readable, modular, and well-documented code is the foundation of every successful automation project.


Post a Comment

0 Comments

Hi, please leave a comment.

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!
To Top