Page 1 of 1

Reusable function to toggle bit

Posted: Mon Jul 24, 2017 10:20 pm
by MatthewMunoz
Hello,

I know from previous posts that I can toggle a bit in a tag using:

Globals.Tags.myvar.Value ^= 1 << 5;

I would like to be able to do this using reusable code which can be called using the "Run Script" action when I click on a button. I have put the following into a Script Module:

public int ToggleBit(int CurrentValue, int BitNumber)
{
CurrentValue ^= 1<<BitNumber;
string msg = CurrentValue.ToString();
MessageBox.Show (msg);
return CurrentValue;
}
When I run this on the development PC it reads the tag, modifies its value and shows the modified value in the message box, but it does not modify the tag value in the PLC.

What am I doing wrong?

Thank you in advance for your assistance.

Matt

Re: Reusable function to toggle bit

Posted: Tue Jul 25, 2017 7:36 am
by AMitchneck
First off, function variables are local to their function. This means any modifications to these variables within the function will not be seen outside the function unless the variable is passed by reference.

Luckily, you already have your function written properly to be able to pass out the result with the return statement. To use the function you just need to call it like such:

Code: Select all

Globals.Tags.myvar.Value = ToggleBit(Globals.Tags.myvar.Value, 4)

Re: Reusable function to toggle bit

Posted: Tue Jul 25, 2017 4:05 pm
by MatthewMunoz
Thank you Adam,

I appreciate your help. The project I am working on has about a dozen INT tags that need manipulation on the bit level. I made one script for each tag and only pass in the bit number. That way the script call can be set up and modified from the Action menu, which will make the repetitive setup work go faster and the project easier to maintain.

Cheers,

Matt