Search code examples
functionplccodesys

CodeSys and RasPi PLC - do FB's in Main() get reinstantiated on Scan?


I'm currently setting up CoDeSys to run on a RasPi but I'm having a little difficulty understanding the specifics of how variables and function blocks within the Main are, or are not, instantiated again upon call when the Main is scanned again.

The closest SE question to what I'm asking is here, I think, but I have a slightly different question. YouTube videos and code examples don't seem to be answering this for me.

I've got the code working under "Step 4: GPIO Control" of this example, I've got my task set to run cyclically at a 20 ms interval, and it does not include anything other than the typical Main. So here's my confusion, in two parts:

  • While I see that the variables in the VAR / END VAR block are instantiated once and then just updated every time the Main block is scanned (i.e. every 20 ms), what about the timer (TON) function blocks? I can see that the timers are indeed running the full 1000 ms despite the Main being scanned every 20 ms, so how does the PLC know that the TON's should not be instantiated again?
  • In single-core PLC's, how is this threading handled? If I understand what I've read correctly, the PLC will not pause execution of the Main while it works through the function blocks that are called.

Thanks!


Solution

  • Variables in a VAR block of a program are not re-instantiated cyclically. Instances of function blocks are variables, just not of a basic type. They are not re-instantiated.

    Watch out : in methods, variables defined in a VAR block are only valid for the duration of the call (they are on the stack, if this means something to you). You would typically not instantiate a function block there (but having pointers/references to function block instances would be typical).

    The PLC works by polling. It does not "wait for the timer", rather it checks every cycle if the timer is done and reacts if it is. Everything is checked every cycle. If you have two timers, they will not each have their thread, they will just be checked every cycle by the same thread.