Part 3 - Tasks, programs and “Hello world”
Video
#PLC #TwinCAT3 #Beckhoff #IEC_61131-3
Table of Contents:
- A) Objectives
- B) Traditional Software vs TwinCAT3 Software with real-time behavior
- B.1) Basics of Hardware, Software and User
- B.2) Software → OS Subsystems → Processor Management & CPU Scheduling
- C) BIOS Settings for TwinCAT3 (enable VT-x)
- D) TUTORIAL 1 - Creating "Hello World!" with ADSLOGSTR() //FILE --> HelloWorld Project
- D.1) How to create a new TwinCAT project
- D.2) How to select the Dark Theme
- D.3) TwinCAT project (Visual Studio Solution Walkthrough)
* D.3.1) SYSTEM
* D.3.2) PLC
* D.3.3) I/O
* D.3.3) MOTION, SAFETY, C++, and ANALYTICS - D.4) How to create a Virtual PLC
- D.5) How to configure Real-Time Settings
- D.6) PLC POUs (Program Organization Units)
- D.7) ADSLOGSTR() function and creating "Hello World!"
* D.7.1) msgCtrlMask
* D.7.2) msgFmtStr and strArg
* D.7.3) Output (Error List and Popup)
* D.7.4) Creating "Hello World!" - D.8) Licensing
- D.9) Running "Hello World!
- E) Summary (copy code)
- Z) Glossary
A) Objectives
In this tutorial we will go through some basics regarding why a standard operating system is not suitable for many of the industrial automation tasks and why you need something like TwinCAT for certain applications.
We will look into how TwinCAT is co-existing next to the operating system and how they co-operate.
We will create our first TwinCAT 3 solution and learn how to configure the realtime properties of our project.
In order to run any TwinCAT software we will also need to enable virtualization in the BIOS of the computer, which will be shown.
We will briefly look at how licensing works in TwinCAT 3, and after that we will create the classical "Hello world" program, although it will probably be different compared to the conventional programming languages you might have worked with previously.
So, while we are at the topic of programming conventional IT-software, what is the main difference between this and programming PLC software?
B) Traditional Software vs TwinCAT3 Software with real-time behavior
First, we will look into the differences of developing traditional IT-software running as a process in an operating system compared to writing software that runs in TwinCAT 3.
In order for us to understand how TwinCAT 3 is working and how we can guarantee real-time behavior, we have to start with the basics first.
B.1) Basics of Hardware, Software and User
Let's start at the bottom ⬇️
A computer basically consists of memory, a CPU, and I/O such as a keyboard, graphic cards and network adapters. All these together make up the hardware of the computer.
On top of the hardware, we have the operating system which is directly interfacing with the hardware. When you start a computer, the BIOS (Basic Input Output System) onboard the motherboard of your computer starts the operating system on the disk, which is the first software that is loaded.
The operating system is a program that acts as an interface between the user and the computer hardware.
The OS consists of several subsystems, each and one with its specific responsibility. A few of them are the:
-
"Processor Management" - which takes care of which process gets the CPU when and for how much time
-
"Device Management" - which keeps track of all devices, and decides which process gets the device and for how much time
-
"File Management" - which keeps track of information, location of information, uses etc
-
"Memory Management" - which keeps track of primary memory, which amongst many other things include keeping track of what parts of it are used by which process and which parts are free, and allocating/deallocating memory to/from a process
-
"Security Management" - which prevents unauthorized access to programs and data.
On top of the operating system we have our conventional applications, such as Microsoft Office, Photoshop and games. Here we also find the applications that we need to develop our own software, such as compilers and editors.
Finally, on the very top we find the (eventual) user that is interacting with the applications.
B.2) Software → OS Subsystems → Processor Management & CPU Scheduling
Let's review in detail the Processor Management
B.2.1) The Scheduler
In Windows we have a piece of software called the Scheduler, and it is this software that decides which process gets the CPU when, and for how much time. The distribution of this is based on a scheduling policy.
Let's review an example:
In this simple example we have a process in the operating system running.
Now let's assume we have a second process started.
In this case, based on the scheduling policy, the scheduler would pause the first process, and start the second.
From the perspective of the first process, this is completely transparent and the program would not recognize the interruption. Internally the program can start several threads, but these all still reside within the same process. Now the second process would be running while the first one would have to wait until it again is assigned CPU time
The scheduler continues distributing processing time like this between the processes.
With multi-core CPUs, it's possible to run several processes simultaneously but it's still the scheduler that decides which processes gets how much time and at what points in time.
The execution of these two programs is not deterministic. This means that there are no guarantees from the operating system for how much time a process will get from the CPU. It can get interrupted at any given time.
For a system controlling a machine, being interrupted in the middle of controlling a moving object can lead to undesirable results. For many applications, this is fine but within the field of industrial automation we need to be able to set boundaries for how long time a certain process can take.
B.2.2) Scheduling Policies
There are many various scheduling policies available, each one with it's own philosophy of how CPU time should be distributed. There is no-one that is "the best", which one that is more suitable all depends on the use case. Some policies are even combinations of other
In Windows 10, a policy called "Multilevel feedback queue" is used which is a combination of the algorithms :
- fixed-priority pre-emptive scheduling
- round-robin
- first in, first out
B.2.3) Context Switching
If you compile a conventional program and run it for example in Windows,
it has an entry-point and an exit point.
At anytime during its execution the program may be interrupted for a while, if the OS decides some other process should run instead.
If a program is interrupted, Windows will save the current program's state, figure out which one to run next, and restore that programs state. This mechanism is called context switching.
B.2.4) User Mode vs Kernel Mode (CPU Protection Rings)
In Windows (and most other operating systems) there is a distinction between code that is running in "user mode", and code that is running in "kernel mode".
A CPU have modes of operation called "rings", which specify the type of instructions and memory available to the running code.
There are four rings available, although Windows generally only uses two of them:
- ring 0 - kernel
- ring 3 - applications (user)
B.2.4.1) Ring 0 (Kernel mode)
Ring 0, also known as kernel mode, has direct access to the hardware.
In Kernel Mode we will find:
- TwinCAT scheduler
- Tasks and Programs
- I/O communication (real-time)
By running in kernel mode, it's possible for TwinCAT Real-Time to access the network ports directly and send and receive real-time Ethernet telegrams (e.g. EtherCAT)
B.2.4.2) Ring 3 (User mode)
Ring 3 is much more restricted, which also works like a protection as the different applications running in Ring 3 can't bring down each other and crash the whole system.
It's in Ring 3 that we have all the "User Space" Windows applications running, in other words, all processes in Windows.
Through something called Virtual Memory, a process running in User Mode can't interfere with memory allocated for another process running in User Mode.
B.3) TwinCAT Real-time scheduler (two separated cores)
TwinCAT 3 is a real time extension to Windows (and also to the FreeBSD derivate Tc/BSD)
In the case of Windows, it runs as a kernel module in Windows and it's this that allows for real-time capable scheduling and parallel execution of tasks, as it has direct access to the hardware.
TwinCAT works with a kernel mode scheduler,
which distributes CPU time to TwinCAT Tasks,
and the operating system itself.
In this example we have a two core PLC
-
On core #1 we have TwinCAT tasks running
-
On core #2 we have configured Windows to run. Windows is just doing the stuff it usually does, as for example:
- running various applications
- running an HMI,
- running a web server
- communicating with the outside world using the TCP/IP stack
In this scenario, even though we have a 2 core system Windows won't actually even see the first core as this is entirely under the control of TwinCAT and Windows doesn't have access to it.
A TwinCAT task is a time container in the processing of an IEC program.
A TwinCAT task can do things like:
- run PLC programs
- do Motion Control
- or interface with the EtherCAT I/O bus
A TwinCAT task is defined by
- a name
- a priority
- and by some time properties like the cycle time
The cycle time is defined as the time it takes to run the cyclic code start to finish.
A task is executed indefinitely many times, and thus anything inside of it can be seen as an endless while-loop and the cycle-time specifies at what interval the while-loop should be executed.
For each task you can now specify a series of programs that will be started by the task.
It's up to the PLC developer to make sure the tasks that we create manage to finish within the cycle-time defined for them.
TwinCAT has built-in and external tools to monitor the real-time usage to aid us in designing our real-time software so that we don't get cycle-time overruns.
Our two tasks in this example need to finish within the cycle-time that we have defined, and preferably so with a margin, which will be be used as idle time.
This whole sequence repeats indefinitely...
For you with a traditional software background, you can see this execution as an endless while-loop, although with clearly defined execution times
As we have two tasks here, it's possible to define the priority of the tasks.
In this application we have strictly separated everything that runs real-time from non-real time by separate cores.
With TwinCAT 3 it's possible to have the TwinCAT tasks and Windows share cores
In a use-case where TwinCAT and Windows shares a core, TwinCAT switches between real-time and non-real time mode to allow Windows to run
It should also be noted that we have standard network UDP and TCP/IP communications in Windows by the standard network stack that is provided by the operating system.
Because this is not suitable for real-time usage, TwinCAT provides drivers for real-time communication so that you don't have to go through Windows for extremely fast speed and low jitter communication.
Examples of this is a real-time UDP driver, but also various industrial fieldbuses such as EtherCAT.
B.4) TwinCAT Real-time scheduler (one shared core)
In the previous example, TwinCAT tasks were allocated a separate core, and Windows was running in its separate core too.
Now we will look in how it's possible to share a CPU core between TwinCAT real-time tasks and user-space applications in Windows in a so-called shared core configuration.
In the case of a shared core, TwinCAT utilizes something called the double-tick method,
in where both switching to real-time mode, the tick, and switching back to user-mode, the double-tick, is triggered by an interrupt.
There is a new concept here, the base time. The base time is the time frame for a constant interrupt where the TwinCAT scheduler pauses Windows and provides time for the TwinCAT real-time tasks.
So if the base-time is set to 1ms, but the cycle-time is set to 10ms it means that the TwinCAT task will only be executed once every 10 ticks.
The TwinCAT 3 runtime wakes up every 1 millisecond and checks if it needs to execute any tasks.
Note: The cycle-time is always a multiple of the base-time
For a core that is shared between TwinCAT and the operating system, there is a limit for how much time (in percentage of the base-time) that the TwinCAT scheduler can use for real-time tasks in order for the OS to always have some time to run.
This upper limit is 90%, which means that if we set the value to 90%, the real-time tasks will get up to 90% of the time, and the OS will get the remaining 10% of the base time. This means that the OS will always at least get 10% of the base-time.
Note: If a TwinCAT task finishes before it has used up its time, the remaining time will not be blocked but the scheduler will immediately switch to the OS
Let's analyse the following example:
Now you might be wondering
"Why these two tasks have varying computing time between the different runs?"
You can clearly see that the execution of Task #2 takes much longer time the second time it executes compared to the first time.
The reason for this is that they might be doing different things in different cycles depending on their internal state.
In one state they might not be doing much at all, while in another state, they might be doing mathematically heavy calculations.
It's up to you, the developer to make sure that both of these tasks can finish within the defined cycle-time.
- This scenario is only applicable if you want to share a core between a TwinCAT task and Windows.
- In recent years, sharing a core is rarely used as the performance and the core-count of the Beckhoff PLCs have increased so much we generally have resources to spare. It is common to have one or two cores solely for Windows and the rest for TwinCAT, but this can vary quite a lot depending on the application.
- It should also be noted that the switching between real-time and non-real time takes some time, which decreases the performance of using shared-cores.
B.5) TwinCAT Real-time scheduler (core isolation)
When using a core that is exclusively reserved for TwinCAT real-time tasks, a so-called isolated core we don't have the double-tick that gives the CPU back to the OS. We only have the first tick.
If we have two cores or more, we can do core isolation.
In this example we have designated one core as a non-RT core, and thus only the OS (that is, Windows or Tc/BSD) can run on it.
We also have a core where we run our TwinCAT tasks.
Note that this core does not need to switch between the operating system and the TwinCAT tasks. 100% of it is available to the TwinCAT tasks.
We might have even more than two cores, and then we might even be able to have separate TwinCAT tasks run on different cores.
This might for example result in a task related to motion to run on one core and a task that is related to vision and cameras to run on another core, and a task related to doing condition monitoring on a third core.
Note: This picture is a little bit simplifying.
For example there will always be slight dependencies between the non-RT and RT cores even if we do core isolation. This is simply due to how CPUs are designed. The cores of a CPU do share common cache on the CPU die. These types of details are however outside of the scope for this tutorial, but it could be good to have in the back of the head.
B.6) Conclusion
Conclusion: you now have the base knowledge for how our applications can have deterministic properties.
Now I think it's time to create our very first program.
C) BIOS Settings for TwinCAT3 (enable VT-x)
Before we can actually execute TwinCAT 3 software on our computer, we need to check a setting in the BIOS of our development machine.
This is only applicable for 64-bit machines, which most computers nowadays are.
We need to make sure to enable Intel Virtualization Technology Extensions, abbreviated VT-x.
This setting can be found in the BIOS of the machine, and sometimes it can have different names as well.
I will demonstrate how to do this on two of my computers:
- First I'll show you how to do it on my desktop computer,
- Secondly I will show you how to do it on a Lenovo Thinkpad laptop.
The procedure should be similar on most computers.
C.1) Enable VT-x in BIOS (Desktop Computer)
- Start by restarting your computer and enter the BIOS.
If you don't know how to enter the BIOS of your system, it's usually printed on the screen when you start it, otherwise advise the manual of your computer. The BIOS is usually entered by continuously pressing either the F12, or the DELETE, or ESC key directly after powering on the system.
-
Next, on this computer we select ADVANCED, and then CPU configuration.
-
What we want to make sure is to have Virtualization technology enabled.
-
We can optionally enable the Intel Virtualization Technology for directed I/O, also called VT-D.
-
Make sure to Save before you exit.
C.2) Enable VT-x in BIOS (Lenovo Thinkpad laptop)
The procedure for the Lenovo Thinkpad laptop is similar.
-
Enter the BIOS
-
Go to security, and then Virtualization.
-
It's called virtualization technology here as well. Make sure it's enabled.
-
Save and restart.
D) TUTORIAL 1 - Creating "Hello World!" with ADSLOGSTR() //FILE --> HelloWorld Project
In this Tutorial, we will create a "Hello World!" program using the ADSLOGSTR()
function.
D.1) How to create a new TwinCAT project
OK I think it's time for us to write our first "Hello World!" program.
So we will be going to our virtual box that we have prepared
What we are going to do is to start the TwinCAT XAE shell,
And here we'll create a new TwinCAT project
And call this "HelloWorld". And press OK
Note: Make sure you have TwinCAT projects and TwinCAT XAE Project selected.
D.2) How to select the Dark Theme
Note: the dark settings are available in "Tools" -> "Options"
Select General Settings, and then the Color Theme
D.3) TwinCAT project (Visual Studio Solution Walkthrough)
As you can see here we have our solution, it's a standard Visual Studio Solution.
And in TwinCAT it's divided into several modules, or so-called configurations.
For example:
- SYSTEM
- MOTION
- PLC
- SAFETY
- C++
- ANALYTICS
- I/O
We will reviewing a few ones of these in this tutorial:
D.3.1) SYSTEM
In SYSTEM we will be doing all the configuration of TwinCAT, for exmaple:
- All the real-time settings
- Defining our Tasks and how often they should run and at what cycle-times
- We will also configure our licenses there (if you buy a license you can install it here).
D.3.2) PLC
In PLC is where we are going to do most of our work in this tutorial. This is where you add all your PLC code basically
D.3.3) I/O
In I/O we can see the fieldbus communication (so the communication with the outside world).
Some of the most common fielbus are:
- EtherCAT
- Profinet
- IO-Link
- Serial Communication
- etc...
These are the only three modules which we will be using in this tutorial.
D.3.4) MOTION, SAFETY, C++, and ANALYTICS
The other modules are:
-
MOTION is used when you want to control motors, and axis's. (useful for robots and CNCs)
-
SAFETY is for human safety related stuff, so you can program a special safety PLC and then you use some special safety logic. It's quite different than programming PLCs but we're not going to touch this in this tutorial. However it's quite an interesting topic.
-
C++, here you can develop C++ modules and use them in your TwinCAT environment
-
ANALYTICS, the Analytics Logger ensures the cycle-synchronous acquisition of process and application data from the machine controller. The data acquired is optionally transmitted to a message broker via the IoT communication protocol MQTT or stored locally in a file on the hard drive of the machine control and recorded with ring buffer functionality.
Note: you can hide the modules you won't use with right-click, then you select "Hide".
D.4) How to create a Virtual PLC
The first thing we are going to do is to create a so-called virtual PLC,
in TwinCAT 3 you can have several PLC projects, and the purpose of this is when you want to divide your project into several modules.
For example:
If you have one project that only does PLC control logic,
and then maybe you want to have one module that does vision for quality inspection.
Virtual PLCs are there just for you to divide your project into more logical groups. And each and one of these can have their own communication with fieldbuses, and to the outside world through ADS, they will have separate ports for this.
For this basic tutorial we will only be using one, so we will create one PLC project, we can call it "HelloWorldPlc"
When HelloWorldPlc is created, we can open it, and in here we have several folders.
D.4.1) VISUs
VISUs is when you want to create visualizations. This is the old-school of visualizations. With TwinCAT, it's provided a very basic set of tools to create very simple human machine interfaces, if you just want to prototype something and test something quickly then these visulizations are quite good.
Note: If you really want to do proper HMIs, I would advise you to look into the web-based HMIs that Beckhoff provides instead.
D.4.2) POUs
POUs stand for Program Organization Units and here is where you put your PLC code, all the function blocks, your programs, any functions, all of this is put in POUs
D.4.3) GVLs
GVLs stands for Global Variable Lists, and in PLC programming, it's very common to use global variables,
Note: if you're from the traditional PC software development, you know the general consensus that you should avoid global variables. But in the world of automation, global variables are basically a norm.
D.4.4) DUTs
DUTs, which stands for Data Unit Types. Here you can define your own data unit types, you can create for example structures, alias types, and so forth.
D.4.5) References
References for example are references to libraries, so this is basically all the standard libraries that you get with TwinCAT, which in turn some of them are based on libraries and code that has to be available if it is IEC61131-3 compatible.
D.5) How to configure Real-Time Settings
D.5.1) Real-Time --> Settings (Read From Target)
Next we are going to go to the SYSTEM module
And inside this folder we have:
- License: here is where we activate the different licenses including the test license
- Real-Time: here we define our real-time settings so this is where we will start
- Tasks: this are connected to the real-time settings so this is basically our executables or our environment for the executables
We are going to start by looking at this "Real Time" settings here
We'll start by selecting this "Read from target"
This means that we will read what is the hardware configuration of this particular target.
And in our case we're going to run everything locally, so it will be on the local device.
The target in our case is our development machine which we can also see here in this tab "Local"
Note: If we would have several PLCs connected to this device we would see them here but now we only have "local" which means that if we read from target we will read from the local machine and in this case it's even a virtual machine.
And we can see that it detected four cores, which is exactly what we have configured for this virtual machine.
and we can actually even see it if you go to the task manager.
We see that we have four cores in the Task Manager,
Note: For this development purpose it doesn't matter if they are virtual or if they are actual real physical cores, it's the same concept and everything will look the same as if you would run this on a real PLC.
D.5.2) Real-Time --> Settings (Shared vs Isolated Cores)
So we have these four cores available to be shared,
and what we can see here is that we are only using one core as a Real-Time Core,
the other cores are only solely used for Windows right now
And here we can also see the Base Time,
which I've discussed previously, which is basically this "tick" time between Windows and TwinCAT real-time
And what we can see here is that we've configured Core 0 to use up to 80% of the (total) time for TwinCAT.
Which means that (at least) 20% of the time will be allocated to Windows, so that Windows can execute its tasks
In this case Windows will also have 3 additional cores just for itself
Note: This configuration doesn't make any sense at all. If we have 4 cores, we can without any problems allocate 1 core 100% to TwinCAT and the other to Windows.
What we can do now is to isolate cores to TwinCAT,
which is what we want to do, and which basically means that only TwinCAT will "see" this core. And there won't be this switching between TwinCAT and Windows for this particular core.
We can use "Available cores (Shared/Isolated)" function here.
So we say that we should have 3 shared cores, so 3 cores between Windows and TwinCAT (although only Windows is going to use them). And one isolated (core).
Then we say that the isolated core should be used by TwinCAT. Which now means that the core limit is 100%, which means TwinCAT will have 100% of this cores available time. This also means that Windows won't see this core once we have activated this configuration.
The current configuration is that all four cores are shared,
but if we (click on) "Set on target"
We get this Window, and we just have to verify that we want 3 shared cores and 1 isolated (core)
It's going to want us to restart, we select "No".
We first save the project,
and then we restart manually.
Now, I've restarted the virtual machine and opened the project again, and as we can see we only have three cores now that Windows can see, and the isolated core is 100% only available for TwinCAT.
D.5.3) Real-Time --> Settings (PlcTask)
Down here we see our different tasks.
For now the only important task is this "PlcTask",
it's a default task created for this "PlcProject" that we have created here, so it's the default task for the program that we are going to execute.
And in this setting we have the base time set to 1ms and the cycle time set to 10ms,
But, because we are running this on an isolated core, the base time is not that important here because we know that we don't have to do this jumping between Windows and TwinCAT every 1ms.
We know that TwinCAT has 100% access to this core so the important thing here is only the Cycle-Time which is 10ms which means that the program that we are going to create is going to be executed once every 10ms.
So it means that we have to guarantee that this program will finish within these 10ms.
D.5.4) Real-Time --> Online
And then we'll go to the next tab "Online". Here we will be able to use/see some real-time usage.
So here we will basically see real-time performance of our tasks, so whether we'll have some jitter and how much of these 10ms that we are actually using.
D.5.5) Real-Time --> Priorities
Priorities is quite interesting when you start to add many many tasks that are executed one after the other,
then you can say which one has higher priority. Which means that one task can preempt another one which means it can interrupt one if it has a higher priority in case both of them can't in the same time (cycle-time).
Normally you don't need to change this too much, I usually even leave this at Automatic Priority Management
The important thing here is to measure your real-time performance and when you get some experience with TwinCAT you spend a lot of time in measuring this different real-time performance of the CPU just to see that your tasks finish in time (within the cycle-times).
So as you can see, it's very easy to configure the real-time configuration of your tasks
Running TwinCAT on an isolated core on a PC is one of the key advantages of using TwinCAT (if not THE key advantage). Beckhoff are utilizing the decades of development of the PC platform I mean, if you come to think about how extremely powerful PCs are now, and knowing that you can use that for industrial automation...that's amazing. You can simply use a very powerful PC with more cores than I have fingers on my hands and distribute the workload amongst them. The growth potential for having a real-time system based on a PC platform is almost infinite. At least I usually find my time to implement and test functionality to be the limiting factor, not the technical platform itself.
D.6) PLC POUs (Program Organization Units)
Ok so now we have our task, we have our isolated core, so now we should be able to run our software.
So let's now go to the PLC module and in the POUs, TwinCAT default creates a MAIN program
And the main program is referenced by this PlcTask,
which is the same PlcTask that we have under SYSTEM
So the reference of the MAIN (PRG) with the PlcTask is as follows,
Reminder: And again, the PlcTask, its real-time properties is defined in "Real Time" and we can see that our PlcTask runs every 10ms. Also we know that it is running on the 4th core in our CPU which is isolated so we know this task has 100% access to this physical core which is very neat
It's that easy! So if we go back here to POUs, and open our main program, it's very empty...
Basically TwinCAT is dividing everything into:
- A Declaration Part (for all variables in the program)
- And the Body (where we place all the control logic).
For this example we're only going to do a very simple "Hello World!" program so we're just going to call something called ADSLOGSTR()
D.7) ADSLOGSTR() function and creating "Hello World!"
So how does the ADSLOGSTR()
function work?
Learn more here
It has three arguments,
- the first one being the message control mask (msgCtrlMask),
- the second the message formatting string (msgFmtStr),
- and the final one the optional string argument (strArg),
This is our code in Structured Text:
ADSLOGSTR(msgCtrlMask := ADSLOG_MSGTYPE_ERROR OR ADSLOG_MSGTYPE_LOG,
msgFmtStr := 'Hello %s',
strArg := 'world!');
We will go through each and one of them, and we'll start with the first argument.
D.7.1) msgCtrlMask
With the "message control mask" (msgCtrlMask) we can define where the string should go and what type of message it should be treated as
In TwinCAT there is no "console" in the traditional sense as you might be used to using .NET, C++ or Python.
As the TwinCAT kernel and thus our TwinCAT software runs in a real-time environment we need to adhere to those rules.
What we can do is to send a message from our real-time context to the non-real time context, that is to Visual Studio or Windows.
When sending a message to Visual Studio we can present it as either:
- a hint
- a warning
- or an error
We also have a possibility to display the message as either:
- an entry in the Visual Studio error list
- or as a message popup box
We simply do an OR for these to combine it into the properties we want such as OR'ing ADSLOG_MSGTYPE_ERROR with ADSLOG_MSGTYPE_LOG to get an error message into the Visual Studio logger.
D.7.2) msgFmtStr and strArg
The second argument, msgFmtStr is where you provide the string that you want to be displayed.
It can contain the formatting code %s, which is the string that is provided as argument three in this function.
Whatever is at %s, will be replaced by the third argument strArg. If you done C style output with printf this is similar.
Note: You don't need to do it this way and can just write "Hello world!" directly in the second argument and leave the third argument empty.
D.7.3) Output (Error List and Popup)
If we run this with the LOG as output, it will be displayed in the Visual Studio Error list.
If we instead run it with the MSGBOX as output, it will be displayed as a popup.
We will discuss the ADS protocol in a coming episode of this tutorial but for now you only need to know that ADS is Beckhoffs middleware protocol and it can amongst many other things be used to communicate between the real-time context of our software, that is our TwinCAT3 software in this case and the non-realtime software, in this case the Visual Studio Error List or the Windows Popup.
ADSLOGSTR() is using a little bit of resources, but that's actually not the reason why I would advise against it. If you're used to printing loads of stuff on the screen for debugging purposes, you will soon find out Beckhoff provides great tools for debugging your software easily and quickly and I would advise to use those tools instead. We will get back to this topic in future episodes of this tutorial.
D.7.4) Creating "Hello World!"
Ok so now that we have gotten an introduction into how ADSLOGSTR is working let's just write it.
So just enter ADSLOGSTR
And here we have this Intellisense, where VS basically detects what inputs we have available. And with this as soon as we enter the first parentheses, VS will show us the three different inputs.
Here you can do [[Autofill (CTRL+SPACE) in TC3]] and it will autofill the rest.
Now we write this code to only run the message once and not every 10ms
Now, in order for us to run this we need to put TwinCAT into RUN-mode.
Right now it's in CONFIGURATION mode
but we can't do it right now because we don't have any software on our PLC.
So if we would put it into run mode right now it wouldn't execute anything because there simply isn't anything on it.
So what we use for that case is this button "Activate configuration"
and that basically takes all the source code on your machine and compiles it and then puts it on your PLC.
We can also do a "Build solution", which only compiles the project on your development environment.
So with "Build solution" you will only compile everything and see that everything is compiling.
With the "Activate configuration", you compile it and put it on the target device, and that's what we want to do.
We can actually just compile it and just see that it works, and we can go to "Output" and just see that we have build succeeded.
Ok next we're going to do the "Activate configuration", and here we get a little option.
We can select to autostart the PLC projects, and this is basically the normal case you want to use when you are finishing your development. What it does is that it, if you restart the PLC it will automatically start the PLC project for you. I usually don't use this in the beginning of the development phase because you usually have bugs and you can get some weird null pointer exceptions and for example if you have a PLC project that automatically starts then then it means you will just get into this endless loop where you never will be able to connect to the PLC to remove that program because it will just crash.
So we'll not enable this for now and then we will just manually have to start the project.
So press OK... (when I press OK the project will be transferred to the PLC and again in this case it's our localhost)
Now we got an interesting question here. "Some required runtime licenses missing. Generate trial licenses?" Before we can run our software, we need to have a license for TwinCAT.
D.8) Licensing
With TwinCAT 3, you don't need to spend a single cent to develop software Beckhoff's licensing model is entirely based on the runtime system. This means that you only need to buy a license for the actual runtime, that is the target PLC.
Until then, you can generate a new license key every week that works for a week.
So once the key runs out after a week, you activate a new one and can go on forever.
You don't need to contact any sales or Beckhoff support to get this trial license, you generate this entirely locally on your computer using a CAPTCHA.
When we enter the captcha, what happens is that the TwinCAT development environment will generate a license file that is put on the target PLC (in our case, our local development machine which acts as a PLC).
Once you've developed all the software and you get it to work fine, you replace the time-limited license-file with a real-license.
This is a huge advantage with TwinCAT 3 as it gives us the possibility to fully develop and test our software before buying any license.
So, once you actually want to run the software without a test-license on a real PLC indefinitely, what do the licenses cost?
Well, for one, there are different licenses depending on what you want to do.
If you only want to run PLC software and running an EtherCAT master for basic I/O control it's enough the buy the base license for TwinCAT 3.
If you want to do motion control, or integrate an SQL server for data storage, or run some C++ code in the TwinCAT real-time context or send SMS messages, you need a separate license for that particular function. (Again, even for all these extra functions you can generate a test license, whether it be a license for running Profinet, or running an SQL database or using a middleware such as OPC-UA or any other function that Beckhoff provides).
Secondly, the license is based on the target runtime performance.
When you buy a PLC from Beckhoff, it's classified into a class, based on it's performance.
The higher the performance, the higher the performance class.
We have everything from low performance single-core PLCs, to PLCs with 50+ cores and a ridiculous amount of memory.
With this licensing model, the licenses gets more expensive the more powerful the PLC is.
It's not only the base license to run TwinCAT 3, all the supplements and extra functions are also priced after the performance class of the PLC.
Now although you can run TwinCAT 3 software on any PC, if the TwinCAT XAR detects that the PC of which it is installed on is not a Beckhoff PLC, it automatically puts the PC in a higher performance class (usually the top one) even though the performance might be very low.
Beckhoff simply considers everything non-Beckhoff to be of the highest performance class.
This is very unfortunate, but understandable as Beckhoff would have to support hardware that they have not manufactured.
Again, I still want to point out that you can still use a normal PC (as Beckhoff PLCs ARE normal PCs) and still have very good performance, although you need to pay a higher premium for the licenses for not using the Beckhoff PLCs.
For pure development purposes, the higher license cost does however not matter as we are anyway only going to generate trial licenses for our PC.
I'm not going to go any deeper into the licensing other than this. For now it's enough to understand that the license is based per runtime and that we can generate test licenses as often as we want for all the software we need to develop.
In other words, it doesn't cost us anything to develop software for TwinCAT 3.
If you have a background like me, that is from traditional IT programming you might not be surprised about this I mean, come one, of course the development environment should be free! Right? You just most likely expect that the development environment shouldn't cost anything.
But trust me when I say that within the world of automation even just a yearly license for the development environment, for certain brands it can be ridiculously costly. This is just the world of automation, things seem to change more slow than in the traditional IT world.
D.8.1) How to generate a Trial License
We want to generate our trial licenses. Select "Yes",
and enter this CAPTCHA.
Click OK, it will generate licenses for me,
You can actually see this here if you go to "About TwinCAT"
And here we can see licenses, the test licenses will expire in a week
D.9) Running "Hello World!
And now it asks us "Restart TwinCAT system in Run mode?".
The run mode is this "green mode",
and we want to do that...
Now we noticed that the Login button got lit, this green button,
so we can login into the TwinCAT runtime, which means that we will be able to login to our program and watch the variables.
And this is one of the very VERY powerful features with TwinCAT that you can basically do all the debugging online, which means you can login to the PLC and see what's happening inside.
We're going to login to this PLC, and select "Yes" here,
Note: the reason we got this question is because we've not enabled the Autoboot feature, for now just select "Yes".
And now we can see the PLC Program online,
"bRunOnlyOnce" is FALSE right now, and the reason for this is that we haven't executed this program yet.
We haven't actually started it, and again this is because we haven't activated this autostart feature Which we don't want to do quite yet because, what if our program crashes? Then it would mean that our computer would just always crash-
So what we're going to do is to manually start this program
Note (how to logout):
you can also logout from this PLC project right now so you stop watching the variables.
And there we got our "Hello World!"
And we can also see that bRunOnce is TRUE here, which means this one has been executed
And if you want this one to execute again, you can change the "bRunOnce" value that is TRUE now to FALSE, do this "Write values", which writes FALSE to this variable
In the next part of this tutorial, we will dive deeper into the structured text programming language itself
E) Summary (copy code)
In this part of this tutorial, we created our first program and called one of the existing functions in TwinCAT called ADSLOGSTR()
function in where we could print a "Hello World" message to the Visual Studio error list. In that function we used the string "Hello World!" as input to the function.
Copy the PLC Code:
PROGRAM MAIN
VAR
bRunOnlyOnce : BOOL := FALSE;
END_VAR
------------------------------------------------------------------------
IF NOT bRunOnlyOnce THEN
ADSLOGSTR(msgCtrlMask := ADSLOG_MSGTYPE_ERROR OR ADSLOG_MSGTYPE_LOG,
msgFmtStr := 'Hello %s',
strArg := 'world!');
bRunOnlyOnce := TRUE;
END_IF
Z) Glossary
File | Definition |
---|