Pointers to standard table

I use a ModBus kit to read 100s of registers from my PLC. This registers are read to a integer32 table. Is there a simple way (using pointers) to have single integer variables pointing to selected table indexes. The code at the present, run every cycle:

nMotor1Isolated = ntStatus[0];
nMotor1Tripped = ntStatus[1];
nMotor1RunMC = ntStatus[2];
nMotor1Running = ntStatus[3];
nMotor2Isolated = ntStatus[4];
nMotor2Tripped = ntStatus[5];
nMotor2RunMC = ntStatus[6];
nMotor2Running = ntStatus[7];

and so on…

Is there a way to use pointers and assign only once on startup?

Yes, you’d need a pointer table, which you’ll initialize in your Powerup chart like this:

// initialize pointer table:
ptMotorValues[0] = &nMotor1Isolated; 
ptMotorValues[1] = &nMotor1Tripped;
ptMotorValues[2] = &nMotor1RunMC; 

And also a pointer to an int32, which you’ll use in your cycle/loop for each of those elements in the integer table, like this:

// spin through your ntStatus table and assign them to what the pointer is pointing to 
// (the individual int 32)

for nMotorValueIndex = 0 to (CONST_MAX_MOTOR_VALUES - 1) step 1
  pInt32 = ptMotorValues[nMotorValueIndex]; // get a pointer to the int32 we're doing next
  *pInt32 = ntStatus[nMotorValueIndex]; 
next

That’s it!

1 Like

It looks like not much saving, code wise still have to declare lots of data (now instead of var1=table[0] we do pTable[0] = &var1) but we are introducing a for-next loop every time we load data from modbus.

Have you tried using excel for this? You can list your variables and create a formula that writes the Optoscript. I do this all the time. I store the spreadsheet in my strategy folder.

If you are concerned about speed, this won’t take a PAC very long to do - the for loop will be multiple orders of magnitude faster than the network/serial modbus call.

If you really, really want to make this “cleaner”, you could modify the Modbus kit subroutine you are using so that it will store your values directly into a pointer table instead of an integer table.