SETL
Hello, I want to ask you how to use Global variables in OpenPLC Editor. I want to create pulse variables as 100ms, 500ms, 1s pulse from the cyclic program via Global variables, but it's not possible because the compiler generates an error. How it's possible to create Global variables, that ist possible use in all programs with different cyclic settings. Thank you very much. 
global_openplc_1.jpg  global_openplc.jpg 
Reply 0 0
thiagoralves
Hi SETL. Creating the global variable is just the first part of the problem. To use a global variable, for each program that you want to use it, you must add a variable with the same name and select External for the Class. Make sure that the type also matches your global variable otherwise you will get a type mismatch error during compilation.

Also, from the screenshots it looks like you have two programs (program0 and program1), but on your resource screen it shows only one instance running program1. With just one instance, the runtime will run only one program. If you want to run both programs at the same time (program0 and program1) you will have to create another cyclic task and another instance and associate it with program0. Then both programs will run concurrently.
Reply 4 0
Robert Lewczuk
Hi SETL. Creating the global variable is just the first part of the problem. To use a global variable, for each program that you want to use it, you must add a variable with the same name and select External for the Class. Make sure that the type also matches your global variable otherwise you will get a type mismatch error during compilation.

Also, from the screenshots it looks like you have two programs (program0 and program1), but on your resource screen it shows only one instance running program1. With just one instance, the runtime will run only one program. If you want to run both programs at the same time (program0 and program1) you will have to create another cyclic task and another instance and associate it with program0. Then both programs will run concurrently.


This helped immensely Thiago but I still struggled longer than I should have so I add this for anyone like myself to save you time very simple you need to add the same exact name for the global item and class as you reference in the global variable list for any sub program then change the local variable in that program to external. EZ PEEZY.
Reply 2 0
kortenbach
Would it be a problem to gray-out the variable type field as soon as it is an external variabe? That way you can't make a "wrong type" mistake when referencing a global variable. I presume that it makes no sense to add a reference to a global vaiable when the types are different(?)
Reply 0 0
rojo
Can a program change value of a global variable so that another program can read an updated value?
Reply 0 0
thiagoralves
rojo wrote:
Can a program change value of a global variable so that another program can read an updated value?

Yes, as long as both programs are part of the same PLC project
Reply 1 0
MichaelWilt
Hola @ThiagoAlves tienen pensado mejorar el problema de estar forzado a declarar las variables globales en cada programa local ?
El método que se tiene actualmente para declarar las variables globales, sirve para proyectos simples/pequeños/ejemplos, sin embargo se convierte en un problema y desgaste de tiempo cuando se realiza un proyecto organizado en multiples programas que explotan las variables globales. En las plataformas de programación en general, las variables globales se declaran una vez y listo. Espero que pronto OpenPLC incluya esta mejora.
Reply 0 0
fg71
Arduino extension is a kind of second program and PLC logic is the main program.
A variable in Arduino extension is declared as external but in plc.st (the main PLC program) its a VAR_GLOBAL
 
The same approach is for access a variable from one program to other.
 
[203128%2F9074620%2Fmceclip0]
 
[203128%2F9074621%2Fmceclip0]
 
[203128%2F9074622%2Fmceclip0]
 
In the plc.st we get
 
[203128%2F9074625%2Fmceclip0]
Reply 0 0
MichaelWilt
El concepto de variables globales y locales, es el mismo en Arduino, en los PLC y en cualquier lenguaje de programación en general, las variables globales se declaran una sola vez (por eso se denominan globales) y pueden ser llamados o accedidos desde programas locales sin tener que volverlos a declarar o denominarlos de una manera distinta.
En OpenPLC se obliga al programador a repetir la declaración de la variable global como "externa" en un programa local,. Esto no ocurre con Arduino, ni con otro software de programación de PLC (Schneider, Siemens, ABB, Allen Bradley, Codesys, etc)
La forma que usa OpenPLC para acceder a las varibales globales es lo que se podría mejorar para reducir los tiempos de programación y depuración.
 
Imaginen el siguiente ejercicio:
 
Tengo 1 Programa local llamado "Principal" y tengo 10 programas locales adicionales llamados "Motor 1" al "Motor 10", cada uno con su particularidad.
En el programa principal leo la entrada lógica de mi botón de parada de emergencia, y seguidamente necesito incorporar esta señal de la parada de emergencia en la lógica de todos mis motores (que los tengo organizados en 10 programas locales diferentes), entonces en Open PLC tendría que declarar 11 veces la variable "Parada de Emergencia" como "externa", porque estoy utilizando 11 programas locales. Eso va a traerle al programador los siguientes problemas:
 
  1. Mayor tiempo por cada vez que debo declarar una "variable global" como "externo" en todos los programas locales.
  2. Quiero cambiarle de nombre a mi variable global y bueno ahora tengo que hacerlo otras 11 veces en todos los programas locales donde lo estoy utilizando y sin equivacarme jeje.
  3. Ahora necesito añadir otras señales que son comunes para los 10 motores, entonces tengo que volver a declarar como externa esas varibales, lo cual arrastra los problemas anteriores e incrementa el riesgo de error en la programación.
Espero que esto pueda ser mejorado en una siguiente versión de OpenPLC.
Con gusto modificaría el codigo fuente de OpenPLC para hacer esta mejora, sin embargo no tengo ni la más mínima idea de como hacerlo jeje.
 
Saludos.
Reply 1 0
fg71
You request is valid but I do not think Thiago will do so much with current OpenPLC Editor when he is starting a new project that use a different framework.
It would be better to suggest features to the new OpenPLC Editor that use Electron + React and use TypeScript as main programming language.
Lets say that is not true, I believe OpenPLC Editor is a fork of Beremiz and doing change in the source code that is the same as doing a pul request.
If the maintainer do not accept the change that is out of control for Thiago who are not maintainer of Beremiz.
 
I could be wrong but that is my thought.
 
Any feature that make efficiency regarding Local/Global variable is good ideas I agree with you.
Reply 1 0
MichaelWilt
Note from admin: post was machine translated from Spanish to English

Hello, can the "function blocks" be declared as GLOBAL variables? or are they only Local variables?
Here is the problem:
Create a Function Block called "MotorBasic_v001"
Add a Global Variable called: "Motor_01" of type "MotorBasic_v001"
Add a "Program" called "Motor_Image"
In the variables of the Program "Motor_Image" I declared the Global variable "Motor_01" as external and of type "MotorBasic_v001"
When I call the function block "MotorBasic_v001" from the library box and assign it the name "Motor_01" and it is created as a Local variable. Then I try to change the class "Local" to "External", however it does not allow me.
I add a couple of variables of type "BOOL" to test.
I compile and it gives me a "declaration" error. I understand that this is because the declaration "Motor_01" is being repeated as a global variable and at the same time as a local variable...
[203128%2F9129029%2Fmceclip0]
 
Could you tell me how to declare a function block as a GLOBAL variable?
Reply 0 0
thiagoralves
You cannot create a function block instance as global. This messes up the concept of object oriented programming and hierarchy. I believe your approach to this could be wrong. Perhaps instead of having multiple programs like you seem to have, maybe it is better to convert them all to function blocks and control them all from a single master program. Separate programs, in my opinion, should be used only when the same PLC is controlling different things that are logically separated. If you create multiple programs that are related to the same control logic, you end up having to create a bunch of global variables like you seem to be doing now.
Reply 0 0
MichaelWilt
Hola Thiago, Muchas Gracias por los comentarios.
 
Verifico que el software OpenPLC si permite crear una instanacia de bloque de función como global, sin embargo al momento de compilar el software encuentra que la declaración es inválida (es decir lo permite, pero luego lo ve como error jeje). No e probado el comportamiento del software al declarar un "TON" como global, pero en principio no debería generar problema.
 
Efectivamente el punto de vista que comentas es una opción (si sólo fuera para 1 sólo motor), sin embargo el ejercicio es sólo una "prueba" que me permite evaluar la flexibildiad de OpenPLC para soluciones que requieran mayor complejidad y mayor número de tareas a realizar de forma estructurada y ordenada, permitiendo que la programación sea facilmente adaptable y escalable.
 
La idea de este ejercicio se resume en lo siguiente:
  1. Tener una zona donde se asocian las entradas/salidas con las variables del automatismo: Ejemplo: In1 -> Confirmacion_Marcha_Motor_1; Motor_1_cmd -> Out0. Esto permite reasignar la variable del automatismo a otra entrada / salida sin tener que buscar dicha entrada en toda la lógica del programa y comprobar que se reemplazo en todos los puntos necesarios. Aquí se optimiza tiempo para resolución de problemas/cambios.
  2. Tener una zona donde se visualice el estado y las conexiones de I/O de todos los bloques de funcion de un mismo tipo (Ejemplo: "Motor_1, Motor_2, Motor_X....") que hayan sido creados y se necesiten utilizar.
  3. Contar con un programa "principal", donde se ejecutara la secuencia "Main" como su nombre lo indica.
  4. Contar con otros programas complementarios que ayuden a ordenar y a servir a la secuencia principal (ejemplo: Mensajes de Display, Sirenas, Alarmas, etc.)
 
Nuevamente recalco que existen muchas formas de dar solución a una determinada necesidad, sin embargo la finalidad de este ejercicio revisar y verificar la flexibilidad de los bloques de funciones que son creados por nosotros.
 
 
A continuación dejo una imagen de como resolví este tema:
  • Como el bloque de función no puede ser declarado como global, utilice variables globales creadas manualmente como "interfaz", de esta manera puedo utilizar la variable "Motor_01_Fault" en cualquier programa o rutina que lo necesite, sin tener que depender de la Entrada Digital que recibe esta señal.
  • Tambien agregue otros programas complementarios como PLC_System y Display_System, para poder enlazar variables entre los POU con la extensión de Arduino en OpenPLC. Esto requirio un poco más de tiempo, debido a que tenía que repetir la declaración de la variable global en estos POU, sin embargo el resultado fue el esperado.
[203128%2F9134614%2Fmceclip0]
 
Muchas Gracias al equipo de OPEN PLC, por la plataforma OpenSource!!, espero aportar con mayor información para la mejora continua del entorno.
"Las formas de programación enriquecen la experiencia"
Reply 0 0
alanibbett
Thanks for this discussion it has been super helpful to me. I have used global with an arduino extension and they work really well. In addition to this I have developed a small driver for my own hardware  which also works but I’d like to use globals in the driver code to indicate to the ladder logic what devices my driver has detected. Is there a syntax that allows me to declare a global in the c++ code at the driver level that can be referenced by any code that uses that driver? I hope this makes sense.
thanks in advance
Alan
Reply 0 0
Reply