Join us today!
Retaining values of the variables declared in a method between PLC cycles - VAR_INST
The variables declared in a method gets reinitialized every time the method is called in per PLC cycle and they don't retain their values since they are saved in a method stack.
"All data of a method are temporary and are only valid while the method is executed (stack variables). This means that TwinCAT re-initializes all variables and function blocks, which you have declared in a method, with each call of the method."
In the example below, we have a function block called FB_Utilities and M_Count method. In the M_Count method implementation, we have a counter which is being increased by 1. When it reaches higher than 50, we stop the counting and log a warning.
FB_Utilities.M_Count :
METHOD M_Count : BOOL VAR_INPUT bStart : REFERENCE TO BOOL; END_VAR VAR nCounter : INT; END_VAR
IF bStart THEN nCounter := nCounter +1 ; IF nCounter > 50 THEN ADSLOGSTR(ADSLOG_MSGTYPE_WARN, 'Counter limit has been reached!', ''); bStart := FALSE; M_Count := TRUE; END_IF END_IF
In the main program:
VAR fbUtilities : FB_Utilities; bStart : BOOL; END_VAR
fbUtilities.M_Count(bStart := bStart);
If we login the PLC and try to monitor the value of the nCounter, we can see that we are not able to monitor it without setting a breakpoint.
Now let's set a breakpoint in the main program and see what happens to the nCounter value each PLC cycle.
We see that it gets reinitialized with zero between the PLC calls, therefore our counter never reaches to 50.
VAR_INST:
To retain the counter value, we can declare the variable using VAR_INST. Now the variable data will be stored in the stack of the function block instance instead of the method stack. Let's make the change in our code:
METHOD M_Count : BOOL VAR_INPUT bStart : REFERENCE TO BOOL; END_VAR //retain the values between the PLC calls VAR_INST nCounter : INT; END_VAR
Now, we can monitor the value of the nCounter without needing to set a breakpoint where the method is being called.
Since the nCounter value is retained, our counter is now able to reach 50 and we get the counter warning.
In case you want to say thank you !)
We'd be very grateful if you could share this community with your colleagues and friends. You can also buy us a coffee to keep us fueled 😊 This is the best way to say thank you to this project and support your community.
twinControls - https://twincontrols.com/
Related : VAR_STAT
In case you want to say thank you !)
We'd be very grateful if you could share this community with your colleagues and friends. You can also buy us a coffee to keep us fueled 😊 This is the best way to say thank you to this project and support your community.
twinControls - https://twincontrols.com/
In PRG methods VAR_INST did not work for me. But VAR_STAT can do the job in this case.
- 17 Forums
- 265 Topics
- 932 Posts
- 2 Online
- 689 Members