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

Functions — Making Code Modular and Maintainable

As a college-level programming instructor, the first thing I like to teach after teaching the basics, such as loops and flow control, is functions. For many new and non-classically trained programmers, the purpose of functions often makes little sense. For the most part, new and inexperienced software developers see functions as a useless code organization technique that convolutes code. However, I usually counter this logic by stating that programmers should be like sewists. When a sewist creates a quilt, they take individual patches and sew them together to create the quilt. When it’s time to create the quilt, there is little concern about creating a patch. The only thing they are worried about is integrating the patch into the quilt as a whole.

For the most part, a programmer should consider themselves to be a sewist of software and the patch of choice should be functions. As we will explore in this chapter, the code...

Technical requirements

For this chapter, a working installation of CODESYS will be needed. The code for the examples can be found here: https://github.com/PacktPublishing/Mastering-PLC-programming/tree/master/Chapter%205.

What is modular code?

To understand the importance of modular code, consider a car. A car is not created of a single piece of material. Instead, a car is the amalgamation of individual components that, when combined, form a fully working vehicle. For example, a car has an engine, a transmission, brakes, and so on. By creating a car in components, the designers can swap out broken parts, upgrade individual components, use certain parts in other cars, and so on without redesigning the whole car.

A program should follow the same logic. Code needs to be placed into logical containers that organize code. The most basic of these containers is called a function. A function is analogous to a patch and a program is analogous to a quilt. A well-written program is a program that is composed of functions that are stitched together to form a fully working program.

With that in mind, what is the underlying purpose of a function, or module? The answer to that question is simple but will usually...

Why use modular code?

Modular code is vital for the longevity of a program. Consider the car example again; it would be inefficient and expensive for a person to have to buy a new car every time they need to change their brake pads. A program is not different. A program needs to be structured in such a way that if a defect is found, you or another developer can easily navigate to the block of code where the defect occurs.

Though the organized structure of a program is a very important concept in code modularization, it is not the only reason to modularize code. There are many other reasons why you would want to modularize your code. It could be for the sake of code reusability. In other words, when your function is properly written, you can use it in another project without having to modify it. This comes back to the patch mentality. If you’re making a quilt, a quality patch can be used in any type of quilt; it is just a matter of sewing or integrating it into the project...

Exploring functions

The most fundamental module of any program in any programming language is the function. We’ve thrown around the term quite a bit, but what is a function? In the most basic sense, a function is a named, callable block of code that performs a task. Essentially, a well-written program will be a collection of functions.

With that being said, it is common for entry-level students and non-formally trained professionals to assume that a function is merely allocating functionality to separate files. This, however, is a major fallacy that can lead to a poorly written program that will not last. Though it is very common to split functions into separate files in PLC programming, a separate file is not a function. As such, it is important to remember that there is a major difference between code in separate files and functions.

What goes into a function?

Before we start writing functions, we need to determine what goes into a function and when a function needs...

Examining return types

Return types can often be very confusing for new programmers. The main hang-up for many of the students that I have taught is that they often have a difficult time understanding what a return type is. As we have seen, a return type is simply a value that a function returns. In very simple terms, the returned value is simply the output of a function.

Each function must be declared with a return type. This return type can be any data type that is supported by IEC 61131-3; for example, the integer data type from the Addition function. In all, a function can return exactly one value of the type the function was declared with. So, if you declared a function with a return type of INT, you must return an integer similar to what we did with the Addition function. As we saw with the Addition function, returning a value is as simple as assigning the function name to a statement, as we did in the preceding code snippet for invoking a function.

This is a simplistic...

Understanding arguments

Where return types are a function’s output, arguments are a function’s input(s). Arguments are optional, as we saw with the Addition function, where no inputs were required. However, for many functions, especially for functions that do math like our Addition function, arguments are usually necessary to provide reusability to a function. For example, our Addition function only added two hardcoded values. For the most part, this function is useless unless we want to add 4 and 3 every time the function is called. As such, a better approach would be to modify our function to take values as inputs.

The first step in creating functions with arguments is declaring variables in the VAR_INPUT section of the file that was automatically generated by the POU wizard. For our modified Addition function, we are going to have the function take two inputs, a and b. As such, we’re going to modify that section of code to match the following. These are the...

Final project – temperature unit converter

Often, as PLC programmers, we are asked for our software to monitor temperatures. These temperatures could be inside the housing of a control panel, the temperature of a part we are fabricating, or many other applications. Now, it is quite common to need to be able to convert between temperature units, especially when the program is deployed to places around the world.

Temperature converters are prime examples of functions as they can be used across multiple projects and the code never has to change. As such, we want this code to be able to be inserted into multiple projects with minimal effort. For our function, we are going to create a state machine to trigger our conversion from one unit to another.

Our program will need to perform the following operations:

  1. F -> C
  2. F -> K
  3. C -> F
  4. C -> K
  5. K -> F
  6. K -> C

Our state machine will have six states. Therefore, create a function called...

Summary

In this chapter, we explored functions, return types, arguments, and more. The goal of this chapter was to demonstrate how to modularize code. In short, this chapter was an introduction on how to become a programming sewist. For programs to survive, they must be modular.

The key takeaway is that a well-written program is a modular one. The functions that we have explored are the backbone of modularity. Essentially, what we have covered in this chapter is the foundation that will help you create code that can be easily modified without breaking other sections of the program. In other words, what we have covered in this chapter will help you build more durable code.

In the next chapter, we are going to expand on this concept a bit more and look at object-oriented programming and explore how we can modularize programmatic blueprints.

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. What is a function?
  2. What are default arguments?
  3. What are named parameters?
  4. In which order are arguments received in a function?
  5. What is a function signature?
  6. What goes into a function?
  7. What is a return type?
  8. Can the return type INT be used with a variable of type REAL?

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