I'm writing an App on CODESYS that has a set of alarms in a variable list whose state I'd like to check in a program. Right now I'm just referencing those variables individually in the program, but I was wondering if there's a way to iterate through every variable in that list, in such a way that I could add new alarms without having to modify the program.
Any ideas?
Thanks
You can't. You may think that taking the address of the first variable and looping until you reach the address of the last would work, but here's an experiment:
However the above does not work at all, at least not on my machine. And that's the problem, CODESYS gives no guarantees how the variables will be arranged in memory. I run the code in a simulator, but maybe if I run on some PLC it could work, you can't rely on that.
A possible alternative would be to define your alarms in a structure and loop over that instead:
Results of the simulation:
This works since structures generally occupy a continuous chunk of memory, however again, I can't guarantee that some PLC won't add some padding to the struct.
Personally I'd use the Python ScriptEngine API that was added to CODESYS to check for changes in the alarms and generate new functions on every save of the project. However, this requires some knowledge of Python and the API. Here's a simple demonstration of the use of the API, which finds all variables of type BOOL in a given GVL and generates a function that counts how many of them are TRUE:
The results of running the above script is the following function:
If at any point you make any changes to the GVL, running the above script will regenerate the function accordingly, so you don't need to change any part of the code that calls the function.