PLCs for Beginners - M. T. White - E-Book

PLCs for Beginners E-Book

M. T. White

0,0
28,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

With the rise of smart factories and advanced technology, the demand for PLC programmers with expertise beyond ladder logic is surging. Written by M.T. White, a seasoned DevOps engineer and adjunct CIS instructor, this guide offers insights from the author’s extensive experience in PLC and HMI programming across industries. This book introduces a fresh approach to PLC programming, preparing you for future automation challenges through computer science and text-based programming.
Starting with the basic components of PLCs and their integration with other modules, this book gives you a clear understanding of system functionality and helps you master PLC program execution by learning about flow and essential components for effective programming. You'll understand program design with pseudocode and flowcharts, vital for planning programs, and cover Boolean logic intricacies, harnessing logical functions and truth tables for precise control statements. The book gives you a comprehensive grasp of Structured Text, its syntax and features crucial for efficient programming. The book also focuses on advanced topics like cybersecurity in PLC systems and leveraging generative AI (GenAI), such as ChatGPT, to enhance productivity.
By the end of this book, you’ll be able to design real-world projects using pseudocode and flowcharts, and implement those designs in Structured Text.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 545

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



PLCs for Beginners

An introductory guide to building robust PLC programs with the Structured Text language

M. T. White

PLCs for Beginners

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Preet Ahuja

Publishing Product Manager: Suwarna Rajput

Book Project Manager: Uma Devi

Senior Editor: Isha Singh

Technical Editor: Yash Bhanushali

Copy Editor: Safis Editing

Proofreader: Isha Singh

Indexer: Subalakshmi Govindhan

Production Designer: Vijay Kamble

DevRel Marketing Coordinators: Linda Pearlson and Rohan Dobhal

First published: May 2024

Production reference: 1100524

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-80323-093-1

www.packtpub.com

To mom and dad.

Contributors

About the author

M. T. White has been programming since the age of 12. His fascination with robotics flourished when he was a child programming microcontrollers. He holds an undergraduate degree in mathematics, a master’s degree in software engineering, and an MBA in IT management. He is currently working as a software developer for a major US defense contractor and is an adjunct CIS instructor, where he teaches Python, C, and an array of other courses. His background mostly stems from the automation industry where he programmed PLCs and HMIs for many different types of applications. He has programmed many different brands of PLCs over the years and has developed HMIs using many different tools. Other technologies that he is fluent in include Linux, Ansible, Docker, AWS, C#, Java, and Python. Be sure to check out his channel AlchemicalComputing on YouTube.

About the reviewers

Keith Lyding is an electrical engineer for a manufacturing company in Columbus, Ohio. He has over 15 years of experience in the electrical field, as well as more than 9 years of experience in automation. He graduated from Thomas Edison State University in 2019. He served in the US Navy for six years and has also worked for Nucor Steel. He currently works for Sonoco Products Company, where he works primarily with Allen Bradley PLCs, Inductive Automation’s Ignition platform, EXOR and Panelview HMIs, and many other platforms. He enjoys troubleshooting, as well as automating complex operations. In his spare time, he loves to serve in his church, coach his son’s baseball team, and spend time with his family.

I extend my deepest gratitude to my wife, Katie, for her unending support. I am grateful to my colleagues and mentors for their guidance throughout my journey: Kyle Ahrendt, William Carleton, and K. Andy Steinacker. I am also appreciative of the men in my life for continuing to sharpen, push, and encourage me to become more like Jesus: Paul Cassidy, Brian Babin, Ken Lyding, K. Andy Steinacker, Jon Krull, David Bout, Isaac Dye, and many, many others.

Ninad Deshpande is an author, storyteller, international speaker, and technology evangelist known in the industrial automation fraternity. He has over 15 years of extensive hands-on experience in varied fields of the automation industry, such as application development, testing, R&D, marketing, corporate communication, and global product management. He is the co-author of the Packt book The Art of Manufacturing. Today, as a co-founder and director of Passion Minds Private Limited, he helps organizations across the globe in various industries with services focusing primarily on technologically and strategically driven content generation.

I thank my family and friends for teaching me life lessons and consistently inspiring me. I admire my mother’s and my wife’s fighting spirit; their constant support and motivation enable me to achieve my dreams.

Table of Contents

Preface

Part 1: Basics of Computer Science for PLC Programmers

1

Computer Science Versus Automation Programming

Technical requirements

What is computer science?

Why study computer science?

What is automation programming?

What is a PLC?

Exploring automation through computer science

How does computer science help automation programmers?

Why should automation programmers care?

Cloud technologies

The internet of things

Machine learning

What does this mean for automation engineering?

PLCs versus microcontrollers

What are microcontrollers?

Surface-level differences

PLC and microcontroller programming languages

Use cases

PLC versus computers

What is a computer?

PLC versus computers

Summary

Questions

2

PLC Components – Integrating PLCs with Other Modules

Technical requirements

PLC types

Common PLC modules

Power supply

Chassis

CPU modules

I/O modules

Safety modules

Sinking versus sourcing

NPN versus PNP

Sensors

Motors and motor controls

What is a motor?

Open and closed-loop control systems

Stepper motors

Servo motors

Encoders

Motor drives

Communication protocols

What is a communication protocol, and what is it used for?

Wiring diagrams

Final project

Specs

BOM

Summary

Questions

Further reading

3

The Basics of Programming

Technical requirements

Understanding what a program is

What is the purpose of a program?

Why use software over hardware?

How to view software and hardware in a system

Software is not a cure-all solution

Understanding programming languages

Syntax

Translators

Machine instruction

Language paradigms

Keywords

Dos and don’ts of learning keywords and syntax

Program flow

Program iteration

Exploring the IEC 61131-3 standard

IEC 61131-3 pitfalls

Final project

Strategy

Summary

Further reading

Questions

4

Unleashing Computer Memory

Technical requirements

What is memory?

Memory

Storage

How computer/PLC memory and storage work

HDDs

SSDs

Volatile versus non-volatile memory

Volatile memory

Non-volatile memory

Memory addresses

How memory works

Computer memory – an analogy

Common storage devices

USB drives

External hard-drives

SD cards

Cloud storage

Obsolete storage devices

Floppy drives

Summary

Questions

Further reading

5

Designing Programs – Unleashing Pseudocode and Flowcharts

Technical requirements

What are pseudocode programs and flowcharts?

Pseudocode

What does pseudocode look like?

Flowcharting

What do flowcharts look like?

Why use pseudocode and flowcharts in PLC programming?

Why use pseudocode?

Why use flowcharting?

When to use one over the other?

Tools needed for flowcharts and pseudocode

Pseudocode tools

Flowchart tools

Whiteboarding

Design exercises

The quadradic equation

The beer program

Final project – Robot startup system

Design requirements

Design logic

Wait sequence

Pseudocode

Flowchart

Summary

Questions

6

Boolean Algebra

Technical requirements

What is Boolean algebra?

Boolean operators

The basic operators

The OR operator

The NOT operator

Boolean expressions

Exploring NOT

The OR operator

The AND operator

Operator laws

Idempotent law

Solving Boolean equations

Examples

Getting to know truth tables

Basic operators

Final project: Creating custom truth tables from scratch

Row 1

Row 2

Row 3

Row 4

Final truth table

Summary

Questions

Further reading

Part 2: Introduction to Structured Text Programming

7

Unlocking the Power of ST

Technical requirements

What is ST?

Area of a circle program in ST

Why is ST important?

ST versus LL

Example 1 – The area of a circle program – LL

Example 2 – Toggling a light

What is CODESYS?

Installing CODESYS

A CODESYS exploration

Exploring the PLC_PRG file

The final project – Hello World

Step 1 – Creating a new project!

Step 2 – Code implementation

Step 3 – Running the program!

Chapter challenge

Summary

Further reading

Questions

8

Exploring Variables and Tags

Technical requirements

What are variables/tags?

Applications of variables

Variables/tags under the hood

Why use variables?

Data types

What is a data type?

The IEC 61131-3 data types

Bits and bytes

Common data types

How to declare variables

Variable section of a file

Declaring a variable

Initializing a variable

Variable naming

Rules to naming a variable

Naming conventions

Final project – declare the variables of a triangle

Code implementation

Challenge – declare the variable for a rectangle’s perimeter

Summary

Further reading

Questions

9

Performing Calculations in Structured Text

Technical requirements

Math in ST

Assigning numbers

Basic calculations

Solution variable

The four basic functions

Basic operation demonstration

Complex mathematical functions

Square root function

Exponent function

ABS function

Trigonometric functions

Arc functions

Order of operations for math calculations

Computing complex equations

Distance between two points

Final projects

Final project 1 – programming the perimeter of a rectangle

Final project 2 – Pythagorean theorem

Summary

Questions

Further reading

10

Unleashing Built-In Function Blocks

Technical requirements

What are prebuilt function blocks?

Functions, function blocks, and keywords

Function blocks under the hood

What is a function block?

Rising and falling edges

Common PLC function blocks

Counter function blocks

Timer function blocks

Final project

Variables

Summary

Questions

Further reading

11

Unlocking the Power of Flow Control

Technical requirements

Exploring what flow control is

Exploring why flow control is important

Exploring logical expressions

Exploring the IF statement

IF statement syntax

Checking if two values are the same!

Exploring the not equals operator

Designing control statements

Overdraft program

Exploring the CASE statement

State machines and CASE statements

Implementing the state machine

Flowcharting and CASE statements

Real-world applications for the CASE statement

Final project

Requirements

Program design

Code implementation

Final challenge

Summary

Questions

12

Unlocking Advanced Control Statements

Technical requirements

Nested control statements

ELSE statements

ELSIF statements

Challenge

Logical operators

Exploring the OR operator

Exploring the XOR operator

Exploring the NOT operator

Final project

Requirements

Variables

Color and shape sorter logic

Testing conditions

Summary

Further reading

Questions

13

Implementing Tight Loops

Technical requirements

Exploring the different types of loops

Counter loop

Precheck loops

Post check loops

Infinite loops

Exploring loops in pseudocode and flowcharts

Exploring loops with pseudocode

Representing a loop in a flowchart

Implementing a FOR loop

Implementing the WHILE loop

Exploring the REPEAT loop

Exporting the EXIT keyword

Understanding nested loops

Challenge – creating a behavior report

Final project

Design

Code implementation

Testing the program

Summary

Questions

Further reading

Part 3: Algorithms, AI, Security, and More

14

Sorting with Loops

Technical requirements

How to use this chapter

What is sorting?

Exploring what arrays are and how to use them!

What is an array?

Array elements

Initializing an array

Retrieving the number of elements in an array

Why are arrays important for sorting algorithms?

Exploring sorting algorithms

What is an algorithm?

What is a sorting algorithm?

Algorithm efficiency metrics

Exploring the Big O notation

Exploring the Big Ω notation

Common sorting algorithms

Exploring bubble sort

Exploring insertion sort

Challenge – Merge sort

Final project – cement bag sorter

Requirements

Analysis

Implementation

Summary

Questions

Further reading

15

Secure PLC Programming – Stopping Cyberthreats

Technical requirements

What cybersecurity is and why it’s important

The basics of cybersecurity

Vulnerabilities, threats, and risk

Threat actors

Exploring AAA

Air-gapped systems

Common cyberattacks

Exploring information gathering

Exploring social engineering

Exploring password hacking

Malware

Attack prevention methods

Stopping social engineering

Defending against password crackers

Password length

Malware defense

Final project – a PLC-based activation system

Design

Certifications

Summary

Questions

Further reading

16

Troubleshooting PLCs – Fixing Issues

Technical requirements

Common causes of PLC issues

Broken software

Exploring environmental issues

Understanding non-environmental issues

Common hardware issues

Exploring power supply issues

Common PLC problems

Bad batteries

Exploring troubleshooting techniques

The PLC toolkit

Diagnosing power supply issues

Diagnosing temperature issues

Diagnosing networks

Troubleshooting software

The basics of troubleshooting software

Final project

Troubleshooting

Summary

Questions

17

Leveraging Artificial Intelligence (AI)

Technical requirements

What is GenAI?

What is AI?

What GenAI can’t do

Reasonable expectations with GenAI

What not to expect with GenAI

What to expect when using GenAI

The basics of prompt engineering

Creating a prompt

Producing workable code with ChatGPT

Final project

Prompt and code

Summary

Questions

Further reading

18

The Final Project – Programming a Simulated Robot

Technical requirements

Project scope

Project requirements

Flowchart for the system

Designing the pseudocode

Implementing the program

Using ChatGPT to implement bubble sort

Final project variables

Main program logic

Testing the program

Summary

Assessments

Index

Other Books You May Enjoy

Preface

Until recently, automation programming has been, for the most part, unchanging. However, with the recent boom in computing power, that is rapidly changing. New technologies are being introduced at a rapid pace, and these are drastically altering the automation landscape. These new, disruptive technologies are rendering the days of only programming in Ladder Logic a relic of the past. In today’s automation landscape, to get the most out of a PLC, one must use Structured Text. This book is an in-depth look at writing very robust and well-written programs in Structured Text while also providing a general education for programming logic and design as well as other core tenets that will be required to future-proof projects.

Who this book is for

This book is for anyone who is interested in learning Structured Text programming. It is designed for beginners who have never programmed before and for those who wish to transition from Ladder Logic to Structured Text.

What this book covers

Chapter 1, Computer Science Versus Automation Programming, introduces you to computer science and contrasts it with automation programming. This chapter will explore the various types of controllers, emerging technologies, and more.

Chapter 2, PLC Components – Integrating PLCs with Other Modules, focuses on introducing the various components that make up a traditional PLC. This chapter will introduce you to analog and digital principles as well as all the needed components that a PLC will need to operate.

Chapter 3, The Basics of Programming, lays the foundation for programming. This chapter will introduce you to what programs are, how they work, and much more.

Chapter 4, Unleashing Computer Memory, lays the foundation for more advanced chapters by introducing you to the basics of memory. Topics explored will include what memory is, how memory works, and common storage devices.

Chapter 5, Designing Programs – Unleashing Pseudocode and Flowcharts, teaches you how to create a design for a program. Concepts explored will be designing a program in pseudocode and with a flowchart.

Chapter 6, Boolean Algebra, covers the basics of Boolean algebra. The core principles will be to learn how to compute logical equations, understand logical operators, and create truth tables.

Chapter 7, Unlocking the Power of ST, explores what Structured Text truly is and why it is important. The key takeaways from this chapter are understanding why Structured Text is important, why it should be used, and how to set up the programming environment.

Chapter 8, Exploring Variables and Tags, expands on and applies the material presented in Chapter 4 to implement what are called variables or tags. This chapter will cover concepts such as data types, naming conventions, and much more.

Chapter 9, Performing Calculations in Structured Text, covers one of the most pivotal skills any PLC programmer can have: programming mathematical calculations. Topics will include how to program math equations and common math functions.

Chapter 10, Unleashing Built-In Function Blocks, explores the built-in function blocks. The main takeaway will be for you to understand what a built-in function block is and how to use common function blocks such as timers and counters.

Chapter 11, Unlocking the Power of Flow Control, introduces flow control with conditionals. This chapter will explore how the flow of a program can be altered and basic intelligence can be introduced to a program.

Chapter 12, Unlocking Advanced Control Statements, expands on concepts that were explored in the previous chapter, and examines topics such as embedded conditional statements, complex logical expressions, and much more.

Chapter 13, Implementing Tight Loops, provides an in-depth exploration of loops. This chapter will explore various types of loops in Structured Text as well as their applications.

Chapter 14, Sorting with Loops, introduces you to the basics of sorting algorithms. The key takeaway from this chapter is to introduce you to concepts such as algorithms, Big O notation, the basics of arrays, common sorting algorithms, and more.

Chapter 15, Secure PLC Programming – Stopping Cyberthreats, provides an overview of the cybersecurity landscape in relation to PLC-based systems. This chapter will present a lot of theoretical knowledge that can be applied to the design of PLC-based systems, networks, and more.

Chapter 16, Troubleshooting PLCs – Fixing Issues, provides the necessary steps to troubleshoot a malfunctioning PLC-based machine. Topics will include common issues, necessary tools, IT diagnostics, and more.

Chapter 17, Leveraging Artificial Intelligence (AI), explores how generative AI (ChatGPT) can be used to help automatically write software. This chapter will explore what generative AI is, how to use it, reasonable expectations, and how to write prompts.

Chapter 18, The Final Project – Programming a Simulated Robot, draws on material explored throughout the book. This chapter will focus on programming a theoretical robot that sorts parts and sends lots down the proper production line.

To get the most out of this book

This book assumes no prior knowledge of PLC programming or programming in general. To get the most out of this book, only a basic understanding of mathematics is required. Ideally, you should be familiar with basic algebra and maybe trigonometry.

Software/hardware covered in the book

Operating system requirements

CODESYS

Windows

ChatGPT

N/A

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/PLCs-for-Beginners. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We had a CASE conditional with an IF statement inside it .”

A block of code is set as follows:

PROGRAM PLC_PRG VAR currentHopperWeight    : REAL := 250; bag1Weight             : REAL; bag2Weight             : REAL; END_VAR

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

PROGRAM PLC_PRG VAR     password    : STRING(255) := 'password';    length    : UINT;    acceptPass : bool; END_VAR

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance: "Air gapped systems are simply systems that are not connected to the internet.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read PLCs for Beginners we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803230931

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Basics of Computer Science for PLC Programmers

Programming is much more than just writing code. There is a lot of theoretical knowledge that goes into crafting a well-written program, and this part will lay the foundation for just that. This part will provide all the theoretical knowledge needed to understand the rest of the book and will cover the basics of PLCs, including PLC hardware, memory, logic, and design, how programs work under the hood, Boolean algebra, and more.

This part has the following chapters:

Chapter 1, Computer Science Versus Automation ProgrammingChapter 2, PLC Components – Integrating PLCs with Other ModulesChapter 3, The Basics of ProgrammingChapter 4, Unleashing Computer MemoryChapter 5, Designing Programs – Unleashing Pseudocode and FlowchartsChapter 6, Boolean Algebra

1

Computer Science Versus Automation Programming

If you were to ask an everyday automation professional what computer scientists are, you would probably get an answer along the lines of math nerds, computer geniuses, and so on. Most automation professionals are usually engineers or trade persons who stem from a field with little to no computer science exposure. This means very few automation professionals are classically trained in computer principles. For many automation professionals, there is a barrier between complex computing and automation.

This book is going to be different from most automation programming books on the market. This book is going to focus on developing software for Programmable Logic Controllers (PLCs); however, this book is designed to teach you, the reader, to be more than a PLC programmer or tech. This book is designed to turn you into a genuine software developer. In short, this book will cover everything from program design to security. This book will also utilize Structured Text over the more traditional Ladder Logic. The reason for utilizing Structured Text is twofold. First, Structured Text is the future of PLC programming. As PLC applications become more advanced, the programming apparatus will need to be more robust. Structured Text offers much tighter control over a program than Ladder Logic. Second, implanting a well-designed program in Structured Text will be much easier to implement than it would be in Ladder Logic. With that said, there are no prerequisites for this book. You do not need to have any special math skills, logic skills, or anything of the sort to follow along. Those skills will be introduced in the book, but they will be easy to master and implement.

To begin, the brain of most modern machines is a PLC. PLCs, for many, are just programmable devices, but they are miniature computers that are governed by the same laws of computing that govern any other device, such as a personal computer or smartphone. This poses a problem in the automation world because software is usually considered an easily replaceable component that exists to complement the hardware. In other words, many automation engineers often have an “if it works it’ll do” attitude towards software. This is a faulty philosophy, as poorly written software can hinder a machine and put it in the cyber trash heap before its time. Therefore, to become more than a simple PLC programmer, a mastery of computer science is a must.

To begin our journey into computer science, we’re going to first explore the following topics:

What is computer science?What is automation programming?Why is computer science important in automation programming?Why should automation programmers care about automation programming?The differences between a PLC and a microcontroller

Finally, to round out the chapter, we will explore the differences between a PLC and a computer.

Technical requirements

This chapter is theoretical and will not require any specific software.

What is computer science?

Computer science is the study of computer systems, with a strong emphasis on software. In a more lay sense, computer science is the study of computational systems such as computers, phones, or anything that runs software, including PLCs. In short, the scope of computer science usually encompasses fields that involve software development or computer architecture. Computer science is a broad field that ties into many other disciplines, such as the following:

Software engineeringArtificial intelligence (AI)NetworkingCyber securityDatabase systemsBioinformaticsDistributed computingComputer architecture

The field of robotics and automation can also loosely be considered a field of computer science.

As can be seen, computer science encompasses a lot of different disciplines. For some, this may seem scary, but rest assured that a mastery of each of these subfields is not necessary to be successful at computer science or programming. The focus of this book is going to be mostly on software engineering, which means there is going to be a heavy emphasis on software design and implementation. So, why should one learn computer science?

Why study computer science?

The ultimate goal of computer science is to create faster and more powerful computer systems that can solve increasingly complex problems. To put it briefly, a person would want to study computer science to build more efficient hardware, software, and networks, improve computer system security, and more. In other words, a person will study computer science to build faster, smarter, safer, and more reliable systems. With that, why should automation programmers or engineers care about computer science?

Before the benefits of computer science can be appreciated for automation programming, it is important to understand what automation programming is. As such, the following section is going to explore what automation programming is and where it is used.

What is automation programming?

Automation programming can take on many different interpretations depending on the context and industry. For this book, automation programming will be considered industrial automation programming. Industrial automation programming and control programming can be considered the same thing. When one mentions controls or automation programming, they are usually referring to writing software that lives on some type of controller that is used to automate the use of machinery. In all, automation software is designed to reduce the amount of human intervention in a process.

Automation programming starts with a programmable device. There are many types of automation controllers, with some being the following:

PLCsRemote terminal unit (RTU)Proportional – integral – derivative (PID)Miscellaneous control boards

What is considered automation software should include more than software that simply lives on controllers. This means that what is considered industrial control software can also branch out into other families of software, such as the following:

Human–machine interfaces (HMIs)Supervisory control and data acquisition (SCADA)Databases

When someone mentions automation programming, they are usually referring to software that lives on the most common types of industrial controllers, PLCs. PLCs are often the main type of controllers for industrial applications and are often seen as the backbone for many machines. This means that when it comes to automation programming, knowing how to program a PLC effectively is necessary.

For this book, automation programming refers to writing software for PLC devices. With that, before the links between automation programming and computer science can be fully appreciated, it is important to establish a high-level understanding of what a PLC is and what it does.

What is a PLC?

A PLC is a specialized programmable device designed to be very rugged and operate for extended periods. PLCs are responsible for operating industrial or heavy equipment and are commonly used in the following:

StreetlightsAmusement parksFactoriesCranesNuclear reactorsSpace launch systemsDams

Anywhere a program is required to operate a piece of industrial or heavy equipment, a PLC will usually be present.

For beginners and even some experienced automation professionals, all this computer science stuff may seem dubious, unnecessary, and more trouble than it’s worth. However, before any rash judgments are made, let us explore why automation engineers need to understand computer science.

Exploring automation through computer science

In automation, software is often seen as a second-class citizen to the hardware. If you speak to an automation professional, chances are they are going to tout the hardware as the main focal point of the system. Automation engineers love to brag about the latest controllers that are being utilized, how they integrated the finest motors and motor drives into the system, and so on. However, it is rare to hear a typical automation engineer brag about the efficiency of the software or tout the design patterns they used to architect the software.

A lot of this attitude towards software boils down to tangible assets. Often, an engineer can hand a customer the latest power supply or brag about how easy it is to swap out a new motor drive. If the customer ever sells the machine off, they can use all those features as selling points to raise the value of the machine. However, there is a major flaw in this logic. Without quality software, the machine will be an expensive paperweight. With low-quality software, the machine will be a high-quality paperweight that can move and perform certain tasks marginally well at best. Put bluntly, the quality of a machine starts with the software. A machine can have the most advanced hardware in the world, but if it has poorly written software, it will be a poorly performing machine at best. With that, how does computerscience help?

How does computer science help automation programmers?

If you think about the way computer science was defined in the past, it was mainly concerned with producing quality software. Computer science has many principles that, when followed, will produce fast, safe, and reliable software. In other words, the computer science principles that are going to be explored in this book are going to allow you to get the most out of that advanced hardware. If you can understand and even master the principles that will be explored, your code will be light years ahead of your competition, and all that fancy hardware will be used to its full potential.

Many experienced automation professionals may be wondering why they should care about computer science and how it relates to automation programming. After all, automation software, for years, has been written with little concern given to software execution performance. There are also a lot of beginners who are more infatuated with robots and building smart factories than with writing quality code. So, to give some context as to why someone should care about computer science, we are going to explore a few reasons why.

Why should automation programmers care?

The world is changing rapidly, and the computer industry is leading the charge. For those who work in the automation industry, where systems can easily be 20 years old, it can often be difficult to see how rapidly the IT world is morphing. In the past, most of the then-emerging technologies were decentralized and did not factor into industrial automation. However, with the widespread adaptation of the internet and interconnected devices, that all changed.

Recently, the world has seen the rise of things such as cloud computing, the IoT, machine learning, and many other things. The new elements have exploded so fast that they are starting to be integrated into the industrial automation realm. To understand why automation programmers should care about computer science, we first need to understand what these modern technologies are. Now, it is important to remember that this list is not exhaustive, but the following technologies will give an insight into why we need to care about computer science principles.

Cloud technologies

The term cloud has been making the rounds over the past few years. In a very lay sense, the cloud is a bunch of interconnected data centers where you can rent resources. These resources vary and have many different applications. For example, some common, high-level services include the following:

Virtual machines (VMs)Data storage, such as databases and cloud storageContainerizationMicroservice supportMachine learningData analyticsNetworking

The best way to conceptualize the cloud is an all-in-one resource that has all the computing infrastructure needed to power your application. There is a lot to understand about the cloud and its various levels that go well beyond the scope of this book. However, it is important to know the most popular cloud service providers (CSPs):

AWS (Amazon)Azure (Microsoft)GCP (Google)OCI (Oracle)IBM Cloud (IBM)

It is important to note that this list is not complete, and from this list, AWS and Azure are the most popular.

Most of the services offered through these CSPs charge either via usage, the number of requests to the service, or the amount of time used. What is also interesting is that the cloud is being adopted by the automation industry because it is often cheaper and requires less skill to create resources in the cloud than having to create those resources in-house and maintain the service on a custom server. Even if the automation company you are working for does not utilize the cloud, it is likely that a customer would require the machine to be interfaced with cloud services. With that, the next major technology that we need to explore is the IoT.

The internet of things

The Internet of Things (IoT) is another buzzword that has been popping up recently. To summarize, the IoT is a group of devices that are networked together to form an integrated smart system, such as a smart house or smart factory. Typically, devices are connected via a network and can pass data freely to any other device in the network, which allows for easy access to real-time production data. The IoT allows for the following:

Problems can be identified more rapidly.Personnel can have real-time status updates.Machine(s) can adjust to changing situations more readily.Processes can be better orchestrated.

Overall, the IoT is becoming a very prominent tool in automation and is the backbone of smart factories. Although the IoT is the backbone of many smart factories, another emerging technology is AI and machine learning (ML).

Machine learning

Of all the buzzwords, machine learning is by far the most famous. Machine learning and AI are all over the news, and systems such as ChatGPT are quickly changing the world. Much like the rest of the modern world, AI and ML have infiltrated the realm of automation. Currently, there are libraries that can be utilized to give PLCs the ability to leverage the power of AI and ML. AI and Machine Learning is a complex field that incorporates aspects of mathematics and computer science to understand and properly implement. Additionally, AI and ML are not singular concepts; instead, machine learning and, by extension, AI encompass many different algorithms that do different things. Common algorithms include the following:

Deep learning algorithms that mimic the human brainRegression algorithms that are used to make predictionsClustering algorithms that cluster things into groups

These are just a few broad types of algorithms. There are other types of algorithms, and many of those algorithms have different categories. For example, regression algorithms can be simple regression algorithms, multiple regression algorithms, or logistic regression algorithms. These algorithms can open vast new avenues that many would never have dreamed of; however, to effectively use ML, a developer must select a machine learning algorithm, collect and process the data, train the model, and finally deploy the model. This can be an exceedingly challenging job, and depending on the algorithm, formatting the data can be a daunting task that requires a lot of knowledge in computer science. So, what does all this equate to?

What does this mean for automation engineering?

So, with all this, why should an automation engineer care about computer science? After all, automation engineers have spent decades doing just fine with simple Ladder Logic and little thought into the guts of software, so why should automation professionals care now?

Well, the answer is quite simple. Effective programming must be implemented to cut costs, secure the system, and ensure that the system runs efficiently. In terms of the cloud, if a machine is constantly uploading useless data to the cloud, it is going to add an extra cost to the system’s operation. For example, if the data is being uploaded to the cloud and the cloud is utilizing services such as computer instances and data resources, each useless byte of data is going to compound the cost of operating the machine. In terms of ML, if those data are being used to train a machine learning model, it can create errors in the model that make it perform poorly. It may also cause the system to take too long to train, which could render it useless. In terms of the IoT, if poor security practices are baked into the system, it can cause the system to become vulnerable to cyberattack. This means that if something is not coded correctly, whole smart factories could be rendered inoperable by simply exploiting something akin to a sensor or voice controller. More than anything else, following computer science principles will simply create better, more robust, and more durable machines. In all, even if you do not use innovative technologies, such as ML, the cloud, or the IoT, it will still pay to learn the core of computer science.

Overall, computer science principles will help secure systems from attack, create smarter systems, and, most importantly, save money. The core of this stems from good coding practices, quality logic, and learning how to implement efficient software. So, now that we know why we need to understand computer science, let us take a step back and look at what a PLC is at the application level. For beginners, especially those who have programmed microcontrollers in the past, the concept of a PLC may not seem necessary. However, in terms of applications, there is a vast difference between microcontrollers and PLCs. With that, let us explore how they differentiate.

PLCs versus microcontrollers

Over the past 15 years, microcontrollers have become quite common for electronics education and hobbyists in general. At first glance, a PLC is a lot like a microcontroller, and if you were to compare a microcontroller to a PLC from 30 years ago, a PLC basically was a rugged microcontroller. Based on the PLC definition established before, it is quite easy to confuse the two types of controllers or, at the very least, confuse the applications. The nature of PLCs has changed, and the two types of controllers are worlds apart. Therefore, it is especially important to understand the differences between the two types of controllers, as it is often more appropriate to use one type over the other. To understand how a PLC differs from a microcontroller, let us explore what a microcontroller is.

What are microcontrollers?

A microcontroller can best be thought of as a low-level computer on a chip. Common microcontrollers include the following:

PICsAVRsArduinoBASIC StampPICAXERaspberry Pico

It is important to note that many of these devices, such as Arduinos, BASIC Stamps, and Raspberry Picos, are not microcontrollers in the same sense as a PIC. These devices are best thought of as developer boards since they come packaged with a lot of external hardware that AVRs and PICs do not have. It is also important to know that these devices, especially the PICAXE, come with a bootloader loaded on them to understand their special programming interfaces, such as the Arduino programming language or PBASIC. For this discussion, we are going to keep things high-level and group all those devices into the microcontroller category.

In terms of architecture, a microcontroller will often come packaged with its RAM, ROM, CPU, and other peripherals baked onto the chip. Microcontrollers do not run operating systems and can only run one program at a time. In short, most microcontrollers are best described as embedded components. So, what are some of the surface-level differences between a PLC and a microcontroller?

Surface-level differences

On the surface, PLCs and microcontrollers are vastly different. A PLC is a self-contained electronic computing apparatus that will usually have built-in programming connectors and expansion ports. On the other hand, a true microcontroller, such as a PIC, is a chip that requires external components, such as external clocks, resistors, and so on, to operate.

It can be said that PLCs have more in common with Arduinos and other development boards that are microcontroller-based. For example, most development boards can be programmed with a USB or ethernet cable and do not usually require external components other than a power supply to run. However, the similarities usually end there. A major difference between a PLC and a microcontroller is the programming system that they use.

PLC and microcontroller programming languages

In general, microcontrollers are programmed in a derivative of a traditional programming language, typically a C, Assembly, Python, or BASIC dialect. For the most part, each microcontroller will have a corresponding programming language. For example, Arduinos use the Arduino programming language, which is a variant of C++, PICAXE chips use a version of BASIC, PIC microcontrollers use C, Parallax’s BASIC Stamp uses BASIC, and so on.

PLCs, on the other hand, are programmed using Ladder Logic, Structured Text or other dedicated PLC programming languages. Most PLCs are programmed in Ladder Logic, which is a programming language designed to simulate relay logic and digital circuits; however, recently, Structured Text (a text-based programming language that is reminiscent of a cross between BASIC and Ada) has been on the rise. Ladder Logic is, right now, more popular than Structured Text, but when it comes to architecting quality and secure code, Structured Text is much easier to use.

There is also another major difference between PLCs and microcontrollers: standardization. Many microcontroller programming languages do not follow any specific standards. Different programming systems can be used to program microcontrollers if the chips have similar architecture, but the languages themselves will usually vary. Many major PLC brands, such as Allen Bradley, Siemens, Beckhoff, and so on, follow the IEC 61131-3 standard. Essentially, this standard is a set of programming language rules that compliant devices follow. The goal of standardizing PLC programming languages, among many other reasons, is to ensure there is not a drastic learning curve between manufacturers. However, much like microcontrollers, a program written for one PLC device will rarely be able to run on a device made by another company or even another PLC model. With that, how are the two devices used?

Use cases

The use cases for PLCs and microcontrollers are also radically different. For the most part, a microcontroller or microcontroller development board is used for low-voltage applications, with very few designed to give outputs over +5v. Microcontroller chips are normally used in the following types of applications:

ToysHobby projectsConsumer electronics (appliances, TVs, etc.)Vehicles

Just about anything that is low voltage in nature and is not designed to perform in a complex industrial environment will usually be controlled by a microcontroller. The best way to think of a microcontroller is as an embedded device.

As stated before, PLCs are used for industrial purposes. For example, PLCs are a mainstay in factories because they run for prolonged periods of time without needing maintenance. They are also designed to control high-voltage systems that are usually associated with machinery. A PLC is not an embedded device. On the surface, a PLC can be thought of as an industrial microcontroller, but it is important to realize that they are different from microcontrollers.

Compared to a microcontroller, a PLC is much more rugged and can run for years without needing maintenance and even longer without needing to be replaced. It is not uncommon for a PLC to be in service for decades. PLCs are specifically engineered to be rugged devices that can withstand an extreme environment without interrupting the process(es) they are programmed to control. Though microcontrollers are often used as components to make a PLC, a PLC is not a microcontroller.

This does not mean that microcontrollers are excluded from the world of automation. Microcontrollers are used in many facets of automation, with applications ranging from machine controllers to the chips used in PLCs. Microcontrollers are particularly important electrical components, and their importance cannot be understated; however, to reiterate, they are not PLCs and should not be employed to do the same job as a PLC.

Therefore, a PLC has more in common with a traditional computer than a microcontroller. To appreciate the complexity of a PLC, let us explore the differences between a PLC and a computer.

PLC versus computers

Over the past 20 or so years, the cost of computers has dropped significantly. This drop in price has given rise to cheaper and more powerful computers. This increase in computing power and decrease in price has been reflected in all aspects of life. For example, smartphones are now an integral part of society; virtually everyone has easy access to tablets, such as Kindles, smart homes are on the rise, and more. This shift in computing has also seeped into the automation world. In contrast to the past, hardware-based control panels have been replaced with touchscreen HMIs, advanced networking technologies are employed everywhere, and, of course, PLCs (that more resemble modern computers as opposed to microcontrollers) are a mainstay in most factories. But before the similarities between a PLC and a computer can be explored, it is important to understand what a computer is.

What is a computer?

Describing a computer can be a bit difficult because many devices, such as modern smartphones, have significantly more power than a state-of-the-art desktop computer from 20 years ago. As such, many devices qualify as computers, even microcontrollers, to an extent. This means that many different devices can be considered computers, and whole books can be dedicated to defining what a computer is. However, for our purposes, we are going to keep things broad and think of a computer in terms of a modern, traditional personal computer – that is, a microprocessor-based device that utilizes an operating system and can run multiple applications at the same time.

PLC versus computers

As said before, although PLCs are often conceptualized as industrial microcontrollers, that is only a superficial comparison. Remember, a microcontroller can best be thought of as a low-level computer on a chip because it will often come packaged with its own RAM, ROM, CPU, and other peripherals baked onto the chip. Microcontrollers do not run operating systems and can only run one program at a time.

In contrast, a computer is a microprocessor-based system with external components, such as ROM, RAM, and other external peripherals. A computer system also requires an operating system such as Windows, MacOS, or a Linux distro. When one compares a computer to a microcontroller, major differences start to manifest. For example, a computer’s main goal is not to control external hardware in the same sense as a microcontroller does; a computer has way more computational power and can run multiple applications simultaneously.

If one were to examine a PLC, one would find that most of the major brands are microprocessor-based, have external peripherals, such as ROM and RAM, and many of the more advanced PLCs use some form of operating system. For example, a high-end Beckhoff PLC will run Windows, whereas brands such as Wago usually use a Linux distro for embedded devices. The reason PLCs are often touted as industrial microcontrollers stems from lower-end PLCs that behave more like microcontrollers than computers and because the PLC can only run one control program at a time. However, advanced PLCs, such as Beckhoff PLCs, blur the line between PLC and computer, run an embedded version of Windows, and have Intel microprocessors. On top of that, the more advanced PLCs can usually house and run their own HMI, security software, control program, and so on simultaneously.

Summarily, it is true that a modern PLC behaves similarly to a microcontroller, considering that it can run one control program and, like a microcontroller, controls external circuitry; however, that is where the similarities end. In terms of modern PLC programming and automation programming in general, it is no longer wise to think of PLCs and other control devices as simple microcontrollers. It is better to think of a modern PLC as a computer designed to control machinery.

Summary

This chapter explored the basics of how automation engineering relates to computer science. Thus far, PLCs, computers, and microcontrollers, their use cases, and more have been explored. By this point, a solid foundation on the concepts should have been established.

The days of hodgepodge Ladder Logic programming are ending. The automation industry is notorious for being many years behind the curve in terms of technological advancements; however, over the past 10 or so years, technology has made leaps and bounds that cannot be ignored. With the introduction of technologies such as the IoT, the cloud, and machine learning, automation developers are going to be forced to abandon the old mindset of “if the program works, it’ll do.” Automation programmers are going to have to adapt to new trends, which means a core understanding of software will be vital in the coming days.

With all that said, a basic understanding of PLC hardware is required to move forward. Just as hardware is nothing without software, software is nothing without hardware. Integrating PLC modules and other hardware is pivotal to the success of a project. As such, the next chapter is going to explore basic PLC hardware components.

Questions

What are three use cases for a PLC?Can a PLC be used in a space launch system?Why is computer science important to an automation programmer?What are two use cases for a microcontroller?Name three emerging technologies for industrial automation.What is computer science?Why should automation programmers care about computer science?Name three common microcontrollers.What are some common microcontroller programming languages?

2

PLC Components – Integrating PLCs with Other Modules

Software and hardware have a symbiotic relationship. Without hardware, software is useless, and vice versa. A key component of computer science is hardware engineering, and as most automation programmers know, hardware is a major factor in automation machinery. In other words, you cannot have a quality machine without quality hardware and software.

In terms of hardware, a PLC is a series of integrated modules that take in data and provide some type of output. To do this, PLCs utilize many different components, such as switches, sensors, motor drives, and safety modules, that all work in unison to control a machine. The key to these systems is the PLC. However, many inexperienced automation engineers do not fully understand what a PLC is, how to integrate external modules, and so on.

Knowing what a component does and how to integrate a module into a PLC system is vital to successful engineering. Even if a person is a dedicated programmer, an in-depth knowledge of hardware is required to both program and troubleshoot a machine. As such, the following is going to be explored in this chapter:

PLC typesCommon PLC modulesSinking vs. sourcingSensorsMotor controlCommunication protocolsWiring diagrams

To round out the chapter, we are going to design a theoretical system that will turn on a motor when a switch is turned on and shut the motor off when a sensor is tripped.

Technical requirements

This chapter will not utilize physical hardware or software. However, to complete the final project, rendering software will be needed. For the most part, no electrical symbols will be used. This means that any rendering software can be utilized, even something as simple as Paint. However, the examples are going to be drawn in block diagram format using draw.io, which is free to use online.

PLC types

PLCs are the brains of a machine; however, there is not one single type of PLC. In actuality, there are two major categories of PLCs, which are known as modular and fixed PLCs. When designing a system, it is important to understand the difference between the two types so the correct one can be chosen for the project. The following is a high-level breakdown of the two types of PLCs:

Fixed PLCs: Fixed PLCs are ones that have their I/O already integrated into them. These PLCs are usually cheaper than modular PLCs but are usually not expandable. This means that whatever I/O comes with the unit is what the engineer is stuck with. Generally, these PLCs are great for standalone or small projects that will never need to be updated. An example use case for a fixed PLC would be something akin to an automatic door opener. For an application like this, there will probably never be a need to expand the system, and only a handful of I/O ports will be needed. In this case, a fixed PLC will be optimal because it will be less expensive.Modular PLCs: Modular PLCs are more expensive but more flexible. Modular PLCs are very common in large automation projects due to their flexibility and higher memory capabilities. Due to the ever-evolving nature of industrial processes, it is very common to see modular PLCs in factories. Overall, there will be a higher upfront cost with modular PLCs, but they will offer more expandability in the future.

Modular PLCs can be considered to be more complex than fixed PLCs. More thought must go into the system design since modular PLCs are not integrated units. Therefore, to fully grasp modular PLCs, the modules that compose them need to be explored.

Common PLC modules

As could be deduced from the last section, a modular PLC is not a singular unit. PLCs are composed of many different modules that, when integrated together, form the PLC. Many different modules do many different things; however, all PLCs have a select few modules that perform the same functionality across all brands. This section will be dedicated to exploring some of those modules. With that, let us explore the power supply module!

Power supply

As everyone knows, electronic devices require electrical power of some type. PLCs require a stable power supply to function properly. Most PLCs utilize a 24VDC power supply. Depending on the PLC brand, the power supply will either be a module that attaches to the PLC in some way or it will be directly wired to the PLC. Of all the modules, the power supply is probably the easiest to comprehend. Let us now explore what a PLC chassis is.

Chassis

Depending on the PLC system being implemented, modules will need what is called a chassis or rack to interconnect with each other. A chassis is like a carriage that houses multiple modules and allows the modules to communicate with each other. A chassis is not always necessary, as some devices connect by simply attaching to each other. For example, to integrate Beckhoff modules, all one must do is slide them together and set an address on the device. Whether a PLC requires a chassis or not will depend on the manufacturer and model. With that, we can investigate the CPU.

CPU modules

Regardless of the model, all PLCs have one key component. This component is known as the CPU module. Many inexperienced engineers consider this module to be the PLC itself; however, the CPU is actually a module as well. If the PLC is the brains of a piece of equipment, the CPU is the brains of the PLC. This module is the computer that houses the PLC program, memory, operating system (if applicable), and all the other necessary components that are needed for the program to tick.

This is the main module an engineer or tech will interact with. These modules usually have some type of communications interface, such as a USB port, Ethernet, or other custom port that is designed to interface with a standard personal computer that contains the programming software. By interfacing with the CPU module, an engineer or tech will be able to do the following:

Upload/download a programAlter the programChange values in the program, such as timer and counter setpointsRead the real-time data collected by the unit

The CPU module will typically be integrated with other modules, such as the I/O (input/output) modules that will send signals to it. The CPU will then process those signals and carry out the programmed instructions. If the CPU module fails, the system will fail with it. Now, if the CPU is the brains of the PLC, the I/O modules can be thought of as the nervous system.

I/O modules

I/O modules are pivotal to a PLC as these modules are responsible for receiving inputs and driving outputs. In terms of I/O modules, there are two main categories that engineers need to know about. The first category is digital, and the other is analog. Both categories have their own uses, and both are of equal importance. Most PLC systems will incorporate a combination of the two types of I/O, which means that an engineer won’t be able to function without a basic knowledge of how they both work. Therefore, to begin the discussion, let’s explore digital modules.

Digital I/O

Digital I/O modules, or as they are sometimes called Discrete I/O modules, are PLC modules that operate in either an on or off-state. Digital I/O modules fall into two categories: inputs and outputs. An input device is usually tied to something like a sensor or switch and once it detects voltage over a certain threshold, it will send a signal to the CPU module that the data point is on. Once the voltage is below a certain threshold, it will lose the signal to the CPU module, therefore letting the PLC know that the data point is off. On the other hand, output modules are usually tied to devices such as relays, LEDs, alarms, and so on. Output modules are used to control the state of these devices. In other words, the CPU module will send a signal to the output module telling it to turn the device on or off.

Overall, it is important to know that discrete devices are like switches; they are either fully on or fully off, and there is no in-between state. Though threshold voltages and outputs can sometimes vary from module to module, 24V will usually trigger a digital module to the on state, and an output module will usually be 24V when activated. For many cases, having a fixed on or off state is not desirable, so an engineer can employ analog modules for cases like these.

Analog modules

Analog modules are like digital I/O modules in that they send and receive signals from the CPU. Unlike their digital