Reader small image

You're reading from  Mastering PLC Programming

Product typeBook
Published inMar 2023
PublisherPackt
ISBN-139781804612880
Edition1st Edition
Right arrow
Author (1)
Mason White
Mason White
author image
Mason White

M.T. White has been programming since the age of 12. His fascination with robotics flourished when he was a child programming microcontrollers such as Arduinos. M.T. currently holds an undergraduate degree in mathematics, a master's degree in soft ware engineering, and is currently working on an MBA in IT project management. M.T. is currently working as a soft ware developer for a major US defense contractor and is an adjunct CIS instructor at ECPI University. His background mostly stems from the automation industry where he programmed PLCs and HMIs for many different types of applications. M.T. has programmed many different brands of PLCs over the years and has developed HMIs using many different tools.
Read more about Mason White

Right arrow

Object-Oriented Programming — Reducing, Reusing, and Recycling Code

Almost all modern software applications utilize object-oriented programming (OOP) in some fashion. The most popular programming languages, such as Python, Java, C#, and C++ (among many others), are all object-oriented. Even most languages that are not traditionally object-oriented such as Microsoft’s F# will usually have object-oriented features. In short, OOP is a staple of modern-day software development.

Until recently, PLC applications were one of the only forms of programming that did not utilize OOP in some fashion. This is mainly due to the nature of PLC applications. For many older applications, it was not necessary to use OOP, as many PLC applications were relatively simple. For the most part, separated files and ladder logic were enough for most applications. However, with the new sophistication of automation systems that are encompassing ever more complexity, a more robust and logical way...

Technical requirements

OOP may seem like an exotic concept, and if you’re not familiar with it, you may already be assuming that you need to install extra plugins. However, as long as you have CODESYS installed, you’re ready to adopt OOP. The code for this chapter can be found here: https://github.com/PacktPublishing/Mastering-PLC-programming/tree/master/Chapter%206

What is OOP?

OOP is widely misunderstood in the automation field. It is often confusing, as the support of OOP features varies from one PLC brand to another. However, new and increasingly popular PLCs, such as those produced by Beckhoff or Wago, support a very pure form of OOP. There is also prejudice from many in the field to adopt the usage of OOP due to people not understanding the paradigm and the benefits that it offers. Much of the prejudice and misunderstanding stems from the novelty of OOP in the PLC programming realm.

With all that being said, what is OOP? The first step in understanding OOP is to understand what OOP isn’t. Many non-formally trained developers think of OOP as either breaking programs into files, similar to functions, or programming with classes—or, as they are known in IEC 61131-3, function blocks. However, this is a gross simplification and an inaccurate definition of what OOP is. It can be argued that this is where much of the prejudice...

Why use OOP?

OOP is a staple of the modern programming world. As stated before, almost all modern applications utilize the object-oriented paradigm. When designed properly, object-oriented code will provide, but is not limited to, the following benefits:

  • Reusability: The ability to move code modules from one application to another.
  • Code maintenance: The ability to quickly fix issues that arise in the software.
  • Reduces redundant code: Code is in one place and one place only.
  • Reduces the memory usage on the controller: Since OOP reduces redundant code, it will cut down on the total memory usage.
  • Leverages design: Function blocks are usually stitched together to form complex system architectures that cannot be accomplished without the use of objects.
  • Increased productivity: Object-oriented code generally produces an overall better-quality product faster and cheaper than a non-object-oriented software system. When designed properly, the modules can be ported...

Understanding function blocks

The term function block can be confusing. Unlike ladder logic, where a function block is merely a pre-built operation that carries out a specific task, when digging into OOP, that idea can be greatly expanded upon. In terms of OOP, function blocks are the code structures that allow developers to blueprint their objects. For readers with knowledge of languages such as C++, C#, Java, or the like, a function block is similar to a class. Generally, PLC programmers that have adopted OOP usually consider function blocks to be the equivalent of classes, and many will even refer to them as classes. In IEC 61131-3, a function block can hold data and code similar to the way a class in a traditional object-oriented language can. As will be explored later, a function block can also inherit from other function blocks and be inherited from, similar to classes in traditional object-oriented languages.

Classes are the backbone of any modern object-oriented language...

Getting to know objects

The root term in OOP stems from objects, which are things. Essentially, the c1 and c2 variables in the PLC_PRG file are objects; they are different instances of the Calculator function block. In other words, the variables are compact copies of the function block. This is a very powerful concept because though the variables reference the same code in the function block, they can hold different data. To demonstrate this, match the following code snippet to your Calculator function block:

FUNCTION_BLOCK PUBLIC Calculator
VAR_INPUT
	input : INT;
END_VAR
VAR_OUTPUT
	output : INT;
END_VAR
VAR
END_VAR

In this demonstration, we have simple input and output variables. This code will require an input variable to be provided when the object variable is initialized. All the logic will do is assign the input to the output, as in the following snippet:

output := input;

To provide an argument to the function block, we have to use named parameters. As such, we are...

Getting to know methods

The term method has been thrown around a few times thus far in the book. A method is a special type of function that belongs to a function block. Methods are members of function blocks that consist of blocks of code that are executed when called. Without methods, a function block is mostly useless. To conceptualize a method, consider the blueprint example before. If the function block is a car, then the methods are the brakes and engine of said car.

Unlike the functions we explored in Chapter 5, methods are not global. This means that they cannot be called from anywhere like the functions we previously explored. Essentially, the only place that can call these functions is a file with an object to the function block or from somewhere inside the function block, such as another method.

To create a method, you must first have a function block. Since we already have a Calculator function block, we are going to add four methods to it that will handle addition...

Getting to know properties

Properties are extensions of the IEC 61131-3 standard. Properties are special methods that are used to manipulate encapsulated data. When you create a property, you will get two files named get and set. These are your getter and setter methods. The getter method will be used to read data, while the setter method is used to write data to an attribute. The true value of properties will be explored in the next chapter; however, for now, we’re going to explore them to a limited degree.

Adding a property

Adding a property is a lot like adding a method. You will essentially follow the same flow of clicks that can be found in Figure 6.4, with the only exception being that you will select Property… instead of Method…. When you click Property…, you should be met with a wizard similar to the one shown in Figure 6.8. The wizard is very similar to the wizard that is used to create methods. To follow along, add the property in Figure...

Understanding the purpose of a getter and setter

Now that we have a property set up, we need to answer a logical question: what are they used for? As stated before, if you have a variable that belongs to a function block, you never want to directly access it. At first glance, this may seem like a convoluted way of doing things; however, the power of a getter method comes in the form of the logic that it contains. Essentially, both getter and setter methods can support logic that can vet how and what’s reading or writing the variable.

Getter method

A getter method is used to read a variable in a function block. For the most part, getters usually have very simple logic. In short, many of the getter methods that I have written in the past (regardless of the language or project that I am working on) are usually methods that simply return a class, function block, or variable.

A basic demonstration for a getter method is reading a variable from the function block we have...

Understanding recursion and the THIS keyword

Recursion is a looping concept that isn’t used much in today’s world. However, it is a concept that often pops up in interviews and is something that all software engineers need to understand. In a nutshell, recursion is where a method calls itself. Recursion is a valid concept and is an important concept to know; however, for many applications, some type of loop will be more appropriate.

If you do opt to use recursion, exercise great caution. Recursion is generally considered resource-heavy, and in the automation world, where many PLCs have traditionally limited computing resources compared to full-fledged computers, it can consume precious resources.

Recursion is also somewhat dangerous as it is easy to create what is known as an infinite recursive loop. These loops are recursive loops that continuously call themselves. Many modern compilers do check for this and will usually throw a compile error before the code is...

Final project – creating a unit converter

In automation programming, it is very common to have to convert between different units of measurement to support clients around the world. This is especially true if you have a single codebase that supports a specific machine that is deployed to many different regions. To accommodate the different units of measurement, it is common to create a function block that can do this. For our final project, we are going to create a very simple function block that can convert the following units:

  • Lbs -> kgs and kgs -> lbs
  • Feet -> meters and meters -> feet

Depending on what you’re working on, there will probably be many more units; however, this is just an example.

The first thing we need to do is create a function block called UnitConversion and add two methods called weight and length to it. Both methods should have a Return type value of REAL and an Access specifier value of PUBLIC. When you’re...

Summary

OOP is the backbone of all modern programs. OOP is so ingrained into the IT world that you can’t function as a programmer without an in-depth knowledge of the concept. The days of being able to get away with simply programming machines, in a procedural sense, with ladder logic are quickly fading.

This chapter was simply a soft introduction to OOP. OOP is way more than just organizing your code into function blocks, as many concepts govern the paradigm. Now that we have a grasp of function blocks, methods, properties, and recursion, we can learn to leverage them to reduce redundant code, create cleaner code, and apply actual architecture to programs.

Questions

Answer the following questions based on what you've learned in this chapter. Cross-check your answers with those provided at the end of the book, under Assessments.

  • What is a function block called in a traditional programming language?
  • What is recursion?
  • What is the purpose of the THIS keyword?
  • What are the two methods that make up a property?
  • What is the difference between a getter and a setter?

Further reading

Have a look at the following resources to further your knowledge:

https://help.codesys.com/api-content/2/codesys/3.5.13.0/en/_cds_method_call/

  • THIS keyword CODESYS documentation:

https://help.codesys.com/api-content/2/codesys/3.5.13.0/en/_cds_method_call/

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering PLC Programming
Published in: Mar 2023Publisher: PacktISBN-13: 9781804612880
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Mason White

M.T. White has been programming since the age of 12. His fascination with robotics flourished when he was a child programming microcontrollers such as Arduinos. M.T. currently holds an undergraduate degree in mathematics, a master's degree in soft ware engineering, and is currently working on an MBA in IT project management. M.T. is currently working as a soft ware developer for a major US defense contractor and is an adjunct CIS instructor at ECPI University. His background mostly stems from the automation industry where he programmed PLCs and HMIs for many different types of applications. M.T. has programmed many different brands of PLCs over the years and has developed HMIs using many different tools.
Read more about Mason White