Reusable function to toggle bit

A forum devoted to the discussion of all topics having to do with scripting and other advanced programming using iX Developer.
Post Reply
MatthewMunoz
Posts: 15
Joined: Tue Oct 30, 2012 8:33 pm

Reusable function to toggle bit

Post 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

AMitchneck
Posts: 137
Joined: Mon Jun 11, 2012 2:10 pm

Re: Reusable function to toggle bit

Post 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)
Adam M.
Controls Engineer
FlexEnergy

MatthewMunoz
Posts: 15
Joined: Tue Oct 30, 2012 8:33 pm

Re: Reusable function to toggle bit

Post 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

Post Reply