Join us today!

Retaining values of...
 
Notifications
Clear all

Retaining values of the variables declared in a method between PLC cycles - VAR_INST

3 Posts
2 Users
1 Likes
523 Views
twinControls
Posts: 114
Admin
Topic starter
(@twincontrols)
Member
Joined: 2 years ago

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. 

var

 

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.

var inst

 

 Since the nCounter value is retained, our counter is now able to reach 50 and we get the counter warning. 

 

 

Reply
2 Replies
twinControls
Posts: 114
Admin
Topic starter
(@twincontrols)
Member
Joined: 2 years ago

Related : VAR_STAT

Reply
Posts: 7
(@theshamot)
Active Member
Joined: 1 year ago

In PRG methods VAR_INST did not work for me. But VAR_STAT can do the job in this case. 

Reply
Share: