10 Tips to Better PLC Programs

10 Tips to Better PLC Programs

In this article I’ll reveal 10 tips to writing better PLC programs. Over the years I’ve seen plenty of badly written and structured programs so I think it’s important that we get some discussion going around this topic.

So what are the 10 tips to better PLC programs? Let’s first run down the list and then later in the article I’ll provide a detailed explanation for each and why you should consider incorporating these tips into your next PLC project.

  1. Understand the fundamentals.
  2. Learn by doing.
  3. Ask lots of questions.
  4. Break larger problems into smaller sub-problems.
  5. Code for re-usability.
  6. Keep it simple stupid.
  7. Write useful comments.
  8. Incorporate standards and naming conventions.
  9. Expect the unexpected.
  10. Ask for help.

Tip #1: Understand The Fundamentals

I guess there’s no better place to start then with the basics. Before embarking on any program of any size and scope it is important to have a sound understanding of the fundamentals. These fundamentals can come in different shapes and sizes, for lack of a better phrase.

If you’re completely new to PLC programming then visiting sites like this one is a good start. The internet can be a wonderful place to learn, share ideas, thoughts and experiences. I should warn you though, the internet can is also be a place of misinformation and dishonesty so choose your resources carefully and stick to reputable sites.

If you are new to PLCs and looking to get started there are lots of free resources here on PLCGurus.NET to get you going – consider registering today. In fact, I did an article recently that explains the basics of programmable logic control, consider giving it a read after you’re done reading this article.

So what if you’re a more experienced programmer looking to expand your skills?
My advice in this respect is, learn multiple platforms whenever the opportunity arises. Don’t get “pigeon-holed” into a single PLC controls platform because its easy or the path of least resistance. There are pros and cons to every PLC platform I’ve encountered and learning as many of them as you can will only make you more marketable and more diverse in the long run.

Often times, the platform you choose will ultimately be customer driven so learning as many as you can will also make your company more profitable. That’s the best part of our job, there’s always more to learn. From IDE’s, to programming, to hardware, to software, to networking, to installing, to commissioning, to troubleshooting – today’s modern day PLC programmer has to have firm knowledge in all of these aspects.

So for tip #1, take advantage of any training you can get your hands on, register for sites like this – it doesn’t cost you anything to do so, therefore, you have nothing to lose – engage other people in the industry, share ideas, share challenges, share solutions. The point here is, if your thirst for knowledge is never quite satisfies then becoming a PLC programmer/System Integrator/Industrial Maintenance Technician is the field for you.

Tip #2: Learn By Doing

Well I think tip #1 is a perfect segue into tip #2 – learn by doing. Reading books, sitting in classes and watching YouTube will only get you so far. At some point, you need to get your hands dirty! If you’re already working in the field or running your own automation company then this shouldn’t be an issue.

I know for me, designing a project from the ground up is one of the most exhilarating feelings there is. And I’m not talking just the programming end of it. From the onset of that first meeting with the customer, when you’re not even sure if you and your company are ultimately going to be awarded the contract, it starts.

Then once you begin working the project, gathering the requirements, brainstorming ideas with colleagues and the customer, generating the controls schematics, spec’ing components, un-boxing those components like it’s Christmas everyday…oh the joy!

Now it’s time to layout and construct that control cabinet and begin the programming phase of the project. This is where the sleeplessness begins. Programming for me is like a black hole in the time-space continuum. I simply lose all concept of it…a finite state of bliss!

And then the day finally comes when your program is somewhat complete, you sling that temporary 3-phase cab-tire feed across the floor and tie-wrap it to the top eye-hook on your panel, and throw the main switch on. Almost instantaneously your control transformer steps down the temporary 3-phase power that will illuminate an array of blinking green and red lights stemming from your shiny new PLC running through its diagnostic processes…exhilarating to say the least.

If you’ve never experienced a complete project like this, you’re probably wondering what is this guy talking about? But I know for a lot of you PLCGurus out there, you know exactly what I’m talking about and its why we love what we do!

Okay so I digressed a little bit during this tip but the bottom line here is, get your proverbial hands dirty with this stuff as much and as often as possible.

Tip #3: Ask Lots of Questions

Ask lots of questions is my advice for tip #3. I’m not just talking with more senior people you know or work with, I’m talking with anyone who has any kind of expertise that can bring you closer to solving the problem or project you are working on.

This will include the end customers, operators, maintenance personnel, machine builders, distributors, OEMs. Every single one of these people will have something to offer that will be of value…I assure you. Automation systems and programs should not be designed and built in a vacuum. If you’re unsure about something, get clarity from whomever is most likely to be able to help you.

In fact, in most instances it will make sense to bounce your question of these multiple people as everyone will have their own unique perspective.

A good solution will embody all perspectives

What do I mean? This means that the end-customer management team (the people paying you) may not have the insight needed that an operator running the machine everyday would, or the operator will not have the same perspective as the maintenance electrician who services the piece of equipment does.

So the main point to tip #3 is, ask as many questions to as many people as possible so that you, the system designer, has the most complete picture of how to solve the problem. It will always cost less to gather as many of the requirements up front then to make guesses along the way and deliver a product that the end-customer didn’t want!

Tip #4: Break Larger Problems into Sub-Problems

For this tip we’re talking Tasks, Programs and Sub-routines. I like to refer to it as divide and conquer. You should always be thinking when embarking on your PLC code “How do I break this problem into smaller sub-problems?”. Luckily, modern IDE’s lend themselves well to this style of programming. For example, Rockwell Automation’s Studio 5000 Integrated Development Environment is moving to a very “VisualStudio’esque” look and feel in its version 31 release. And this is for good reason, Visual Studio is among the best IDE’s on the planet and we are seeing more and more a shift towards a higher-level, object oriented design mentality in the PLC world.

Things like tag scoping – the ability to set visibility rules on your variables. User Defined Types (UDTs) – very reminiscent of structs in C. Add-on Instructions (AOIs)- the ability to encapsulate your code and maximize code re-usability. Cascading of types using dot (.) notation – these are all higher-level programming paradigms that we are now seeing in machine software design.

This power and flexibility really does lend itself to the divide and conquer philosophy. Making it extremely modular and enforces good programming structure. I’m seeing machine programs that are taking these high-level constructs to the n’th degree. Programs that no tag is arbitrarily created, rather it is aType.ofAType.ofAType.ofAType (did you catch the .notation there?) almost to the point where no tag exists without being derived from a cascading of types…again the power of an object oriented approach.

Now with all that, I do feel there is a point where readability and the ability for your average maintenance electrician to have any kind of fighting chance to diagnose a problem, breaks down. If the code is well tried and “bullet-proof” as they say, and every sensor or movement is fully annunciated on an HMI or SCADA detailing the precise issue and corrective action, that’s one thing.

However, the complexity and readability of some of the programs I’ve seen can prove very challenging, and in some cases debilitating in an industrial environment where a failed proximity switch can cause hours of downtime.

Truth is, I’ve yet to see a PLC controlled automation system that can truly say it’s “bullet proof”…if any of you out there disagree and have built such a system, feel free to leave a comment below!

Tip #5: Code for Re-usability

I think tip #4 was a perfect preamble to tip #5 – code for re-usability. The fact of the matter is we are being given all this power under the hood of modern day logic controllers, so why wouldn’t we leverage it to maximize efficiency and build code that’s reusable.

Well to me, again, the only drawback is the one I already eluded to in the previous tip with code readability and maintainability. Aside from that, I think leveraging the power of UDTs and AOIs is an absolute must. Especially if you are tasked with building similar type equipment over and over again and find yourself copying and pasting large portions of ladder logic from one program to another.

In this case, take the time to formulate the code into it’s own drag-and-drop type instruction and have it at your disposal for all future projects. The ability to encapsulate well-tried code and reuse it not only saves time, but also saves money and in the end makes your programs more robust and profitable.

Tip #6: Keep it Simple Stupid

With everything we’ve already talked about, you’re probably wondering how on earth can we keep it simple? Well the truth is the old KISS rule still applies. The general rule when programming any system is to keep simplicity a priority. This should always be a design goal you’re striving for. Try to avoid unnecessary complexities in your programs.

This reminds me of a quote from Martin Fowler, a software engineer who popularized code refactoring.

Any fool can write code a computer can understand. Good programmers write code that humans can understand.

Martin Fowler

Of course, in our world, complexities are sometimes unavoidable, however, I would say follow these simple rules (if you have additional suggestions…comments please!):

  1. Always keep the end-user in mind.
  2. Never let code re-usability trump maintainability.
  3. Avoid premature code optimizations.
  4. Always maintain your commitment to improve the process.

Tip #7: Write Useful Comments

I know, this one shows up in every programming class, book or website. That said, I think PLC programmers are among the worst at commenting their code (self included). I’ve seen countless programs where not a single comment was input.

The truth is we know exactly what we did, why we did it, and where to look next…of course we do, we wrote the program! The problem is, the maintenance electrician who gets called down to the machine on the midnight shift to start troubleshooting your program has absolutely know idea what you were thinking.

I’ll tell you what, let’s all make a deal right now to start documenting our programs better. Code comments always seem to be the lowest on the priority list, but consider this, every line of ladder, function block or structured text you enter into your program is a potential bug. There’s value in taking the time to explain what is you’re doing or the rationale behind the operation of a given section of code. The maintenance electrician will thank you…and believe me, two years from now when you get called back to that piece of equipment to troubleshoot it, you’ll thank you!

Tip #8: Incorporate Standards & Naming Conventions

Whenever possible you should be leaning on any applicable standards in place for the system your designing. Standards provide a framework of design patterns and best practices that are well-tried, so use them whenever possible.

For example, depending on the specific project you’re working on, standards such as ANSI, IEC, NFPA 70e, CSA, UL and many others are all standards and practice associations designed for the betterment and safety of industrial automation components and systems. Use these well-tried standards to help govern your next project, especially when pertaining to any kind of safety related design and programming.

Naming conventions: This is another important aspect to better PLC programs. Use consistent and meaningful file and tag (variable) names when programming your next automation system. Avoid cryptic names that mean nothing other than to the people who designed it.

I’ve seen far to often naming conventions (file and variable) that look like some kind of cryptic alpha-numeric code phrases that I’m sure mean something to someone, somewhere, however, mean absolutely nothing to the engineers or technicians tasked with servicing the equipment. Going back to Tip #6 – Rule #1, the naming conventions you adopt and deploy should consider the end-user.

Here are some naming convention best practices:

  1. Use capital letters or underscores to delimit words, not spaces. Example myTag or my_tag.
  2. Keep file names short, but meaningful.
  3. If using a date in the file name always state the date “back to front” and in this format: YYYY or YYYYMM or YYYYMMDD.
  4. Order the elements in a file name in the most appropriate hierarchy to retrieve records.
  5. When including numbers in a file name, always give it as a two-digit number rather than one.
  6. When a version number is required, make sure it appears in the file name.
  7. Use meaningful directory names.

Tip #9: Expect the Unexpected

This is one that is always interesting…expect the unexpected. This can range from anything like mid-project scope changes to unexpected program anomalies, unexpected process dynamics, or flat out project failures. One project will always stand out for me that no one saw coming…let me explain!

It was early in my career as young engineer where I worked for a Tier 2 integrator to one of the big 3 (at the time anyway) auto suppliers and it was my job to oversee the installation and commission the cell. I should mention that both the plant the system was installed in, and the company I worked for has since shut down. The reason this particular project stands out for me is because, well quite frankly, it never worked, nor was it ever going to work!

After the initial install, which took approximately two weeks, I was flying back and forth from Toronto to Atlanta every weekend for about 4 months while the line was not operational to continue commissioning the cell.

To outline the project, we utilized two Kawasaki 6-axis articulated robots on either side of the vehicle assembly line with a main “cell level” Allen-Bradley ControlLogix controller. The task of the robots was to install both the front driver side and passenger side seats in the vehicle so they could be fastened at the next operation by a human operator. These were previously being “hand-bombed” in the vehicles by human operators on either side, which of course was leading to ergonomic repetitive strain type injuries.

The cell had two lines, one carrying the vehicles as mentioned, and another line beside it carrying the seats to be installed in that vehicle, they were synchronized with the seat conveyor slightly ahead of the vehicle they were to be placed in (approximately one car length). The image above is a crude rendering to give you a visual.

We had a robot on either side of the line mounted to a tracking vehicle (7th axis) that would clamp on to the vehicle and free wheel along-side it as it indexed through the cell (after installing we would unclamp and drive the robot vehicle back – VFD controlled motor driven back).

The basic sequence of operation was as follows:

  • The driver/passenger seats would index into the cell slightly ahead of the vehicle they were to be placed.
  • A pneumatic (PLC controlled) Fixture Station would positively locate the seats and halt the seat-line via a hard-wired interlock.
  • The passenger-side robot would unload the driver seat and place it onto the “Overhead Driver Seat Fixture”.
  • Once cleared of the overhead fixture (via software interlocks), the Driver-side Robot would unload its seat from the overhead fixture and at the same time the Passenger-side robot would unload the passenger seat from the seat fixture station.
  • Both robots would now be holding their respective seats and waiting in the “pounce” position to clamp up to the vehicle and track. Therefore, it was imperative that all of this material handling took place before the vehicle exited the permitted “clamping window” (this was not accounted for in the original design!).
  • Once confirmed clamped and tracking, the robots would proceed to install the seats into the vehicle and the seat fixture station would be released and the seat conveyor turned back on allowing the next pallet of seats to enter the cell.
  • After successful installation, the robot vehicles would be motor driven back to the home switch and the process would repeat.

As noted above, there was no contingency built into the system to abort the process if the clamping window was missed other than to stop the vehicle line (via another hard-wired interlock), however, this was not an acceptable solution to the customer for obvious reasons.

The exact timing escapes me now, however, I do recall that by the 8th or 9th vehicle cycle we would essentially have no choice but to stop the line. With every cycle, there was a small accumulation of cycle time error, error that was not accounted for – it was time to go back to the drawing board!

What was eventually designed, built and shipped down to me to remedy this problem was a set of pneumatic turntables that we would place at the ends of either side of the line so in the event we missed the “clamping window” we would drive the robot vehicles with their respective seats down to the end of the track as quickly as possible using the variable speed drives, initially designed to only drive us back to the home position, and place them on the turntables. Of course, my job was to integrate the program logic necessary to achieve this and subsequent robot programming – now of course “under the gun” as they say to get it all working!

The operators at the exit point of the cell (outside of the perimeter guarding at the turntables), there to secure the seat bolts and make the required seat electrical connections (power seats only), would be able to operate a push button that would rotate the seats out of the cell, and then by means of a manual pneumatic pick and place system be able to unload the seats from the turntables and manual place them in the vehicle…a band-aid to the problem at best, however, it would save us from stopping the main vehicle line.

The remaining months (week-end travels) I spent optimizing robot positions, program logic and recovery to try to get as much cycle time out of the process as possible, however, the efforts were futile as the required cycle-time was simply unattainable. The lead design engineers on the project failed to do a proper cycle time analysis during the design phase at the onset of this project. As a result, the project ultimately was shut-down and removed, however, I felt it was important to share this example of how, while we try everything to succeed, sometimes we get unexpected results and even worse…project failures.

Tip #10: Ask for Help

The last tip I’m going to leave you with is to ask for help. There is no shame in admitting you don’t know or fully understand something. What you don’t want to be doing is spinning your wheels indefinitely try to solve something or find something in a program that isn’t immediately apparent to you.

I don’t know how many times I’ve toiled over an issue for hours and then finally when asking for help, and getting a fresh set of eyes on it, the problem is found within minutes…embarrassing yes, but a relief nonetheless. This works both ways too, in my opinion “tunnel-vision” is a real thing and sometimes once you get started down a path even the most obvious things seem difficult. Heck, the catch phrase here at PLCGurus.NET is “A problem is only hard until you know how to solve it…then it’s trivial”. This really couldn’t be a truer statement.

A couple of guidelines to follow when it’s time to ask for help:

  1. First try to solve the problem yourself – learning by doing is the best way (and also Tip #2).
  2. Try to narrow down the problem – it will be easier to ask for specific help.
  3. Provide enough detail – when asking for help make sure to include all relevant details.
  4. Don’t be lazy! I know this sounds obvious but keep in mind when you’re asking for someone else’s help they have to stop what they’re doing to help you.
  5. Be patient. Unless you’re paying for someone’s help have patience. There are plenty of people out there who will be willing to share their knowledge and expertise.

Final Words…

Well I hope I’ve given you some things to think about and have provided you some good tips to make you not only a better PLC programmer but also a better engineer, technician or technologist in your field.

If you haven’t done so yet, I do encourage you to become what is quickly becoming one of the largest and fastest growing communities of professional engineers, technicians and technologists. Registration is and will always remain completely free. Register Here!

Also, check out our YouTube Channel to see some great videos…and don’t forget to like and subscribe to our channel! If you enjoyed this article be sure to check out some of these good reads too:

Lastly, if you run  into any problems in your day-to-day engineering activities please be sure to check out our Live and Interactive PLC Forum! And if you so desire, assist other community members by replying or offering helpful information to the questions or challenges they may be facing right now!