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

Complex Variable Declaration — Using Variables to Their Fullest

Variables are the backbone of any program. As you can guess, any program of significant size and functionality will use variables. Thus far, we have used variables extensively. However, in terms of the raw power of variables, what we have explored so far has hardly scratched the surface. For systems such as CODESYS, variables are a very rich concept, and unlike traditional languages such as C++ or Java, there are many tools available to help you easily implement variables.

If you’ve ever programmed in a traditional programming language, such as C++, C#, Java, or the like, you’ll notice many similarities between those languages and the concepts in this chapter. Though we have used variables till now, we have not taken full advantage of all the attributes that are offered by variables. As we transition into object-oriented programming in the coming chapters, it is important to understand how to organize...

Technical requirements

As usual, to follow along with this chapter, all you will need is CODESYS installed and working. Similar to past projects, the source code can be found at the following URL: https://github.com/PacktPublishing/Mastering-PLC-programming/tree/master/Chapter%204. All code examples presented in this chapter will be presented in the GitHub directory. As usual, for the optimal learning experience, it is best to explore the examples and modify them.

Auto declaring variables

In the previous chapters, we manually created variables. Manually creating variables is a common way of creating variables, but it is not the only way. CODESYS offers a simple tool for declaring variables called an Auto Declare tool. The tool is useful for declaring variables with data types that you may not be familiar with, creating a variable in a different file, and so on. The tool is also handy for assigning actual outputs, comments, and more for the variable.

The purpose of this tool is to help assist you in the creation of variables. However, this tool can easily be more trouble than it is worth. For the most part, it will be easier to declare a regular variable as we have been doing so far – that is, simply using the editor to write the variable’s code manually. However, if something is complex, in a different file, or you simply forgot the syntax, the tool can be of great value. In short, use the tool wisely and when necessary.

...

Understanding constants

It is often necessary to have an immutable variable. In other words, it is often necessary to declare a variable, assign it a value, and ensure that the value never changes. Possible examples of required constants are as follows:

  • Mathematical constants such as pi
  • Motor speeds that never change
  • Machine part sizes for calculation (things such as gear ratios)

This list is by no means comprehensive, nor will you always need to declare constants for the preceding bullet items. Whether or not you declare a constant is up to you and the application that you’re developing. In short, you will declare a constant when you want to add a level of protection so that a variable’s value never changes.

Declaring a constant is very simple. You can either use the Auto Declare tool and simply check the CONSTANT box, or you can declare one manually with the following syntax:

VAR CONSTANT
      const: INT :...

Investigating arrays

Arrays are pivotal to any program. Arrays are data structures that allow you to declare one variable, which can hold many different values of a certain data type. The general syntax for declaring an array is as follows:

name: ARRAY[<start_element>..<ending_element>] OF <TYPE>;

Therefore, if we wanted to declare an array of Boolean values called TestArray with elements ranging from 1 to 10, we would use the following syntax:

TestArray: ARRAY[1..10] OF BOOL;

Much like regular variables or constants, arrays can be declared manually or with the Auto Declare tool. The declaration of an array is different from traditional languages such as Java or C++. So, if your background is primarily in a traditional language, you may find the declaration of arrays to be awkward, especially when it comes to a concept known as multidimensional arrays. If you come from a traditional computer science background, you will probably be familiar with this term...

Exploring global variable lists

In traditional programming, global variables are usually considered dangerous and bad practice. However, the philosophy in PLC programming is a little different. Global variables can be dangerous; however, it is common that many processes depend on the same values. As we’ll explore later, there are ways to encapsulate and pass data around, but when there are many different code blocks that consume the values, it can often be inefficient to pass the data around.

Global values are often placed in special files called GVLs. Variables in a GVL can be accessed and manipulated by any file. Consequently, GVLs can be kind of dangerous to use, and code that utilizes variables from a GVL can be difficult to troubleshoot. Since a variable can be altered by any block of code from any file, it can be very difficult to figure out where a defective value stems from. Also, if a value is forced, it can trigger a response in many processes. This means that it...

Understanding structs

Structs are special data structures that allow you to group logically related data into a single data structure. Structs in IEC 61131-3 work very similarly to a struct in a C-like language. They are custom data types that contain variables of different data types in a singular data structure. If you’ve never programmed in a C-like language, structs may seem a lot like classes, a concept that will be covered later.

Declaring a struct

Creating a struct is very similar to creating a GVL. Similar to a GVL, you create a struct with the following steps:

  1. Right-click Application.
  2. Hover over Add Object.
  3. Click DUT.

When you finish these steps, you should see a wizard that is very similar to the wizard used to create a GVL, except that it has a few more options. The wizard can be viewed in Figure 4.12. For now, the only thing that you will need to do is change DUT in the Name field to motorStruct and click Add. Once you click Add, a new...

Getting to know enums

Similar to a struct, an enumeration is also a user-defined data type that is composed of comma-separated values. These values are predefined constants. Essentially, when a value in an enumeration is set, it cannot be changed. As such, enumerations are excellent tools for defining threshold limits, motor speeds, temperature values, and more. You declare an enumeration with the same wizard that we used to declare a struct, so be sure to view Figure 4.12.

For this example, create an enum name, motorSpeeds, using the same DUT wizard as before but by checking Enumeration as opposed to Structure, and leaving Textlistsupport unchecked. Once the code is generated, you can remove the enum_member attribute that is auto generated. Once that is done, modify the code to match the following:

{attribute 'qualified_only'}
{attribute 'strict'}
TYPE motorSpeeds :
(
     maxSpeed := 2000,
     minSpeed ...

Exploring persistent variables

Compared to many of the other concepts, such as enums and structs, that have been explored, persistent values are most similar to constants. However, there is a difference between constant and persistent variables. A persistent variable will hold its value in case of a cold system reset, a warm reset, or a repeated download. In other words, the value in the variable won’t be lost during a hard shutdown, but the value can still be changed during runtime. According to the documentation, applications for persistent variables range from counters to hour meters. Essentially, use persistent variables for values that must be preserved in case of things such as power failures.

Declaring a persistent variable is quite easy. You can manually insert the following code in any file in which you want to create a persistent variable:

VAR PERSISTENT
END_VAR

You can also declare a persistent variable using the tool and check the PERSISTENT box. Once the...

Final project – motor control program

To demonstrate all the concepts we have covered so far, let's build a motor control program. The program will simulate five motors. The motors will be in an array and the program will set the speed of the motors based on a persistent variable. To begin, let us create a motor structure:

TYPE motorStruct :
STRUCT
     motorStateMsg : STRING[20];
     motorState    : BOOL;
     motorSpeed    : INT;
END_STRUCT
END_TYPE

This code will create a structure that will dictate whether the motor is on with a Boolean variable, the motor speed (which will be set with an enum value), and a string that will tell which state the motor is in. After this structure is created, add an enum named motorSpeeds. Once you create the enum, add the code to match the snippet:

{attribute 'qualified_only'}
{attribute 'strict&apos...

Summary

In this chapter, we have explored many types of variables such as GVLs, enums, constants, structs, and more. In traditional PLC programming, concepts such as these are rarely used. However, as technology advances, these concepts are going to become more ingrained into the development of automation equipment. The concepts we have explored in this chapter will allow you to better organize your code. They will also serve as a way to better encapsulate data.

As we continue our journey in PLC programming, variables will play a vital role. In the next chapter, we are going to explore functions. As such, understanding variables will be pivotal in the exploration of function arguments.

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.

  1. How many dimensions can be included in an array that is declared using the tool?
    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
  2. What is the difference between a GVL and a struct?
  3. Describe the difference between an enum and a constant.
  4. What is a common error you may have with an array?
  5. Declare a 2D array of dimensions 5 and 6.

Further reading

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

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 €14.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