Welcome Guest ( Login | Register )



All times are UTC - 7 hours [ DST ]



Post new topic Reply to topic  [ 3 posts ] 
Author Message
 Post subject: Reusable function to toggle bit
PostPosted: Mon Jul 24, 2017 10:20 pm 

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

Offline
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


 Profile  
 
 Post subject: Re: Reusable function to toggle bit
PostPosted: Tue Jul 25, 2017 7:36 am 

Joined: Mon Jun 11, 2012 2:10 pm
Posts: 96

Offline
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:
Globals.Tags.myvar.Value = ToggleBit(Globals.Tags.myvar.Value, 4)

_________________
Adam M.
Controls Engineer
FlexEnergy


 Profile  
 
 Post subject: Re: Reusable function to toggle bit
PostPosted: Tue Jul 25, 2017 4:05 pm 

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

Offline
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


 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 7 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron