Jump to content

leikang

Staff group
  • Content Count

    97
  • Joined

  • Last visited

Everything posted by leikang

  1. Grundlagen des Kontaktplans in der SPS-Programmierung Kontaktplanlogik war ursprünglich eine schriftliche Methode zur Dokumentation des Entwurfs und der Konstruktion von Relaisgestellen, wie sie in der Fertigung und Prozesssteuerung verwendet werden. Jedes Gerät im Relaisgestell wurde im Kontaktplan durch ein Symbol dargestellt, wobei die Verbindungen zwischen diesen Geräten angezeigt wurden. Darüber hinaus wurden auch andere externe Elemente des Relaisgestells wie Pumpen, Heizungen usw. im Kontaktplan angezeigt. Kontaktplanlogik hat sich zu einer Programmiersprache entwickelt, die ein Programm durch ein grafisches Diagramm darstellt, das auf den Schaltplänen der Relaislogik-Hardware basiert. Kontaktplanlogik wird zur Entwicklung von Software für speicherprogrammierbare Steuerungen (SPS) verwendet, die in industriellen Steuerungsanwendungen verwendet werden. Der Name basiert auf der Beobachtung, dass Programme in dieser Sprache Leitern ähneln, mit zwei vertikalen Schienen und einer Reihe horizontaler Sprossen dazwischen. Während Kontaktplandiagramme früher die einzige verfügbare Notation zum Aufzeichnen von speicherprogrammierbaren Steuerungsprogrammen waren, sind heute andere Formen in IEC 61131-3 standardisiert. Kontaktplanlogik wird häufig zum Programmieren von SPSen verwendet, wenn eine sequentielle Steuerung eines Prozesses oder Fertigungsvorgangs erforderlich ist. Kontaktplanlogik ist für einfache, aber kritische Steuerungssysteme nützlich. Da speicherprogrammierbare Steuerungen immer ausgefeilter wurden, wurde sie auch in sehr komplexen Automatisierungssystemen verwendet. Häufig wird das Kontaktplanlogikprogramm in Verbindung mit einem HMI-Programm verwendet, das auf einer Computerarbeitsstation ausgeführt wird. Beispiel eines einfachen Kontaktplanlogikprogramms Die Sprache selbst kann als eine Reihe von Verbindungen zwischen logischen Prüfern (Kontakten) und Aktoren (Spulen) betrachtet werden. Wenn ein Pfad zwischen der linken Seite der Sprosse und dem Ausgang durch aktivierte (wahre oder „geschlossene“) Kontakte verfolgt werden kann, ist die Sprosse wahr und das Speicherbit der Ausgangsspule ist aktiviert oder wahr. Wenn kein Pfad verfolgt werden kann, ist der Ausgang falsch (0) und die „Spule“ wird analog zu elektromechanischen Relais als „stromlos“ betrachtet. Die Kontaktplanlogik verfügt über Kontakte, die Schaltkreise zur Steuerung von Spulen schließen oder unterbrechen. Jede Spule oder jeder Kontakt entspricht dem Status eines einzelnen Bits im Speicher des programmierbaren Controllers. Im Gegensatz zu elektromechanischen Relais kann ein Kontaktplanprogramm beliebig oft auf den Status eines einzelnen Bits verweisen, was einem Relais mit einer unendlich großen Anzahl von Kontakten entspricht. Sogenannte „Kontakte“ können sich auf physische („harte“) Eingaben an den programmierbaren Controller von physischen Geräten wie Drucktasten und Endschaltern über ein integriertes oder externes Eingabemodul beziehen oder den Status interner Speicherbits darstellen, die an anderer Stelle im Programm generiert werden können. Jede Sprosse der Kontaktplansprache verfügt normalerweise über eine Spule ganz rechts. Einige Hersteller erlauben möglicherweise mehr als eine Ausgangsspule auf einer Sprosse. —( )— Eine normale Spule, die immer dann aktiviert wird, wenn ihre Sprosse geschlossen ist. —()— Eine „Nicht“-Spule, die immer dann aktiviert wird, wenn ihre Sprosse geöffnet ist. —[ ]— Ein normaler Kontakt, der immer dann geschlossen wird, wenn seine entsprechende Spule oder ein Eingang, der sie steuert, aktiviert wird. —[]— Ein „Nicht“-Kontakt, der geschlossen wird, wenn die entsprechende Spule oder ein Eingang, der sie steuert, nicht aktiviert ist. Die „Spule“ (Ausgang einer Sprosse) kann einen physischen Ausgang darstellen, der ein an den programmierbaren Controller angeschlossenes Gerät steuert, oder ein internes Speicherbit zur Verwendung an anderer Stelle im Programm. Logisches UND ------[ ]--------------[ ]----------------( ) Schlüsselschalter 1 Schlüsselschalter 2 Türmotor Das Obige realisiert die Funktion: Türmotor = Schlüsselschalter 1 UND Schlüsselschalter 2 Diese Schaltung zeigt zwei Schlüsselschalter, die Sicherheitspersonal verwenden könnte, um einen Elektromotor an einer Banktresortür zu aktivieren. Wenn die normalerweise offenen Kontakte beider Schalter geschlossen werden, kann Strom zum Motor fließen, der die Tür öffnet. Logisches UND mit NICHT ------[ ]--------------[]----------------( ) Tür schließen Hindernis Türmotor Das Obige realisiert die Funktion: Türmotor = Tür schließen UND NICHT (Hindernis). Diese Schaltung zeigt einen Druckknopf, der eine Tür schließt, und einen Hindernisdetektor, der erkennt, ob sich etwas im Weg der sich schließenden Tür befindet. Wenn der normalerweise offene Druckknopfkontakt schließt und der normalerweise geschlossene Hindernisdetektor geschlossen ist (kein Hindernis erkannt), kann Strom zum Motor fließen, der die Tür schließt. Logisches ODER --+-------[ ]-------+-----------------( ) | Äußeres Entriegeln | Entriegeln | | +-------[ ]-------+ Inneres Entriegeln Das Obige realisiert die Funktion: Entriegeln = Inneres Entriegeln ODER Äußeres Entriegeln Diese Schaltung zeigt die beiden Dinge, die die elektrischen Türschlösser eines Autos auslösen können. Der Fernbedienungsempfänger wird immer mit Strom versorgt. Der Schlossmagnet wird mit Strom versorgt, wenn einer der beiden Kontaktsätze geschlossen ist. Industrielles STOP/START In der üblichen industriellen Start-/Stopp-Verriegelungslogik haben wir eine „Start“-Taste zum Einschalten eines Motorschütz und eine „Stopp“-Taste zum Ausschalten des Schützes. Wenn die „Start“-Taste gedrückt wird, wird der Eingang über den Öffnerkontakt der „Stopp“-Taste wahr. Wenn der „Run“-Eingang wahr wird, schließt der versiegelte „Run“-Schließerkontakt parallel zum „Start“-Schließerkontakt und hält die Eingangslogik wahr (verriegelt oder versiegelt). Nachdem der Schaltkreis verriegelt wurde, kann die „Stopp“-Taste gedrückt werden, wodurch sich sein Öffnerkontakt öffnet und folglich der Eingang falsch wird. Der „Run“-Schließerkontakt öffnet sich dann und die Schaltkreislogik kehrt in ihren Ruhezustand zurück. --+----[ ]--+----[]----( ) | Start | Stopp Lauf | | +----[ ]--+ laufen -------[ ]--------------( ) Motor laufen lassen Das Obige realisiert die Funktion: laufen = (Start ODER laufen) UND (NICHT Stopp) Beachten Sie die Verwendung von Klammern, um die logische ODER-Funktion zu gruppieren, bevor die logische UND-Funktion ausgewertet wird (die eine höhere Betriebspriorität hat). Beachten Sie auch die Verwendung von NICHT, um die „Stopp“-NC-Kontaktlogik darzustellen. Diese Verriegelungskonfiguration ist eine gängige Redewendung in der Kontaktplanlogik. In der Kontaktplanlogik wird sie als Seal-In-Logik bezeichnet. Der Schlüssel zum Verständnis der Verriegelung liegt in der Erkenntnis, dass der „Start“-Schalter ein Momentschalter ist (sobald der Benutzer die Taste loslässt, ist der Schalter wieder geöffnet). Sobald der „Lauf“-Magnetschalter einrastet, schließt er den „Lauf“-NO-Kontakt, der den Magnetschalter einrastet. Das Öffnen des „Start“-Schalters hat dann keine Wirkung. Aus Sicherheitsgründen sollte ein Not-Aus und/oder Stopp in Reihe mit dem Startschalter fest verdrahtet sein, und die Relaislogik sollte dies widerspiegeln. --[]----[]----+--[ ]--+---------( ) ES Stop | Start | Motor | | +--[ ]--+ Run Komplexe Logik Hier ist ein Beispiel dafür, wie zwei Sprossen in einem Leiterlogikprogramm aussehen könnten. In realen Anwendungen kann es Hunderte oder Tausende von Sprossen geben. Normalerweise wird komplexe Leiterlogik von links nach rechts und von oben nach unten „gelesen“. Wenn jede der Linien (oder Sprossen) ausgewertet wird, kann die Ausgangsspule einer Sprosse als Eingang in die nächste Stufe der Leiter einspeisen. In einem komplexen System gibt es viele „Sprossen“ auf einer Leiter, die in der Reihenfolge der Auswertung nummeriert sind. 1. ----[ ]---------+----[ ]-----+----( ) Schalter | HiTemp | A/C | | +----[ ]-----+ Feucht 2. ----[ ]----[]--------------------( ) A/C Heizen Kühlen Zeile 1 realisiert die Funktion: A/C = Schalter UND ( HiTemp ODER Feucht ) Zeile 2 realisiert die Funktion: Kühlen = A/C UND ( NICHT Heizen ) Dies stellt ein etwas komplexeres System für Sprosse 2 dar. Nachdem die erste Zeile ausgewertet wurde, wird die Ausgangsspule „A/C“ in Sprosse 2 eingespeist, die dann ausgewertet wird, und die Ausgangsspule „Kühlen“ könnte in ein Ausgangsgerät „Kompressor“ oder in Sprosse 3 auf der Leiter eingespeist werden. Dieses System ermöglicht die Aufschlüsselung und Auswertung sehr komplexer Logikdesigns. Zusätzliche Funktionalität Zusätzliche Funktionalität kann einer Leiterlogikimplementierung vom SPS-Hersteller als spezieller Block hinzugefügt werden. Wenn der spezielle Block eingeschaltet wird, führt er Code für vorgegebene Argumente aus. Diese Argumente können innerhalb des speziellen Blocks angezeigt werden. +-------+ -----[ ]--------------------+ A +---- Fernentriegelung +-------+ Fernzähler +-------+ -----[ ]--------------------+ B +---- Innenentriegelung +-------+ Innenzähler +--------+ --------------------+ A + B +----------- | in C | +--------+ Addierer In diesem Beispiel zählt das System, wie oft die Innen- und Fernentriegelungstasten gedrückt werden. Diese Informationen werden in den Speicherplätzen A und B gespeichert. Speicherplatz C enthält die Gesamtzahl der elektronischen Türentriegelungen. SPS haben viele Arten von Spezialblöcken. Dazu gehören Timer, Rechenoperatoren und Vergleiche, Tabellennachschlagevorgänge, Textverarbeitung, PID-Steuerung und Filterfunktionen. Leistungsstärkere SPS können auf einer Gruppe interner Speicherplätze arbeiten und eine Operation auf einem Adressbereich ausführen, um beispielsweise einen physischen sequentiellen Trommelregler oder eine Finite-State-Maschine zu simulieren. In einigen Fällen können Benutzer ihre eigenen Spezialblöcke definieren, die eigentlich Unterprogramme oder Makros sind. Die große Bibliothek an Spezialblöcken und die schnelle Ausführung haben die Verwendung von SPSen zur Implementierung sehr komplexer Automatisierungssysteme ermöglicht.
  2. Este artículo trata sobre el método de resolución de problemas de programación de PLC. En los PLC industriales donde se utilizan miles de entradas y salidas, sabemos la duración de los programas de PLC, depende de la aplicación o el uso de la planta. Solucionar problemas de programas de PLC Siemens Algunas veces, las personas pueden cambiar los parámetros lógicos sin saberlo y esto puede provocar una falla. Incluso se crean algunas fallas durante la etapa de diseño lógico debido a la complejidad del diseño. El software siemens plc tiene diferentes herramientas útiles disponibles para solucionar las fallas generadas en los programas. Las fallas pueden ser como superposición de direcciones, múltiples instancias de salida iguales, superposición de direcciones de bits de memoria, muchas veces se usa un solo programa para trabajar una y otra vez, etc. Para descubrir estos problemas, hay cuatro tipos de ventanas disponibles en el software de Siemens que nos ayudarán a solucionar los problemas. Ellos son: Referencia cruzada Estructura de llamada Lista de tareas Estructura de dependencia Analicemos cómo usarlos en nuestro programa para solucionar problemas y dónde encontrarlos en el software. Referencia cruzada La referencia cruzada se utiliza para encontrar todas las entradas y salidas digitales y analógicas utilizadas en la lógica. Nos ayudará a saber la cantidad de veces que se utilizan las E/S en el programa y también llevará a los usuarios directamente a la ubicación específica de las E/S en las páginas lógicas. A continuación se muestra un ejemplo de uno de los programas, en el que puede ver cómo se ve la tabla de referencias cruzadas. Contiene toda la información como direccionamiento, idioma del programa, entradas y salidas utilizadas, etc. Estructura de llamada Cuando desee saber qué bloque se utiliza en la programación, se utiliza la estructura de llamada. Esta es una función inversa de referencia cruzada en la que llegamos a saber cuántas veces se usan SFC y bloques FB en OB (Bloque de organización) y aquí llegamos a saber cuántas veces se usan OB en SFC y FB. Lista de tareas La lista de asignaciones es una característica muy útil a la hora de saber cuántas entradas, salidas, temporizadores y contadores utilizamos en nuestra aplicación y cuántos de ellos aún quedan, para poder utilizarlos en futuras lógicas. Estructura de dependencia La estructura de dependencia se utiliza para mostrar dónde se utilizan todos y cada uno de los bloques dentro de la programación. Pero en el paso 7 no lo llevará directamente a la ubicación; sin embargo, en TIA PORTAL lo llevará a la ubicación donde está escrito el programa. NOTA: Para abrir estas ventanas en el paso 7, use la información como se muestra en Dibujo. Después de hacer clic en mostrar tienes las opciones. En TIA PORTAL, siga el siguiente paso que se muestra en el dibujo.
  3. En esta publicación, daré algunas instrucciones básicas que provienen de mi experiencia personal para brindarle una guía sobre cómo es la resolución de problemas en sistemas de automatización (PLC/DCS): La resolución de problemas de los sistemas de automatización tiene en general la misma táctica para encontrar la solución a la falla del sistema. Sin embargo, dependiendo de la complejidad y el tamaño de la aplicación y del sistema de automatización específico, los pasos para la solución de problemas serían un poco diferentes o más complicados. El mejor conocimiento se obtiene mediante la práctica y las condiciones reales de resolución de problemas. Practicar una y otra vez es la solución en mi opinión. ¡¡Cualquier suplemento y comentario es bienvenido!! Solucionar problemas de un sistema PLC Antes de continuar, aceptamos que los sistemas de automatización modernos tienen PLC para controlar la aplicación. Si tenemos una aplicación pequeña entonces el sistema posiblemente tenga un microPLC (o nanoPLC) u otro tipo de controlador compacto (muchas veces esto depende de la aplicación). Dije sistemas de automatización modernos porque en el pasado (antes de que los PLC y otros controladores compactos fueran conocidos y utilizados por las empresas de desarrollo de automatización), el control de un sistema de automatización se realizaba únicamente con relés. Investigar el programa del controlador Lo primero que debemos hacer es averiguar si cumplimos las condiciones adecuadas para la operación que está defectuosa. Para ello debemos encontrar la “mente” de nuestro sistema. Esta “mente” es el controlador (ya sea una especie de PLC u otro tipo de controlador compacto). Si no cumplimos con las condiciones adecuadas, entonces debemos investigar el programa del controlador para averiguar el origen del problema (SIEMPRE revise que aparezcan mensajes en SCADA. Esto guiará más rápido a la solución porque en SCADA aparece información importante como falla /descripción de alarma o una dirección específica en el PLC). Lo que descubriremos es... ya sea una señal defectuosa del hardware (por ejemplo, una señal digital de un botón o una señal digital de un interruptor mecánico o una señal digital de un contacto de relé que "no llega" a la entrada del controlador o una señal analógica que tiene valores incorrectos) o una señal defectuosa de otro sistema de software (por ejemplo, SCADA). Investigar las condiciones que surgieron del hardware. Cuando concluimos sobre el origen del problema, entonces dejamos por un momento el programa del controlador y salimos a comprobar nuestras conclusiones. Ya deberíamos haber encontrado los dibujos del sistema de automatización para poder ver las conexiones de los componentes que queremos comprobar. Por ejemplo, si descubrimos que tenemos una señal digital de un botón que “no llega” a la entrada del controlador, entonces tomamos nuestro multímetro y vamos a revisar el botón. Si el botón está bien, investigamos si hay algún fusible entre el botón y la entrada del controlador. Si lo hay, lo comprobamos. Si el fusible está bien, entonces investigamos el recorrido del cable. Quizás tengamos un cable cortado. Si el cable está bien, entonces quizás tengamos un problema de hardware en la entrada del controlador y quizás debamos cambiar este módulo de entrada por uno nuevo o arreglarlo (las reparaciones deben ser realizadas por personal calificado). Investigar el hardware tras las salidas de nuestro controlador. Si concluimos que estamos en las condiciones adecuadas, entonces debemos revisar los componentes que tenemos entre el controlador y el equipo defectuoso (nos referimos al equipo que no funciona como debería). Por ejemplo, si tenemos un horno industrial que no cierra la puerta (aunque tengamos las condiciones para cerrar la puerta desde el programa), tal vez tengamos un relé defectuoso que se energiza desde el PLC (u otro controlador) para cerrar la puerta. Si el relé está bien, entonces quizás tengamos problema con el motor que se encarga de cerrar la puerta. Debemos verificar el estado del motor (bobinas del motor, piezas mecánicas) Si el motor está bien, debemos verificar los valores de voltaje que llegan a la entrada del motor (con nuestro multímetro) y también verificar el estado del cable si las medidas del multímetro no son correctas. Si el voltaje y el cable están bien, entonces tal vez tengamos un atasco en algún lugar de la construcción de la puerta del horno. ¡Las unidades de potencia son una “ventaja”! Generalmente, cuando tenemos unidades de potencia (variadores) en nuestro sistema de automatización para accionar un motor, entonces debemos tener juntos el manual de la unidad de potencia específica. Esto se debe a que las unidades de potencia cuentan con un display digital o displays LED de 7 segmentos o simples LEd’s para informarnos sobre la falla que existe en su interior o en el motor accionado. Esto es muy útil para ingenieros y técnicos. Además, las unidades de potencia modernas tienen algoritmos especiales para verificar el estado del motor, los valores de voltaje y corriente, etc. Por ejemplo, si un motor se sobrecalienta, el variador nos informará de ello porque verifica continuamente el sensor de temperatura (por ejemplo, el termistor) que se encuentra dentro de la carcasa del motor. Luego debemos revisar el motor si realmente está sobrecalentado o tenemos algún sensor de temperatura defectuoso que debemos reemplazar. Verificar el estado de los controladores Algunas veces, cuando la CPU de nuestro PLC detecta una condición inaceptable en el flujo del programa, entonces pasa al modo “STOP” y posiblemente un led parpadea indicando este mal funcionamiento. Además, si ocurre algún otro mal funcionamiento en el sistema, algunos LED indican el tipo de falla (consulte el manual del controlador para obtener más información). El mismo comportamiento tiene en general cualquier tipo de controlador que se establezca en un sistema de automatización. Sistemas de seguridad Muchos sistemas de automatización (a menudo máquinas de producción) tienen en su diseño algunos "sistemas de seguridad" como "Pilz" o "Siemens Sirius". Se trata de controladores compactos e inteligentes para controlar situaciones como la apertura de puertas protectoras o la parada de emergencia. Cuando ocurre algo de esto, el sistema de seguridad detiene el funcionamiento del sistema de automatización para protección de personas y máquinas. Para restablecer el sistema de automatización al estado funcional, existen instrucciones especiales en los manuales de los sistemas de seguridad. La conclusión de todo lo anterior es tener una táctica paso a paso para la resolución de problemas. Con el paso del tiempo y adquiriendo más experiencia, quizás nos saltemos algunos pasos, sobre todo si somos el personal responsable del mantenimiento de un sistema con el que nos topamos a diario. Sin embargo, una buena táctica es ser organizado y paciente. ¡Buena suerte con tus esfuerzos!
  4. En este post entenderemos cómo filtrar entradas digitales y analógicas en un PLC. Como dice el tema, el filtrado es un medio para eliminar picos no deseados en las señales recibidas en el PLC. Su función es eliminar las fluctuaciones y pasar sólo los cambios de señal adecuados en un momento determinado al PLC. Dentro de un PLC, el circuito de filtro viene primero y luego viene el circuito de procesamiento de entrada del PLC, que acepta la entrada filtrada final y la utiliza para su lógica. Filtros de entrada digital PLC Consideremos primero la entrada digital. La función de la entrada con un filtro es aceptar una entrada de campo digital y pasarla a un circuito de procesamiento a través del filtro. Si ve la imagen de abajo, hay dos partes. En primer lugar, el círculo verde indica que se aprobará el cambio de entrada y el círculo rojo muestra que no se aprobará el cambio de entrada. En la primera parte (arriba), hay dos cambios en los que hay muchas fluctuaciones y los cambios de entrada se omitirán. Hay dos cambios en los que no hay fluctuaciones y ese cambio de entrada se pasará al circuito de procesamiento. Lo mismo es la teoría con la segunda parte (abajo). Esto es posible filtrando. El filtrado se define por un factor o tiempo. Supongamos que establece un tiempo de 3 ms. La función del filtro es aceptar solo el cambio de entrada que se mantiene por encima de 3 ms. Si la entrada cambia antes de 3 ms, esa entrada no se considerará y se ignorará. Esto significa que se desprecian los impulsos perturbadores cortos y de alta frecuencia. Esta lógica es la misma que la del temporizador antirrebote que escribimos en la lógica del PLC. En la imagen de abajo, la lámpara se encenderá solo cuando la entrada del botón de inicio permanezca alta durante 3 segundos. Esta es la misma lógica utilizada en un filtro de paso digital. Pasará el cambio de entrada a la parte de procesamiento solo cuando esa entrada mantenga un estado (alto o bajo) durante el tiempo establecido. Además del tiempo, como comentamos, algunos PLC tienen la opción de configurar un factor en lugar del tiempo. El factor calcula el tiempo interno y decide el nivel de filtrado. Cuanto mayor sea el valor del factor, mayor será el poder de filtrado. Filtros de entrada analógica PLC Ahora veamos el filtrado en entradas analógicas. Como las entradas analógicas son de naturaleza variable, la lógica de filtro para ellas no se puede implementar de la misma manera que para las entradas digitales. Entonces, en las entradas analógicas, se utiliza la lógica de promedio. El filtro promediará los valores alcanzados en un tiempo determinado y dará un valor final promedio para ese tiempo. Consulte la imagen a continuación para ver el estudio. El primero: el color azul tiene un factor de 1. El segundo, el color verde, tiene un factor de 2. El tercero: el color naranja tiene un factor de 3. El cuarto: el color marrón tiene un factor de 4. A medida que aumenta el valor del factor de filtro, puede ver que la forma de la señal mejora al filtrar la señal a un valor más nítido. En un tiempo determinado, el filtro promediará los valores que obtiene de la entrada; y, según las fórmulas utilizadas en él, dará el resultado promedio final por tiempo. Entonces, a medida que aumenta el factor de filtro o ponderación, obtenemos un valor más fino de una señal analógica con menos interferencia. Normalmente se utiliza para este fin un filtro de primer paso. De esta manera, concluimos que el filtrado es de gran utilidad para reducir el ruido no deseado de la entrada de campo y pasar valores adecuados, que también protegerán el circuito de entrada del PLC de daños; si se producen picos altos o no deseados.
  5. leikang

    Arquitectura DCS versus PLC

    La principal diferencia entre DCS y PLC es el modelo de negocio que analizamos comparando la arquitectura DCS versus PLC. Arquitectura DCS versus PLC Se puede decir que el modelo de negocio DCS se basa en un sistema integrado monolítico de un solo fabricante. Arquitectura DCS Para un DCS, el controlador, el subsistema de E/S, el software del servidor de base de datos, el software de ingeniería y el software del operador son todos una única unidad monolítica diseñada en conjunto y solo funcionan entre sí. No es posible utilizar componentes de terceros. No es posible utilizar ninguno de estos componentes en ningún otro sistema. Un DCS utiliza una red de subsistema de E/S y una red de control basada en Ethernet estándar, pero con un protocolo de aplicación propietario y, por lo general, solo con un modelo particular aprobado de conmutadores Ethernet. Figura 1 En un DCS todos los componentes provienen del mismo fabricante Solo se permite una versión específica de Windows y solo en un tipo de computadora aprobada enviada por el fabricante del DCS. Estas restricciones permiten al fabricante de DCS probar todo en conjunto de manera muy exhaustiva, a gran escala, con mucha carga y con muchos controladores y estaciones de trabajo. También se prueban juntas aplicaciones como control de lotes, control avanzado y ajuste automático, etc. Esto garantiza que no haya conflictos de compatibilidad ni dependencias imprevistas. Es posible realizar pruebas exhaustivas a gran escala porque básicamente hay un solo tipo de cada componente, por lo que solo hay una o muy pocas combinaciones. El software de terceros solo está permitido en “estaciones de aplicaciones” separadas donde no puede entrar en conflicto con las aplicaciones nativas del DCS y debe ser probado y aprobado por el fabricante del DCS; en la lista blanca. Un DCS es monolítico y utiliza el mismo subsistema de E/S, controlador y software de la misma marca, y una única plataforma de computadora y sistema operativo. Esto ha sido probado exhaustivamente a muy gran escala. Soporte a largo plazo de DCS Los sistemas suelen permanecer operativos durante 15 años o más. Durante este tiempo, habrá varias versiones de Windows, paquetes de servicio, revisiones, muchas actualizaciones de definiciones de virus y también será necesario reemplazar el hardware de la computadora. Por lo general, DCS solo admite un único tipo de software antivirus y cada vez que hay una nueva definición de virus o cuando hay un paquete de servicio o revisión del sistema operativo Windows, el sistema prueba nuevamente todo el conjunto monolítico de todo el hardware y software. proveedor antes del lanzamiento, lo que garantiza que la definición de virus y el paquete de servicio se puedan implementar sin conflictos de compatibilidad. Actualización del DCS Las versiones de DCS también se actualizan como una única unidad monolítica de todo el hardware y software, como el firmware de la tarjeta de E/S, el firmware del controlador, el software del servidor, el software de la estación de ingeniería, el software de la estación del operador y cualquier otro software, todos se actualizan juntos. Cada vez que hay una nueva versión del sistema, el fabricante del sistema ha probado minuciosamente todos estos componentes juntos a gran escala para garantizar que todos sean compatibles entre sí. Además, el proceso de transferencia directa en línea de la versión anterior a la nueva versión se ha probado minuciosamente a gran escala, lo que garantiza una implementación sin problemas en el sitio. Es esta tranquilidad que proporcionan las pruebas exhaustivas y a gran escala lo que hace que el DCS sea muy popular en grandes instalaciones como complejos petroquímicos. Estas pruebas resultan prácticas gracias a las pocas combinaciones en un sistema monolítico. Arquitectura PLC / Modelo de Negocio Se puede decir que el modelo de negocio de PLC se basa en una arquitectura flexible realizada por un integrador de sistemas (SI). Arquitectura PLC La arquitectura del PLC es muy flexible y cada componente se puede seleccionar libremente entre cualquiera de los muchos proveedores. El PLC es la CPU con software de configuración y subsistema IO. A veces, el subsistema de E/S puede provenir de un tercero. Incluso las tarjetas de E/S que se conectan al backplane pueden provenir de terceros. El software HMI suele ser de terceros. Normalmente es mejor un servidor OPC nativo del fabricante del PLC, pero a veces se utilizan servidores OPC de terceros. Figura 2 Para un PLC se integran componentes de diferentes fabricantes Básicamente, cualquier PLC funciona con cualquier subsistema de E/S, servidor OPC y software HMI porque se utilizan protocolos estándar como PROFIBUS-DP, PROFINET, Modbus/RTU, Modbus/TCP, DeviceNet y EtherNet/IP, así como OPC, etc. . El equipo de red, las computadoras y la versión de Windows se pueden seleccionar libremente. Algunos componentes que no funcionan están en la lista negra. Figura 3 DCS utiliza un único proveedor, mientras que las soluciones PLC combinan varios proveedores, lo que genera una gran cantidad de combinaciones. Nota: Actualmente también está disponible un proveedor de paquete de PLC único Esta flexibilidad permite cientos de combinaciones de hardware y software, lo que hace imposible que estos fabricantes se reúnan para probar todas las combinaciones posibles de su hardware y software en cada versión de Windows antes de que una planta decida comprar. Los fabricantes involucrados pueden probar algunas combinaciones, pero pueden o no ser a gran escala con cargas pesadas. Un PLC permite cualquier combinación de subsistema de E/S, CPU y software HMI/SCADA, en una amplia variedad de plataformas informáticas y de sistemas operativos. No se pueden probar todas las combinaciones. El fabricante de PLC puede suministrar todos los componentes de hardware y software, todos del mismo fabricante, ya que muchos fabricantes de PLC han adquirido empresas de HMI. Si es así, es posible que esta combinación en particular haya sido probada más exhaustivamente que las otras combinaciones probadas. Las aplicaciones auxiliares de terceros, como control de lotes, control avanzado y autoajuste, etc., generalmente no se prueban juntas, ya que dan como resultado un número aún mayor de combinaciones. PLC utiliza software de configuración propietario al igual que DCS. Es decir, no puede utilizar software de configuración de terceros para su PLC, al igual que un DCS. Un servidor OPC nativo para el PLC es mejor que un servidor OPC de terceros porque el software de configuración del PLC generalmente configura automáticamente el espacio de direcciones para el servidor OPC. Soporte a largo plazo para PLC Durante los 15 años o más de funcionamiento típico del sistema, habrá varias versiones de Windows, paquetes de servicio, revisiones, muchas actualizaciones de definiciones de virus y también será necesario reemplazar el hardware de la computadora. Normalmente, los PLC no tienen restricciones en cuanto al software antivirus o la versión del sistema operativo Windows, por lo que nuevamente el número de combinaciones de definiciones de virus, paquetes de servicios y revisiones se vuelve demasiado amplio y poco práctico para que estos fabricantes se reúnan para probar cada nueva combinación posible antes de una implementación en plantas para garantizar que no habrá conflictos de compatibilidad cuando se implemente en una gran cantidad de combinaciones de hardware y software. El fabricante del PLC puede limitar a un único software antivirus y versión de Windows. Si es así, es posible que esta combinación en particular haya sido probada más exhaustivamente que las otras combinaciones que prueban. Actualización de PLC Para un PLC, los componentes de hardware y software se actualizan individualmente. Es decir, el firmware del subsistema de E/S, el firmware de la CPU y el software de configuración, el servidor OPC, el software HMI y cualquier otro software se actualizan de forma independiente entre sí. Teniendo en cuenta diferentes versiones para cada opción de componentes, el número de combinaciones aumenta en órdenes de magnitud. Esta flexibilidad hace que no sea práctico que estos fabricantes se reúnan para probar todas las combinaciones posibles de nuevas versiones antes de su implementación en las plantas. Probar la transferencia en caliente de una combinación de versiones a otra combinación de versiones se vuelve casi imposible. El fabricante del PLC puede suministrar todos los componentes de hardware y software, limitarse a un único software antivirus y una versión de Windows que se prueban antes de la implementación, y limitarse a un único controlador de servidor de base de datos de subsistema de E/S/estación de operador de PLC/HMI, DCS, sistema PLC. actualizaciones de versiones amplias y pruebe la transferencia directa antes de la implementación. De esta forma se abandonaría la flexibilidad del PLC para alcanzar la robustez de un DCS.
  6. Cuando trabaja en un sistema de automatización industrial para la programación de PLC, tiene requisitos en los que necesita controlar un proceso de forma gradual o paso a paso. Algoritmos de control No puedes simplemente activar o desactivar una lógica para realizar tu trabajo. Puede tener efectos adversos en la salida real de su PLC. Por esta razón, existen varios tipos de métodos de control disponibles en un programa de PLC para realizar las acciones adecuadas. En esta publicación, veremos los diversos métodos de algoritmos de control que se utilizan en un programa de PLC. Control PID Este es, con diferencia, el método de control más famoso. PID utiliza un mecanismo de control de circuito cerrado. Esto significa que primero recibirá la retroalimentación y, según lo que desee, variará la salida en consecuencia. Para ello, el controlador PID utiliza cálculos matemáticos internos con tres parámetros: proporción, integral y derivada. Entonces, si desea controlar una enfriadora con un compresor, entonces el PLC controlará la salida del compresor midiendo primero la temperatura real y verificándola con la cantidad que requiere el usuario. En función de esa diferencia cada vez, la salida del compresor se controlará gradualmente o se encenderá y apagará para mantener la temperatura. Para ello se utilizará un bloque PID en el programa del PLC para realizar esta tarea. Generador de funciones Este es un tipo de método de control muy simple. En el generador de funciones, debe definir una tabla de entrada de n valores. De manera similar, defina una tabla de salida de n valores. Entonces, por ejemplo, si definimos 10 tablas de valores tanto en el lado de entrada como en el de salida, tenemos un elemento de 10 tamaños. Ahora bien, estos 10 elementos tendrán valores diferentes. Si configura 0-100 en el lado de entrada, entonces habremos configurado 0-50 en el lado de salida. Estos 10 elementos son 10 rangos, es decir, 0-10, 10-20, 20-30, etc. En consecuencia, el lado de salida se distribuirá en 10 elementos de 0 a 5, 5 a 10, 10 a 15 y así sucesivamente hasta 50. Cuando una entrada en tiempo real se encuentra entre cualquier valor en el lado de entrada, la salida escalada correspondiente será aprobado. Aquí tiene total flexibilidad para configurar los valores de la tabla de entrada y salida. Control de lógica difusa La lógica difusa es un método relativamente bueno para controlar una salida. Normalmente, tiene dos estados binarios: 0 y 1. Entonces, consideremos si una válvula se puede abrir o cerrar. ¿Pero qué pasa si la válvula se atasca en el medio? No sabemos si la válvula está cerca del estado abierto o cerrado. En ese caso, ayuda si existe un estado entre 0 y 1. Esto ayuda al menos a acercarse a una posibilidad. A esto se le llama lógica quisquillosa. Aquí puedes definir valores cercanos a 0 y 1. Puede ser como 0,9 o 0,2. En consecuencia, puede controlar las salidas cuando se acerque a estos valores. Y cuando alcanza el límite extremo, es decir 0 o 1, puedes abrir o cerrar completamente la válvula. Antes de eso, puedes operar las válvulas gradualmente. Esto aporta un control más preciso al proceso. Entonces, este bloque de control permite una colección de valores que pueden resultar útiles en situaciones impredecibles. Se requiere mucho conocimiento y experiencia para establecer correctamente los valores y conjuntos para que la lógica funcione correctamente. Posición proporcional Esta lógica abrirá o cerrará un dispositivo pulsando los contactos para abrir o cerrar en algún temporizador predefinido establecido por el usuario. Se realiza para un ancho de pulso proporcional a la desviación entre la posición requerida y la posición actual. Debe configurar parámetros de control como cuánto mínimo y máximo limitar la salida, cuánto tiempo permanecerá encendida la salida, la velocidad a la que el dispositivo debe abrirse o cerrarse en %/segundo, etc. El bloque de funciones recibe retroalimentación real, evalúa los temporizadores internos y verifica si la apertura o el cierre se realizan dentro de la velocidad deseada o no. En caso contrario se dará el correspondiente pulso de apertura o cierre. De esta forma, vimos los diversos métodos de algoritmos de control utilizados en la programación de PLC.
  7. Los objetos más elementales en la programación del diagrama de escalera son los contactos y las bobinas, destinados a imitar los contactos y las bobinas de los relés electromecánicos. Los contactos y las bobinas son elementos de programación discretos que tratan con estados variables booleanos (1 y 0; encendido y apagado; verdadero y falso). Cada contacto en un programa PLC de Diagrama de Escalera representa la lectura de un solo bit en la memoria, mientras que cada bobina representa la escritura de un solo bit en la memoria. Las señales de entrada discretas al PLC desde interruptores del mundo real se leen mediante un programa de diagrama de escalera mediante contactos referenciados a esos canales de entrada. En los sistemas PLC heredados, cada canal de entrada discreta tiene una dirección específica que debe aplicarse a los contactos dentro de ese programa. En los sistemas PLC modernos, cada canal de entrada discreta tiene un nombre de etiqueta creado por el programador que se aplica a los contactos dentro del programa. De manera similar, los canales de salida discretos, a los que se hace referencia mediante símbolos de bobina en el diagrama de escalera, también deben llevar algún tipo de dirección o etiqueta con el nombre de la etiqueta. Para ilustrar, imaginaremos la construcción y programación de un sistema de detección de llama redundante para monitorear el estado de la llama de un quemador utilizando tres sensores. El objetivo de este sistema será indicar un quemador “encendido” si al menos dos de los tres sensores indican llama. Si solo un sensor indica llama (o si ningún sensor indica llama), el sistema declarará que el quemador está apagado. El estado del quemador se indicará visiblemente mediante una lámpara que los operadores humanos podrán ver fácilmente dentro del área de la sala de control. El cableado de nuestro sistema se muestra en el siguiente diagrama: Cada sensor de llama emite una señal de voltaje CC que indica la detección de llama en el quemador, ya sea encendido (24 voltios CC) o apagado (0 voltios CC). Estas tres señales de voltaje CC discretas son detectadas por los primeros tres canales de la tarjeta de entrada discreta del PLC. La lámpara indicadora es una bombilla de 120 voltios y, por lo tanto, debe recibir alimentación de una tarjeta de salida discreta de CA, que se muestra aquí en la última ranura del PLC. Para que el programa de escalera sea más legible, asignaremos nombres de etiquetas (direcciones simbólicas) a cada bit de entrada y salida en el PLC, describiendo su dispositivo real en un formato fácil de interpretar. Etiquetaremos los primeros tres canales de entrada discretos como sensor de entrada A, sensor de entrada B y sensor de entrada C, y la salida como quemador de salida encendido. Aquí se muestra un programa en escalera para determinar si al menos dos de los tres sensores detectan llama, con los nombres de las etiquetas haciendo referencia a cada contacto y bobina: Los contactos conectados en serie en un diagrama de escalera realizan la función lógica Y, mientras que los contactos en paralelo realizan la función lógica O. Por lo tanto, este programa de detección de llamas dos de tres podría describirse verbalmente como: “El quemador se enciende si A y B, o B y C, o A y C” Una forma alternativa de expresar esto es usar la notación del álgebra booleana, donde la multiplicación representa la función Y y la suma representa la función O: Quemador_encendido = AB + BC + AC Otra forma más de representar esta relación lógica es utilizar símbolos de puerta lógica: Para ilustrar cómo funcionaría este programa, consideraremos un caso en el que los sensores de llama B y C detectan llama, pero el sensor A no (Nota 1). Esto representa dos de tres buenas condiciones, por lo que esperaríamos que el PLC encienda la luz indicadora de "Quemador encendido" según lo programado. Desde la perspectiva del rack del PLC, veríamos encendidos los LED indicadores de los sensores B y C en la tarjeta de entrada discreta, así como el LED indicador del canal de salida de la lámpara: Nota 1: La razón más probable por la que uno de cada dos sensores de llama no detecta la presencia de una llama es algún tipo de desalineación o suciedad del sensor de llama. De hecho, esta es una buena razón para utilizar un sistema de detección de llama 2 de 3 en lugar de un esquema de detector simple (1 de 1): hacer que el sistema sea más tolerante a problemas ocasionales con los sensores sin comprometer el funcionamiento del quemador. seguridad. Esos dos canales de entrada energizados "establecen" bits (estado 1) en la memoria del PLC que representan el estado de los sensores de llama B y C. El bit del sensor de llama A estará "borrado" (estado 0) porque su canal de entrada correspondiente está desenergizado. El hecho de que el LED del canal de salida esté energizado (y la lámpara indicadora de "Quemador encendido" esté energizada) nos indica que el programa del PLC ha "establecido" el bit correspondiente en el registro de memoria de salida del PLC al estado "1". Una pantalla de bits de registro de entrada y salida muestra los estados de "establecimiento" y "reinicio" del PLC en este momento: Al examinar el programa Diagrama de escalera con la indicación de estado habilitada, vemos cómo solo el par de contactos del medio pasa "potencia virtual" a la bobina de salida: Recuerde que el propósito de un contacto en un programa de PLC es leer el estado de un bit en la memoria del PLC. Estos seis “contactos virtuales” leen los tres bits de entrada correspondientes a los tres sensores de llama. Cada “contacto” normalmente abierto se “cerrará” cuando su bit correspondiente tenga un valor de 1, y se “abrirá” (pasará a su estado normal) cuando su bit correspondiente tenga un valor de 0. Así, vemos aquí que los dos contactos correspondientes al sensor A aparecen sin resaltar (no representando “conductividad” en el circuito del relé virtual) porque el bit de esa entrada está reseteado (0). Los dos contactos correspondientes al sensor B y los dos contactos correspondientes al sensor C aparecen resaltados (representando "conductividad" en el circuito virtual) porque sus bits están configurados (1). Recuerde también que el propósito de una bobina en un programa de PLC es escribir el estado de un bit en la memoria del PLC. Aquí, la bobina "energizada" establece el bit de la salida 0 del PLC en un estado "1", activando así la salida del mundo real y enviando energía eléctrica a la lámpara "Quemador encendido". Tenga en cuenta que el color resaltado no indica que un contacto virtual esté conduciendo energía virtual, sino simplemente que es capaz de conducir energía. Sin embargo, el color resaltado alrededor de una bobina virtual indica la presencia de "poder" virtual en esa bobina. Los contactos y relés no sólo son útiles para implementar funciones lógicas simples, sino que también pueden realizar funciones de enclavamiento. Una aplicación muy común de esto en sistemas PLC industriales es un programa de arranque/parada con enclavamiento para controlar motores eléctricos mediante interruptores de botón de contacto momentáneo. Como antes, esta funcionalidad se ilustrará mediante un circuito y programa de ejemplo hipotético: En este sistema, dos interruptores de botón están conectados a entradas discretas en un PLC, y el PLC, a su vez, energiza la bobina de un relé de contactor de motor por medio de una de sus salidas discretas. Un contacto de sobrecarga está cableado directamente en serie con la bobina del contactor para proporcionar protección contra sobrecorriente del motor, incluso en caso de una falla del PLC donde el canal de salida discreta permanece energizado (nota 2). El programa de escalera para este sistema de control de motores se vería así: Nota 2: Si bien es posible cablear el contacto de sobrecarga a uno de los canales de entrada discretos del PLC y luego programar un contacto de sobrecarga virtual en serie con la bobina de salida para detener el motor en caso de una sobrecarga térmica, esta estrategia dependería de que el PLC realice una función de seguridad que probablemente se realice mejor mediante circuitos cableados. Al presionar el botón "Inicio" se activa el canal de entrada discreta 6 en el PLC, que "cierra" el contacto virtual en el programa del PLC denominado IN switch Start. El contacto virtual normalmente cerrado para el canal de entrada 7 (el botón "Parar") ya está cerrado de forma predeterminada cuando no se presiona el botón "Parar", por lo que la bobina virtual recibirá "alimentación" cuando se presiona el botón "Inicio". presionado y el botón “Parar” no. Tenga en cuenta que el contacto sellado lleva exactamente la misma etiqueta que la bobina: Contactor de SALIDA. Al principio puede parecer extraño tener un contacto y una bobina en un programa de PLC etiquetados de manera idéntica (Nota 3), ya que los contactos se asocian más comúnmente con entradas y las bobinas con salidas, pero esto tiene mucho sentido si comprende el verdadero significado de Contactos y bobinas en un programa de PLC: como operaciones de lectura y escritura en bits en la memoria del PLC. La bobina etiquetada como contactor OUT escribe el estado de ese bit, mientras que el contacto etiquetado como contactor OUT lee el estado de ese mismo bit. El propósito de este contacto, por supuesto, es bloquear el motor en el estado "encendido" después de que un operador humano haya soltado el dedo del botón de "Arranque". Nota 3: Un error muy común entre los estudiantes que aprenden por primera vez la programación del diagrama de escalera de PLC es asociar siempre los contactos con las entradas del PLC y las bobinas con las salidas del PLC, por lo que parece extraño que un contacto lleve la misma etiqueta que una salida. Sin embargo, esta es una asociación falsa. En realidad, los contactos y las bobinas son instrucciones de lectura y escritura y, por lo tanto, es posible hacer que el PLC lea uno de sus propios bits de salida como parte de alguna función lógica. Lo que sería realmente extraño es etiquetar una bobina con una dirección de bit de entrada o un nombre de etiqueta, ya que el PLC no es eléctricamente capaz de establecer el estado de energía real de ningún canal de entrada. Esta técnica de programación se conoce como retroalimentación, donde una variable de salida de una función (en este caso, la variable de retroalimentación es el contactor de SALIDA) también es una entrada para esa misma función. La ruta de retroalimentación es implícita más que explícita en la programación del diagrama de escalera, siendo la única indicación de retroalimentación el nombre común compartido por bobina y contacto. Otros lenguajes de programación gráfica (como el bloque de funciones) tienen la capacidad de mostrar rutas de retroalimentación como líneas de conexión entre las salidas y entradas de funciones, pero esta capacidad no existe en el diagrama de escalera. Una secuencia paso a paso que muestra el funcionamiento y el estado de este sencillo programa ilustra cómo funciona el contacto de sellado, a través de un ciclo de arranque y apagado del motor: Esta secuencia ayuda a ilustrar el orden de evaluación o de escaneo de un programa de diagrama de escalera. El PLC lee un diagrama de escalera de izquierda a derecha, de arriba a abajo, en el mismo orden general en el que un ser humano lee oraciones y párrafos escritos en inglés. Sin embargo, según el estándar IEC 61131-3, un programa de PLC debe evaluar (leer) todas las entradas (contactos) de una función antes de determinar el estado de la salida de una función (bobina o bobinas). En otras palabras, el PLC no toma ninguna decisión sobre cómo configurar el estado de una bobina hasta que se hayan leído todos los contactos que suministran energía a esa bobina. Una vez que el estado de una bobina se haya escrito en la memoria, cualquier contacto que tenga el mismo nombre de etiqueta se actualizará con ese estado en los escalones posteriores del programa. El paso 5 de la secuencia anterior es particularmente ilustrativo. Cuando el operador humano presiona el botón "Parar", se activa el canal de entrada para el interruptor IN de parada, lo que "abre" el contacto virtual normalmente cerrado IN interruptor de parada. En el siguiente escaneo de este renglón del programa, el PLC evalúa todos los contactos de entrada (inicio del interruptor de entrada, parada del interruptor de entrada y contactor de salida) para verificar su estado antes de decidir qué estado escribir en la bobina del contactor de salida. Al ver que el contacto de parada del interruptor IN ha sido forzado a abrirse mediante la activación de su respectivo canal de entrada discreta, el PLC escribe un estado "0" (o "Falso") en la bobina del contactor OUT. Sin embargo, el contacto de retroalimentación del contactor de SALIDA no se actualiza hasta el siguiente escaneo, razón por la cual aún lo verá resaltado en color durante el paso 5. Un problema potencial con este sistema, tal como está diseñado, es que el operador humano pierde el control del motor en caso de una falla de cableado "abierto" en cualquiera de los circuitos del interruptor de botón. Por ejemplo, si un cable se cae de un contacto de tornillo para el circuito del interruptor del botón pulsador de "Arranque", el motor no podría arrancar si ya estaba detenido. De manera similar, si un cable se cayera de un contacto de tornillo para el circuito del interruptor del botón de “Parada”, el motor no podría detenerse si ya estaba funcionando. En cualquier caso, una conexión de cable rota actúa de la misma manera que el estado "normal" del interruptor de botón, que es mantener el motor en su estado actual. En algunas aplicaciones, este modo de falla no sería un problema grave. Sin embargo, en muchas aplicaciones es bastante peligroso tener un motor en marcha que no se puede detener. Por esta razón, es habitual diseñar sistemas de arranque/parada de motores un poco diferentes a lo que se muestra aquí. Para construir un sistema de control de motor de “parada en caso de falla” con nuestro PLC, primero debemos volver a cablear el interruptor de botón para usar su contacto normalmente cerrado (NC): Esto mantiene activado el canal de entrada discreta 7 cuando se suelta el botón. Cuando el operador presiona el botón "Parar", el contacto del interruptor se abrirá a la fuerza y el canal de entrada 7 se desenergizará. Si un cable se cae de un terminal de tornillo en el circuito del interruptor de "Parada", el canal de entrada 7 se desenergizará de la misma manera que si alguien presionara el botón de "Parada", lo que apagará automáticamente el motor. Para que el programa PLC funcione correctamente con este nuevo cableado de interruptor, el contacto virtual para la parada del interruptor IN debe cambiarse de normalmente cerrado (NC) a normalmente abierto (NO): Como antes, el contacto virtual de parada del interruptor IN está en estado "cerrado" cuando nadie presiona el interruptor "Parada", lo que permite que el motor arranque cada vez que se presiona el interruptor "Arranque". De manera similar, el contacto virtual de parada del interruptor de ENTRADA se abrirá cada vez que alguien presione el interruptor de "Parada", deteniendo así el flujo de "energía" virtual hacia la bobina del contactor de SALIDA. Aunque esta es una forma muy común de construir sistemas de arranque/parada de motores controlados por PLC (con un interruptor de botón NC y un contacto virtual de “parada” NO), los estudiantes nuevos en la programación de PLC a menudo encuentran confusa esta inversión lógica. Quizás la razón más común de esta confusión sea una mala comprensión del concepto "normal" de los contactos de interruptor, ya sean reales o virtuales. El contacto virtual de parada del interruptor IN está programado para estar normalmente abierto (NO), pero normalmente se encuentra en estado cerrado. Recuerde que el estado "normal" de cualquier interruptor es su estado mientras está en reposo sin estimulación, no necesariamente su estado mientras el proceso está en un modo de funcionamiento "normal". El contacto virtual "normalmente abierto" del interruptor IN normalmente se encuentra en estado cerrado porque su canal de entrada correspondiente generalmente se encuentra energizado, debido al contacto del interruptor del botón normalmente cerrado, que pasa energía eléctrica real al canal de entrada mientras nadie presiona el interruptor. ¡El hecho de que un interruptor esté configurado como normalmente abierto no significa necesariamente que normalmente se encontrará en estado abierto! El estado de cualquier contacto de interruptor, ya sea real o virtual, es función de su configuración (NO versus NC) y del estímulo que se le aplica. Otra preocupación que rodea a los problemas de cableado del mundo real es qué hará este sistema si el circuito de la bobina del contactor del motor se abre por cualquier motivo. Se puede desarrollar un circuito abierto como resultado de la caída de un cable de un terminal de tornillo, o puede ocurrir porque el contacto de sobrecarga térmica se abrió debido a un evento de sobretemperatura. El problema con nuestro sistema de arranque/parada de motor tal como está diseñado es que no es "consciente" del estado real del contactor. En otras palabras, el PLC “piensa” que el contactor se energizará cada vez que se energice el canal de salida discreta 2, pero en realidad puede no ser el caso si hay una falla abierta en el circuito de la bobina del contactor. Esto puede provocar una condición peligrosa si posteriormente se elimina la falla abierta en el circuito de la bobina del contactor. Imagine a un operador presionando el interruptor de "Arranque" pero notando que el motor en realidad no arranca. Preguntándose por qué puede ser esto, va a mirar el relé de sobrecarga para ver si está disparado. Si se dispara y el operador presiona el botón "Reset" en el conjunto de sobrecarga, el motor arrancará inmediatamente porque la salida discreta del PLC ha permanecido energizada todo el tiempo después de presionar el interruptor "Start". Hacer que el motor arranque tan pronto como se reinicie la sobrecarga térmica puede ser una sorpresa para el personal de operaciones, y esto podría ser bastante peligroso si alguien se encuentra cerca de la maquinaria motorizada cuando arranca. Lo que sería más seguro es un sistema de control del motor que se niegue a "engancharse" a menos que el contactor realmente se active cuando se presione el interruptor de "Arranque". Para que esto sea posible, el PLC debe tener alguna forma de detectar el estado del contactor. Para que el PLC sea “consciente” del estado real del contactor, podemos conectar el contacto del interruptor auxiliar a uno de los canales de entrada discreta no utilizados en el PLC, así: Ahora, el PLC puede detectar el estado en tiempo real del contactor a través del canal de entrada 5. Podemos modificar el programa PLC para reconocer este estado asignando un nuevo nombre de etiqueta a esta entrada (contactor auxiliar de entrada) y usando un contacto virtual normalmente abierto con este nombre como contacto sellado en lugar del bit del contactor de SALIDA: Ahora, si el contactor no se energiza por algún motivo cuando el operador presiona el interruptor de "Inicio", la salida del PLC no se bloqueará cuando se suelte el interruptor de "Inicio". Cuando se elimina la falla abierta en el circuito de la bobina del contactor, el motor no arrancará inmediatamente, sino que esperará hasta que el operador presione el interruptor de "Arranque" nuevamente, lo cual es una característica de operación mucho más segura que antes. Una clase especial de “bobina” virtual utilizada en la programación en escalera de PLC que vale la pena mencionar es la bobina de “enclavamiento”. Por lo general, vienen en dos formas: una bobina de ajuste y una bobina de reinicio. A diferencia de una bobina de "salida" normal que escribe positivamente en un bit de la memoria del PLC con cada escaneo del programa, las bobinas de "configuración" y "reinicio" solo escriben en un bit de la memoria cuando se energizan mediante energía virtual. De lo contrario, se permite que el bit conserve su último valor. Se podría escribir un programa de arranque/parada de motor muy simple con sólo dos contactos de entrada y dos de estas bobinas de enclavamiento (ambas con el mismo nombre de etiqueta y escritas en el mismo bit en la memoria): Tenga en cuenta el uso de un contacto de interruptor de botón normalmente abierto (NO) (¡otra vez!), sin contacto auxiliar que proporcione indicación de estado del contactor al PLC. Este es un programa mínimo, mostrado con el estricto propósito de ilustrar el uso de bobinas de enganche de “establecimiento” y “reinicio” en la programación de PLC con diagrama de escalera. Las bobinas de “Configuración” y “Reinicio” (denominadas bobinas de “Enclavamiento” y “Desenganche”) son ejemplos de lo que se conoce en el mundo de la programación de PLC como instrucciones retentivas. Una instrucción "retentiva" conserva su valor después de ser prácticamente "desenergizada" en el "circuito" del diagrama de escalera. Una bobina de salida estándar no es retentiva, lo que significa que no se "bloquea" cuando se desenergiza. El concepto de instrucciones retentivas y no retentivas aparecerá nuevamente a medida que exploremos la programación de PLC, especialmente en el área de los temporizadores. Normalmente, intentamos evitar que varias bobinas lleven la misma etiqueta en un programa de diagrama de escalera de PLC. Dado que cada bobina representa una instrucción de "escritura", varias bobinas que llevan el mismo nombre representan múltiples operaciones de "escritura" en el mismo bit en la memoria del PLC. Aquí, con las bobinas de enclavamiento, no hay conflicto porque cada una de las bobinas solo escribe en el bit del contactor de SALIDA cuando su contacto respectivo está energizado. Mientras sólo se accione uno de los pulsadores a la vez, no habrá conflicto entre las bobinas con el mismo nombre. Esto plantea la pregunta: ¿qué pasaría si se presionaran simultáneamente ambos pulsadores? ¿Qué pasaría si las bobinas “Set” y “Reset” fueran “energizadas” al mismo tiempo? El resultado es que el bit del contactor de SALIDA primero se "establecerá" (se escribirá en un valor de 1) y luego se "restablecerá" (se escribirá en un valor de 0) en ese orden a medida que los dos renglones del programa se escanearan de arriba a abajo. . Los PLC normalmente no actualizan sus registros de E/S discretas mientras escanean el programa del diagrama de escalera (esta operación se lleva a cabo antes o después de cada exploración del programa), por lo que el estado real del canal de salida discreta será cualquiera que la última operación de escritura indique. , en este caso “restablecer” (0 o apagado). Incluso si la salida discreta no está “confundida” debido a las operaciones de escritura conflictivas de las bobinas “Set” y “Reset”, otros renglones del programa escritos entre los renglones “Set” y “Reset” podrían estarlo. Considere, por ejemplo, un caso en el que había otros renglones de programa después de los renglones "Establecer" y "Reiniciar" que leían el estado del bit del contactor de SALIDA para algún propósito. De hecho, esos otros renglones se “confundirían” porque verían el bit del contactor de SALIDA en el estado “establecido”, mientras que la salida discreta real del PLC (y cualquier renglón que siga al renglón “Reset”) vería el bit del contactor de SALIDA en el estado. Estado de “reinicio”: Múltiples bobinas de salida (no retentivas) con la misma dirección de memoria son casi siempre un error de programación por esta razón, pero incluso las bobinas retentivas que están diseñadas para usarse en pares coincidentes pueden causar problemas si no se anticipan las implicaciones de la energización simultánea. Múltiples contactos con direcciones idénticas no son ningún problema, porque múltiples operaciones de "lectura" en el mismo bit en la memoria nunca causarán un conflicto. El estándar de programación de PLC IEC 61131-3 especifica contactos de detección de transición, así como los contactos "estáticos" más habituales. Un contacto de detección de transición se "actuará" sólo durante un escaneo del programa, incluso si su bit correspondiente permanece activo. En la norma IEC se definen dos tipos de contactos de diagrama de escalera con detección de transiciones: uno para transiciones positivas y otro para transiciones negativas. El siguiente ejemplo muestra un diagrama de cableado, un programa de diagrama de escalera y un diagrama de tiempos que demuestra cómo funciona cada tipo de contacto de detección de transición cuando es estimulado por una señal de entrada real (eléctrica) a un canal discreto: Cuando se presiona el interruptor de botón y se energiza la entrada discreta, la primera lámpara de prueba parpadeará "encendida" durante exactamente una exploración del programa del PLC y luego volverá a su estado apagado. El contacto de transición positivo (con la letra “P” adentro) activa la prueba OUT1 de la bobina solo durante el escaneo y ve el estado de la transición de la prueba IN de “falso” a “verdadero”, aunque la entrada permanece energizada durante muchos escaneos después de eso. transición. Por el contrario, cuando se suelta el interruptor del botón y se desactiva la entrada discreta, la segunda lámpara de prueba parpadeará "encendida" durante exactamente una exploración del programa del PLC y luego volverá a su estado apagado. El contacto de transición negativa (con la letra "N" en el interior) activa la prueba OUT de la bobina2 solo durante el escaneo ve el estado de la prueba IN transición de "verdadero" a "falso", aunque la entrada permanece desenergizada durante muchos exploraciones después de esa transición: Cabe señalar que la duración de un único escaneo de programa de PLC suele ser muy corta: se mide en milisegundos. Si este programa fuera realmente probado en un PLC real, probablemente no podría ver ninguna de las lámparas de prueba encendidas, ya que cada pulso tiene una duración muy corta. Los contactos de transición generalmente se usan cada vez que se desea ejecutar una instrucción solo una vez después de un evento "desencadenante", en lugar de ejecutar esa instrucción una y otra vez siempre que el estado del evento se mantenga "verdadero". Los contactos y las bobinas representan sólo las instrucciones más básicas en el lenguaje de programación del PLC de diagrama de escalera.
  8. In a previous article, we discussed what is a function block FB, how it works in a PLC program, and how to create and use one. In this article, we will talk about data block instances of different function block types in Siemens Tia Portal and when to use each type. Contents: What is a function block FB? Different options of data instances. Single Instance. Parameter Instance. Multi-instance. What is a Function Block? A function block or an FB is simply a block that contains code logic. You use this FB to achieve specific functionality through the pieces of code written inside. When calling a function block into your code you will be asked to assign a data block also called data instance to be associated with this FB, to save the values of the FB parameters. Not all parameters inside an FB are saved in the data instance, but we will get to that later. When calling a function block, you have 3 different options for associating a data block instance with this function call. These different options will depend on where you are calling your FB. So, in a nutshell. A function block FB is basically a function FC with a dedicated data block DB, this data block is used to store the values of the function block parameters. Different Options for Data Instances We have 3 different options for a data instance of a function block, these options are: Single Instance. Parameter Instance. Multi-Instance. The three different call data instances come from the 3 different call methods: You can call a function block FB inside the main OB1 which will give you the option of: Single instance. You can call the function block FB inside a function FC, which will give you two options Single instance Parameter instance You can call the function block inside another function block, which will give you the three available options for creating a data instance Single instance Parameter instance Multiple instances Single Data Instance First, let’s start by creating a function block FB, as we mentioned before, we create a function block by clicking add a new block and choosing the type of block we want. See picture 1. Picture 1 – Creating a function block FB Now, let’s call the ReusableFB that we created inside our main OB1. See picture 2. Picture 2 – Calling the FB inside the main OB1 As you see from the previous picture, when calling an FB inside the main OB1 you will be asked to assign a data instance to be associated with this FB call. In this case, there will be only one option, which is the single instance. After choosing a single instance option, a data block will be created and associated with the FB call. See picture 3. Picture 3 – Single instance created The created single instance will be used to store the values of some of the FB parameters. Like the inputs, outputs, In Out, and static parameters. Other parameters of the FB will not be stored, like temp and constants. See pictures 4 and 5. Picture 4 – Data is saved inside the data instance Picture 5 – Data saved from the FB into the data instance. Now, let’s create a simple logic inside the FB to help us understand the data instances better. This logic will add a constant value of 15 to a static variable and then move the result to the output. See picture 6. Picture 6 – Create a simple logic Now, go back to the main OB1 and notice how your FB call is now. See picture 7. Picture 7 – Update the FB call after each change Any change you make to the logic inside the FB, will result in the need for updating the Function block call, so that the changes you made can be applied. You can update the block call by right click the FB call and pressing the update block call option or by recompiling your PLC code. See picture 8. Picture 8 – Updating the FB call After updating the block call, the changes you made in the FB code will be applied and employed in the block call. As you see in picture 9. The FB now expects an input signal of type bool to be provided and the FB will give an output of type int. Picture 9 – Inputs and outputs are now associated with the FB call Let’s simulate our code and see how the PLC will behave. See the next animation showing a simple simulation of the PLC logic so far. As you see from the animation, whenever the start signal is TRUE, the function will be executed and the output keeps changing. And once the start signal is no longer available the Output will remain at the last value recorded. The use of the data instance here is that the values of the static variable and the output variable are saved inside the single instance, so when the start signal comes back again, the function will continue from the last recorded values. Very Important Note You should never use the same single instance for two different calls of an FB. See the next animation. As you see from the animation, we have two different FB calls, but both calls are associated with the same single instance, which is why even when the start2 signal was FALSE, the Output2 value was changing with Output1. As you would expect the change in the data instance of the 1st call will also be affected in the 2nd call because they have the same memory block. See picture 10. Picture 10 – Never use the same data instance with different FB calls If you used the same data instance with different FB calls, then your function block is no longer reusable. Even if the inputs/outputs parameters are different for each different FB call. As you saw from the last video (animation) both calls had the same results even though 2nd call doesn’t even have an enable input signal. Another very important note We said before that if you call your FB from a higher-level FC, you will have two options for the associated data instance; these options are the single instance and the parameter instance. See picture 11. Picture 11 – Using a single instance with an FB called from an FC If that happened, and you will call an FB inside an FC, You should never use a single instance for your FBs. To know why that is. See picture 12 Picture 12 – Calling the higher-level FC more than once As you see from picture 12, when you call the higher-level FC in your logic more than one time, you will not be asked to assign a data block, because FCs don’t need one. But you know that there is a called FB inside the FC, this FB has a single instance associated with it. So now the 3 FC calls have the same data instance for the FB call. So, your function FC is no longer reusable. What to do? The best option for when you need to call an FB inside an FC is to use the parameter instance. Parameter Instance As we said before, if you called an FB inside an FC you shouldn’t choose the single instance but rather the parameter instance is better for your reusability purposes. A parameter instance will save the data instance of the FB called into the In Out area of the FC block interface. Allowing you to enter a new data instance for each FC call. See pictures 13 and 14. Picture 13 – Assign parameter instance when calling an FB inside an FC Picture 14 – Each FC call will need a new data instance As you see from the previous picture, whenever you call the FC inside your program, it will ask for a data instance for the reusable FB inside the FC. But, using this way you will have to create the data instance yourself. See picture 15. Picture 15 – Create a new data instance To create a new data instance, you do the same as creating an FC or an FB, but this time you choose the DB option. And make sure that you select the DB type to be the same as the FB called. Now, your FC can be reused as many times as you want, you just have to create an instance for each call. See picture 16. Picture 16 – Assign the DB to the FC call Multi-instance Database A multi-instance DB simply means that the DB of the called FB will be stored inside the DB of the higher-level calling FB. This option is only available if you call an FB from another FB. Let’s create another FB to use it as a higher-level FB. After creating this HigherLevelFB, call it from the main OB1, and off-course the only option of calling will be a single instance as shown before. See picture17. Picture 17 – Call the HigherLevelFB from the main OB1 Now, call the ReusableFB from the HigherLevelFB. And choose the Multi-instance option. See picture 18. Picture 18 – Assign multi-instance DB When you choose the Multi-instance option, the created DB will be stored inside the static parameters of the calling FB. See picture 19. Picture 19 – Instances are saved inside static parameters You can call the ReusableFB many times, each time you call it the multi-instance will be stored inside the static parameter. See picture 20. Picture 20 – Calling the ReusableFB many times As you can see the data instance of the lower-level FB will be saved inside the data instance of the higher-level FB. It is best for better program structure and easy-to-read logic. Conclusion Creating function blocks inside your code will require associating a data block with each FB call you to make in your logic. This data block or also called data instance has different options depending on the type of block that is calling your FB. Be careful when choosing the type of data instance, as some options may not be suitable for your case as we showed before. And sometimes this can lead to problems in your logic and your function can no longer be reusable. Using multi-instance can help better organize your program structure, as all called FBs will store their DBs inside the main calling FB.
  9. leikang

    System and Local Time in PLC

    In previous articles, we talked about timers in PLC, different types, and how to use them. Timers don’t really need real-time to work, as they just depend on counting seconds or milliseconds depending on your settings. But for some applications, you need to know the PLC program’s real date and time for example for diagnostics purposes. In this article, we will talk about the system and local time of a PLC. Contents: Why do I need real-time in PLC? Example program and simulation What is system time? What is local time? Conclusions. Why do I need Real-time in PLC? In many applications of PLCs, you would need to know the real-time while the process is running, for many different reasons. Following are some of these reasons: Backup of the PLC to the main server. For diagnostics of the PLC, you need to have a time record for the diagnostics, to know at which time a certain event has occurred, otherwise, diagnostics information wouldn’t be very useful. For applications where you need to work with the time of day interrupts OB10 you would need to know the actual time. You might need to use local time or system time in parts of your logic where you need to handle real-time applications. For data logging, if you have important data to save and you need the time stamp for each data recording, then you need to have the right time setting for your PLC so that stored data would make sense. PLC Example Program and Simulation To better understand what is system time and local time in a PLC, we will start by creating a very simple program and use it to explain the concept of real times inside PLCs. Check the following step: In this article, we will not create any PLC logic, but we will show some configurations that are related to the system and local time in PLC, how to set them, and what are the differences. Open Siemens Tia Portal, Add a new device, and this time we will use the CPU 1512C-1 PN. See picture 1. Picture 1 – Add new PLC Compile and start a new PLC simulation. open the online & diagnostics page and check the set time of the PLC. See picture 2. Picture 2 – Online time of the PLC From the previous picture you can see that there are two different times: The PG/PC time – this is the local time of your PC itself. The Module time – this is the actual time inside the PLC itself. Both these times can be set as the same value, or they can be different. it is best to make them the same, it is better to make the module time similar to your local time, or more specifically similar to the local time of the area where the PLC will be used. See picture 3. Picture 3 – Set time of the PLC If you want module time to be the same as local time, then select Take from PG/PC and press apply. In your main OB1, drag and drop the RD_SYS_T and RD_LOC_T instructions. These are the read system time and read local time instructions. These instructions are built-in functions FCs inside the PLC and they are used to write the local time and system time of the PLC to whichever destination you choose in the output OUT of the instruction. see picture 4. Picture 4 – Add read system and local time instructions Add a new global data block, and define some tags to work with. See picture 5. Picture 5 – Create a new global data block Run your simulation again and check both times. See pictures 6 Picture 6 – Online local and system time of the PLC You see from the previous picture that the local time and system time of the PLC is the same, but they are different from the actual local time of your PC. If you remember, we have set the module time of the PLC to be similar to the PG/PC time, which is your local time. See picture 7. Picture 7 – Module time and PG/PC time As you see, on the set time page the module time is chosen to be taken from PG/PC time. But then in actual cases, they are different. Why? Why times are different? Because the default setting of the PLC local time is the UTC+0 or the Zulu time if you’re familiar with that term, you don’t change it from the online and diagnostics page, but rather from the properties of the PLC itself. See picture 8. Picture 8 – Time of day configuration in a PLC As you can see, the default setting of the PLC time of day is set to UTC+0 time, and that is why the PLC module time was different from your actual local time. Except if you were actually in London, then you wouldn’t face this problem. To correct the PLC local time we have to change that in the configuration, we need to change the time zone to the time zone we have, which is in my case the UTC+02:00. See picture 9. Picture 9 – Adjusting PLC local time to your time zone You can also see that the daylight saving time option was deactivated because it is not used in my country. You will have to activate it if it is used in your area. Now that all configurations are set correctly, go back and see the local time and system time again in the simulation. See picture 10. Picture 10 – The local time of PLC is now the same as PC You see now after adjusting the PLC time zone, the local time of the PLC and the actual local time of your area is the same. As we said before it is very important to set the right local time of the PLC, for the many reasons we mentioned above. Can you now define what is the system time and local time of the PLC? System Time in PLC Is the module time of the CPU clock. The CPU clock interprets the module time as the coordinated universal time (UTC). Accordingly, the module time is always stored without the factors “local time zone” or “summer time” in the CPU clock. The CPU clock then calculates the local time of the CPU clock based on the module time. The module time of the CPU clock is used as a template for all time processes starting from the CPU. Examples of use: Calculation of local time of CPU clock based on module time Representation of the module time in local time under “Online & Diagnostics” Entries in the diagnostics buffer of the CPU Local Time in PLC Information on the time zone and the start of daylight saving time and standard time, which you have set in the configuration of the CPU clock, is used to output the local time. Local time is the time you have on your PC or in your country which will be different from one area to another. Conclusion Many applications will require that the PLC would know the real-time or local time of the process, so that it would be able to perform certain tasks, for example, data logging and diagnostics tasks. In a future article, we will show some applications where real-time is needed for your logic The local time of the PLC should be manually configured to match the area where the PLC will be used.
  10. In a previous article, we discussed what an organization block is, and we talked about one very important organization block, which is the main OB1. In this article, we will continue discussing the different OBs and this time we are talking about the time of day interrupt organization blocks or OB10. Contents: What is time of day Interrupt OB10? How to create and use OB10? Simple program example. Important Rules for the time of day interrupts. Conclusions. What is a Time of Day Interrupt (OB10)? As the name suggests, a time of day interrupt is an organization block that will interrupt the execution of the main cycle of your PLC program at a certain time of the day. This interrupt time (date and time) can be specified to occur once at a specified time or to occur periodically at specified time intervals, for example, every minute, hour, day, week, and some other options. You can have more than one time-of-day interrupt in the same program, they don’t have to have the same logic or code, each one can have its own functionality and also each one can be configured separately to occur at a specified time. How to Create and Use OB10? To create a time of day interrupt you follow the same steps you would do if you need to add any new block into your logic. See picture 1. Picture 1 – Add a time of day interrupt Press the Add new block option in the project tree on the left, choose organization block, and then choose a time of day interrupt as shown in the previous picture. Now you can open the OB10 and add whatever PLC logic you want to execute when this block is called, by called we mean that the interrupt event or time has occurred and so the operating system will interrupt the main cycle and execute the OB10. We will write a very simple code into the OB10 to help us better understand how this OB10 block works. In this logic, we used add instruction to add a value of 1 to a memory area that we called TimeOfDayInterruptCounter and then put the result of the summation back in the same area. That way we can have a counter for the execution of the OB10. Each time the OB10 will be called and executed, the value of TimeOfDayInterruptCounter will increase by 1. See picture 2. Picture 2 – Add your logic to the OB10 Now that we have created the OB10 and written some logic inside, we need to configure the set time of the OB10 and how many times we want it to interrupt our main cycle. To configure the time and interval setting of the OB10 we need to go to the properties page of the OB10. See picture 3. Picture 3 – Properties of OB10 In the properties of the OB10, you will find a lot of settings and attributes that you can configure. What we need now is the time of day interrupt page so we can set up when the OB10 will be called and how many times. See picture 4. Picture 4 – Time of day interrupt setting As you see from the last picture, you can set the execution of OB10, the start date, and the time of day at which the OB10 should be executed. For the sake of simulation, we made the execution interval to be every minute so that every minute the OB10 will be called and executed. That means starting from the date of 3/23/2023 and time 09:25 AM the value of TimeOfDayInterruptCounter will increase by 1 every minute. You have the option of setting the time according to the PLC system time or local time as you see from the last picture. In a previous article, we talked about the system and local time of the PLC, what each time mean, and how to configure and use them. As we said before the local time is the time you see now on your PC. So it is the actual time of the region where the PLC will be used. You have to configure the local time for the PLC, depending on where it will be used. See picture 5. Picture 5 – Setting the local time for the PLC Simple PLC Program Example We added a time of day interrupt OB10 to our PLC program and we have set it so it will be executed every minute. We also have configured the local time of the PLC. We created a simple logic of an ADD instruction to accumulate the value of the TimeOfDayInterruptCounter by 1 each time the OB10 is executed. We will add another instruction, but in the main OB1, this instruction is RD_LOC_T or read local time, so we can see how the local time is progressing and compare it with the execution of OB10. See picture 6. Picture 6 – Simple program example Compile your PLC program and start a new simulation. Notice that we will set the time of day interrupt occurrence so that the OB10 can be called and executed while we are simulation the PLC logic. See the following simulation. As you see from the animation, the value of TimeOfDayInterruptCounter is zero at the start and then it will be increased by 1 every minute starting from time 09:25 AM indicating that the OB10 is being executed every minute. Important Rules for the Time of Day Interrupts If you set a time interrupt in such a way that the corresponding OB is to be processed once, the start time must not be in the past (relative to the real-time clock of the CPU). If you set a time interrupt in such a way that the corresponding OB is to be processed periodically, but the start time is in the past, then the time interrupt OB is processed the next time it is due according to the current time. The date of periodic time interrupts must correspond to a real date. For example, the monthly repetition of a time interrupt OB with a start date of 1/31 is therefore not possible. In this case, an OB is only started in the months that have 31 days. A time interrupt activated during startup is not executed until the startup has been completed. A startup deletes all time interrupts that were set and activated by an instruction in the user program. Conclusion OB10 is an organization block that can be configured to interrupt the cycle of your program at a certain day and time. This interrupt can either occur once or periodically every certain amount of time. No specific reason why would you need an OB10, as it depends on your process and your logic. And yes, you can achieve the same functionality using your personal code, but it is an available and easy-to-use built-in function. And you know how to use it.
  11. In previous articles, we discussed what an organization block is, and we talked about the main cyclic interrupt OB1 and the time of day interrupt OB10. In this article, we will continue discussing the different OBs, and this time we are talking about the Time Delay Interrupt organization block or OB20. Contents: What is OB20? How to call OB20? Parameters of SRT_DINT instruction. Example Program. Conclusion. What is Time Delay Interrupt (OB20)? OB20 is an organization block that is called and executed by the operating system, but we have to tell the operating system when to call this OB20. The operating system gets the information from the user PLC program to call this OB20, it will wait for the delay time configured then it will call and execute whatever logic is inside the OB20. We create an OB20 block from Add a new block in the project tree. See picture 1. Picture 1 – Create a new OB20 block Now that I have created a time delay interrupt, when will it be executed? And how to configure the time delay of the block execution? Again, OB20 is an organization block, which means you don’t call the block to be executed, but you tell the operating system when it can call it and execute whatever functionality is written inside. How to Tell the Operating System to Call the OB20? To tell the operating system that we want to call the OB20, we use the SRT_DINT or start time delay interrupt, see picture 2. Picture 2 – Start time delay instruction Parameters of SRT_DINT instruction As you see from the last picture, you can use the SRT_DINT instruction to call the OB20. but you need to configure some parameters, for the instruction to work. EN: the instruction will not be executed until a negative edge signal is presented at the EN input. That means you have to assign a condition of the set of conditions to enable signal and the instruction will only work when this condition is true then false again. OB_NR: you assign the number of the delay interrupt that you need to call, in our case 20 as we created OB20, but we can create more than one delay interrupt and then we will have to call each one with a separate SRT_DINT instruction. DTIME: that is the delay time you want to wait before executing the OB20, we will set this time to 5 seconds for the sake of simulation. SIGN: Identifier that appears when the time-delay interrupt OB is called in the start event information of the OB. Example PLC Program To better understand the OB20, we will create a simple logic to see how an OB20 can be called and executed. We will build this PLC example on the previous logic we made for the OB1 and OB10 in previous articles. Inside the OB20 we will create a logic that counts how many OB1 cycles have been called and executed within the 5 seconds delay time that we have configured for the OB20. See picture 3. Picture 3 – Logic inside OB20 In the last picture, you see that we used MOVE instruction to push information on cycle counts at the start of the OB20 call and after it has been executed. See picture 4 for the rest of the logic. Picture 4 – Calculate how many cycles count inside 5 sec After that, we will subtract the two values of cycle counts to get how many cycles have been executed within the five seconds delay. Now that we have created the logic we want, how can we call the OB20? As explained before we have to use the SRT_DINT instruction. We will use this instruction inside the OB10 which we have configured before to be executed every minute. That means the OB20 will also be called and executed every minute but with a delay time of 5 seconds. In the previous article we built a logic that calls how many times the OB1 is being called and executed, we also built another logic that will call the OB10 every minute. In this example, we will use the call of the OB10 to call the OB20. See picture 5. Picture 5 – Calling the OB20 through OB10 We said before that the SRT_DINT needs a negative edge signal at the EN for the call to start. That is why we used the TimeOfDayInterruptEnabled signal which we know it will be true when OB10 is executed and then go back to false giving us the edge signal we need. Now that all PLC logic is complete, let’s compile and run a new simulation. See the following simulation of our project. You see in the animation at first the values of cycle counts are zeros but when the OB10 is called and the TimeOfDayInterruptEnabled is true logic will wait 5 seconds then the count values will be updated with cycle counts. Conclusion OB20 is an organization block called and executed by the operating system. We can tell the operating system to call the OB20 with the SRT_DINT instruction.
  12. In previous articles, we discussed different types of organization blocks, like the main OB1 which is the main cyclic program block, in this article we will take about another cyclic organization block. The OB30 or cyclic interrupt OB. Contents: What is cyclic interrupt OB30? What is the main OB1 cycle? Why do I need OB30? How to configure cyclic interrupts? What if I have more than one cyclic Interrupt? Conclusion. What is Cyclic Interrupt OB30? A cyclic interrupt OB30 is an organization block that gets called and executed at specified and exact time intervals, unlike the main cyclic OB1 which is continuously called and executed the cyclic interrupt will be called at time intervals which you should configure when creating a cyclic interrupt OB. For example, if I created an OB30 with a time interval _also called cycle time_ of 20ms, that means the operating system will interrupt the main cycle OB1 and calls the OB30 each 20ms. You have to make sure that the runtime of a cyclic interrupt OB must be smaller than its time interval. Otherwise, it could still happen that the next call of the OB30 will arrive while this call of the OB30 is still being executed. In this case, the operating system generates a time error that might lead to PLC going to STOP mode. What is the Main Cycle OB1? The main cyclic OB1 is the organization block which is responsible for cyclically executing your logic by the PLC. Whenever you create a new project and add a PLC, the Main OB1 will be automatically created by the software. The essential basis of your PLC code is the cyclic behavior, meaning you need your code to be executed continuously. When the processing of your logic has been completed, the operating system starts processing it again. That is done through the use of the main OB1, you put and call all of your logic and code inside this OB1 and the operating system will make sure to continuously execute it. Main OB1 cycle time refers to the runtime of the cyclic program, including the runtime of all nested program parts like FCs, FBs, and higher-priority OBs. If you have created several program cycle OBs, each program cycle OB contributes to the cycle time. The operating system monitors whether the cycle time remains smaller than the configured maximum cycle time. If it exceeds the maximum cycle time, PLC will either go to STOP mode or call OB80 depending on your programming. Why do I need OB30? Someone could argue that I can put whatever functionality inside the OB30 in the main OB1 and try to get away with it depending on the very fast performance of most PLCs nowadays. This can be OK sometimes, but not every time. Depending on the performance of your PLC, the main cycle time could be something between 1 to 150ms; it can be different but this is the standard configuration, this cycle time depends on so many factors, like the size of your PLC program, and interrupts inside your logic and other factors that will most likely make the run time of your cycle not stable. Now, if you need to do certain functionality exactly each 10ms, not 9ms and not 11ms. Now you can’t depend on the main OB1, as the result might not be as desired. In this case, you use the cyclic interrupt OB30, you configure it to the 10ms you want and the operating system will make sure to call and execute this function every 10ms exactly. That is why it is called interrupt; because it will interrupt the execution of the main OB1 to call and execute your OB30. Examples of Functionality that Needs OB30 PID controller processing. Safety circuits monitoring. Monitoring communication between machines. All previous examples have the need to continuously monitor and check your parameters at certain times, as they relate to real physical quantities or to machine safety. The execution of such functions shouldn’t be delayed as they affect the safety and continuity of your process. How to Configure Cyclic Interrupts? When you create a cyclic interrupt, there are some parameters you need to configure. See picture 1 for adding a new OB30. Picture 1 – Add new cyclic interrupt OB30 When creating a cyclic interrupt, you can find many parameters you can set in the properties of the block see picture 2. Picture 2 – Properties of OB30 The most important parameters that you need to consider are as follows: Cycle time Use the parameter “Cycle time” to set the period of time between two calls of the cyclic interrupt OB. It is an integer multiple of 1 µs. Phase offset Here, you set the time period by which the start times are shifted as compared to the multiple of the cycle time. See picture 3 for cycle time and phase offset configuration. Picture 3 – Setting the cycle time and offset of OB30 Priority of the cyclic interrupt OB This is another important parameter you have to consider when configuring a cyclic interrupt, as you might have more than one cyclic block, if in case two different OBs need to be called at the same time, the operating system will call and execute the block with a higher priority number. You should know that the PLC main program cycle OB1 has priority number 1 which is the lowest priority level a block can have. That is why OB1 can be interrupted by any other block call. See picture 4. Picture 4 – Setting the priority of OB30 What if I have more than one Cyclic Interrupt? It is not uncommon that you would have more than one cyclic interrupt in your logic. If you have two PID controllers in your PLC logic then you might need two cyclic interrupts to handle each PID. In that case, you need to make sure that the calling and execution of different cyclic interrupts will not be overlapped. For example, if you have OB30 with an interval cycle time of 5ms and OB31 with a cycle interval of 10ms, that means the second call of the OB30 will also be the time for calling OB31. This might lead to logic errors, even if you set the priority of one of them to be higher than the other, it will mess up your cycle time for the lower priority block. See picture 5. Picture 5 – Overlapping of calling different cyclic interrupts In that case, a phase offset may be advisable when you are using multiple cyclic interrupt OBs. If their cycle times have common multiples, you can use a phase offset to prevent simultaneous start times. See picture 6. Picture 6 – Offset between different OB calls So, to avoid this overlapping, we will set the offset time of OB31 to be 1 ms. That means the counting for the OB31 time interval will be offset by 1ms than the starting time of OB30. See picture 7. Picture 7 – Offset setting of OB31 Conclusion Cyclic interrupts are very useful for time-critical tasks that shouldn’t face any delays. You can have more than one cyclic interrupt in your logic. Use the offset setting of the cyclic interrupts to avoid simultaneous start times. Use priority setting to control the order of executing different cyclic interrupts.
  13. In this article, we continue our discussion about different types of organization blocks in Siemens PLC. This time we will take about the OB121 or the programming errors interrupt in the Tia portal. Contents: What are programming errors interrupt OB121? Examples of programming errors. What will happen if a programming error is detected? Simulating a programming error in TIA Portal. How can the OB121 be useful against programming errors? Conclusions. What are Programming Errors Interrupt (OB121)? OB121 is an organization block that will get called by the PLC’s operating system if a programming error occurs while running your logic. Note that we are not talking about a programming error that will be caught by the compiler when trying to download your logic into your PLC. See picture 1. Picture 1 – Some programming errors will get caught by the compiler As you see from the last picture, there is a programming error in my PLC logic; some operands are missing in the input and output of Network 1. But, this error was caught by the compiler before even downloading the logic into the PLC. The error in picture 1 is not the programming error type that can trigger the need to call OB121. Errors in your PLC program that can’t be found by the compiler, but still can cause troubles in your logic while PLC is running are the programming errors we mean. These errors will trigger a call to the OB121 by the operating system. Examples of Programming Errors Here are some examples of mistakes in your PLC logic that can cause programming errors: Maximum nesting depth of block calls exceeded. You have used a NULL pointer to address an operand. Unknown instruction. The addressed string has incorrect length information. Area length error when reading. Area length error when writing. Error in timer no. Access to a DB that is not loaded; the DB number is located in the permitted area. DB does not exist. These errors and many more can cause programming errors in your PLC. You can check the Help section of the TIA Portal to find out what other reasons can cause PLC programming errors. What will happen if a Programming Error is Detected? When your PLC detects a programming error, one of three events can occur. Your PLC will show an error and go to STOP mode. Your PLC will show an error but keep running your logic. Your PLC will show an error then try to solve this error. These three events will depend basically on your PLC programming. Meaning your code will decide how the operating system will behave when detecting a programming error. Simulating a programming error in TIA Portal To better understand how the PLC will behave, we will create a simple program where we cause a programming error, and then we will see what will happen. See picture 2. Picture 2 – Simple program logic The logic we created is very simple, when the InitiateProgError has been enabled the value of 126 will be moved into DB52.DBW16 area. Note that we haven’t created DB52. so, that will be our programming error. Note that this error will not be caught during compiling or downloading into the PLC. See pictures 3 and 4. Picture 3 – Error not caught by the compiler See how the block was successfully compiled, while including a programming error. Picture 4 – Block downloaded into PLC Again, the block was downloaded into PLC with a programming error. Now, let’s simulate our PLC program and see what will happen. See animation 1 for the simulation of the PLC code. Animation 1 As you see from the above animation, the PLC ERROR LED will flash red for a few seconds then the PLC will go into STOP mode. Go to PLC online diagnostics to see what happened. See picture 5. Picture 5 – Online and diagnostics of the PLC What you saw in the animation is exactly what you see in the previous picture. They can be mentioned into 3 steps: The PLC detects the programming error which is OB52 not loaded. The operating system will trigger the call for the OB121, but there is no OB121 created in our logic. When the PLC finds out that there is no OB121 created in our logic, the operating system will initiate a request STOP. And the PLC will go into STOP mode. How can the OB121 be useful against Programming Errors? Let’s add an OB121 to our PLC code and see how things will change. See picture 6. Picture 6 – Adding an OB121 After creating and adding the OB121 into our PLC logic, let’s see what will happen in the simulation. Keep in mind that we haven’t written any PLC logic inside the OB121. See animation 2. Animation 2 As you see from animation 2, when InitiateProgError is triggered, the PLC ERROR led will flash red but the PLC will keep running. Meaning that the PLC will not go into STOP mode. Let’s check the online diagnostics to see what actually happened. See picture 7. Picture 7 – Error didn’t cause PLC stop You see from the picture that the PLC detects the error but doesn’t go into STOP mode. It will skip this error, continue the cycle and start all over again from the beginning. When it arrives at the error again, it will detect the error again, giving an alarm in the diagnostics. Skip the error and continue. That means the PLC will give the same alarm every scan cycle. And that is why in the picture you see the event keeps triggered and the alarm is repeating each scan cycle. So, just having an empty OB121 will give you the benefit of keeping the PLC running and y extension, keeping your process running. But, there is more we can do, we can try to catch this error and eliminate it. Also, we can try to show the type of programming error detected. Determine the Error Type The OB121 has an internal fault ID identifier that we can use to show the type of fault, maybe as an alarm on an HMI. Inside the OB121 we will create a simple MOVE instruction, where we will push the Fault_ID input of the OB121 to a defined memory area inside our global DB. See picture 8. Picture 8 – Identifying the error type As you see from the previous picture, when the programming error occurs, the Fault_ID will be pushed into the Data.ProgErrorID. See picture 9. Picture 9 – Programming Error Fault_ID You can see the fault ID is 3A. if you check the TIA Portal help you can find the meaning of this fault. 3A: Access to a DB that is not loaded; the DB number is located in the permitted area. Catching the Error This simply means, trying to solve the PLC programming error after you have identified the reason. This will depend mainly on what is the error and how you want to handle it. We will just simulate a solution to the error, to see how the PLC will behave. The actual solution for the error we created will be to just create the DB52 or use a data block that is already created. But for the sake of simulation, we will just add a simple contact that will open when the programming error occurs to catch this error. See pictures 10 and 11. Picture 10 – Catching the error Whenever OB121 is called, the CatchError will be set. Picture 11 – Eliminate the error Whenever OB121 is called, the CatchError will be set, and it will be used to catch the programming error in Network 1. See animation 3 for the PLC simulation. Animation 3 From the above animation, you can see that when the InitiateProgError is triggered, the PLC will go into error for a moment then the error will be cleared and the PLC is in RUN mode all the time. Conclusion Just having an empty OB121 in your logic will ensure that your PLC will not go into STOP mode if there was a programming error in your code. You can later use the OB121 to also identify the error and solve it.
  14. When you are working with PLC, you need to know what types of voltages are generally available in it; so that you can do the wiring accordingly. Not just power supply, but we must also be related to the input and output voltage required. Every PLC manufacturer has their own set of voltage and current ranges according to the module and CPU they provide. In this article, we will learn the PLC operating voltages generally available everywhere. PLC Power Supply In standard, PLC operates in four types of voltages – 24V DC, 24V AC, 110V AC, and 240V AC. In some PLCs, only the CPU requires a power supply and the IO modules get supply from the CPU backplane, whereas in some PLCs, all the modules including CPU, inputs, and outputs require a power supply. In any case, you will require a SMPS or transformer in the PLC panel, for converting raw power voltage. In AC supply voltage, some PLC’s offer a range of voltage from 110-240V AC. Every power supply point in the PLC has an earthing point, for providing safety to the PLC in case of any surge or short circuit. When an AC supply is used, it is mostly equipped with a protective fuse inside. DC supply too has a fuse inside, but for AC supply, it is compulsory to use it for the high amount of voltage involved. When the rated voltage is given in the CPU, it means that the voltage you are providing has been stabilized properly and controlled to a great extent. But, it is not practical for voltage to remain constant at 24V or 240V. So, a range of rated voltage comes for a PLC like 20-28V DC or 220V-245V AC. This range is predefined in every PLC so that you get an area of power supply for working with them efficiently, without any problem. Power Supply for IO Modules Now, let us come to our next topic for the power supply required for IO modules. As discussed earlier, two types of power supplies are available – one where the module is powered by the CPU backplane itself and one where the module requires an external power supply. When using the backplane, every CPU has a rating for mA that it will provide as a load to the modules connected. For example, if a CPU has a rating of 24VDC – 450mA, then it will also specify that the CPU backplane can provide this much of current to the IO modules and you can connect only that amount of modules with the CPU rack. Also, each module will specify how much current it will take when connected on a backplane bus. This can help you select the appropriate modules and CPU for a specific application. Coming to the second type of power supply, there are some modules that require an external power supply. So, in that case, you have to choose an SMPS or transformer with a higher current and load rating accordingly. This can, in turn, power up both the CPU and modules properly and also power up other components of the panel which require the same supply. Power Supply for Field Instruments Field wiring for a PLC also mostly requires DC voltage for instruments and AC voltage for high-power devices. So, the above four voltages mentioned earlier work the same for IO module common supply wiring. Also, remember that there is mostly a battery backup inside the PLC apart from the standard power supply. This ensures that the program inside the memory of the PLC remains intact in case of any power outage. Power Supply Selection for PLC When selecting the power supply, it is thus necessary to consider the following parameters generally – rated voltage, rated current, rated power, ripple and noise, voltage adjustable range, voltage tolerance, line regulation, and load regulation. Once you have selected the right power supply, you can then wire the CPU and modules to power it up properly. In this way, we understand the concept of PLC operating voltages.
  15. Programmable logic controllers (PLC) and programmable automation controllers (PAC) are two types of industrial controllers used to automate processes and machines in manufacturing, processing, and other industrial applications. Both types of controllers have similar functions, but there are also significant differences between them. In this article, we will take about the differences, similarities, and examples of PLC and PAC. Contents: What are PLCs? What are PACs? Similarities between PLC and PAC. Differences between PLC and PAC. Examples of PLC models from various vendors. Examples of PAC models from various vendors. When is a PLC best fit? And when is a PAC? Conclusion What is a PLC? PLC stands for Programmable Logic Controller, which is a specialized industrial computer used for automation control systems. PLC is designed to operate in harsh environments and are used to control machinery in manufacturing plants, assembly lines, and other industrial settings. PLC can be programmed using 5 different languages such as ladder logic, function block diagrams, structure text, instruction list, and sequential charts. These 5 languages are approved and applied as per the IEC 61131-3 standards. What is a PAC? PAC stands for Programmable Automation Controller, which is similar to a PLC but has more advanced functionality. PAC combines the capabilities of a traditional PLC with the ability to perform much more complicated tasks and communicate with other devices and systems, making them more flexible and powerful than PLC. PAC is typically used for more complex automation and control applications in industries such as automotive, aerospace, and power generation. PAC can be programmed using the same 5 languages as PLC but also they can be programmed using C and C++, giving them the ability to handle coding more complex algorithms. Similarities between PLC and PAC The similarities between PLC are PAC are too many that it is difficult sometimes to tell if they are even different. Although there is still some difference between them. The similarities they share can be even more. Here are some of the common points between PLC and PAC: Core Functionality Both PLC and PAC are designed to provide reliable and accurate control of industrial automation systems. They are used to monitor inputs from sensors and other devices, process the information, and then output control signals to actuators and other equipment. Programming Both PLC and PAC use programming languages to create control logic that determines the behavior of the automation system. They share the 5 programming languages defined in the IEC 61131-3 standards, but PAC offer more programming language options including C and C++. Durability Both PLC and PAC are built to withstand harsh industrial environments, such as temperature extremes, humidity, and vibration. They are designed to be rugged and reliable, with long lifetimes and lower maintenance requirements. Modular Design Both PLC and PAC have a modular design, which allows for easy expansion and customization. Modules can be added or removed to meet specific requirements. Industry Standards Both PLC and PAC are built to meet industry standards for automation and control systems, such as IEC 61131. These standards ensure interoperability between devices and systems from different manufacturers. Differences between PLC and PAC The distinction between PAC and PLC can be somewhat blurry. While there is no definition of what constitutes a PAC, there are some common characteristics that differentiate PAC from PLC: Functionality While both PLC and PAC are used for automation and control applications, PAC have more advanced functionality such as motion control, process control, and data acquisition. PAC also typically have more processing power and memory than PLC. Connectivity PAC have more advanced connectivity options than PLC, including Ethernet, USB, and wireless. This makes it easier to integrate them into larger automation systems and to communicate with other devices and systems. Cost Because of their more advanced functionality and flexibility, PAC are generally more expensive than PLC. More Advanced Features PAC often have more advanced software features than PLC, such as integrated motion control, data logging, and advanced diagnostic tools. These features make it easier for engineers and technicians to monitor and troubleshoot the control system. Examples of PLC Models from various Vendors Siemens S7-1500 PLC: This is a high-performance PLC from Siemens, one of the leading automation vendors. It is designed for demanding applications and offers advanced functions such as motion control, safety, and security. See picture 1. Picture 1 – SIEMENS S7-1500 PLC Allen-Bradley CompactLogix 5370 PLC: This is a versatile PLC from Rockwell Automation that offers a wide range of I/O options and communication protocols. It is suitable for a variety of applications, including machine control and process automation. See picture 2. Picture 2 – Allen-Bradley CompactLogix 5370 PLC Mitsubishi Electric Q Series PLC: This is a reliable PLC from Mitsubishi Electric that offers high-speed processing, flexible I/O options, and advanced programming capabilities. It is suitable for a variety of applications, including automotive, food and beverage, and pharmaceuticals. See picture 3. Picture 3 – Mitsubishi Electric Q Series PLC Omron NJ Series PLC: This is a high-speed, high-performance PLC from Omron that offers advanced motion control and network capabilities. It is suitable for a variety of applications, including packaging, printing, and semiconductor manufacturing. See picture 4. Picture 4 – Omron NJ Series PLC Beckhoff TwinCAT PLC: This is a software-based PLC from Beckhoff that runs on a PC-based platform. It offers advanced functions such as motion control, CNC, and robotics, and is suitable for a variety of applications, including machine control and process automation. See picture 5. Picture 5 – Beckhoff TwinCAT CX9240 PC-based PLC Examples of PAC Models from various Vendors Emerson DeltaV DCS PAC: This is a distributed control system (DCS) PAC from Emerson. It is designed for complex continuous control applications and offers advanced functions such as process modeling, batch management, and advanced control. See picture 6. Picture 6 – Emerson DeltaV DCS PAC Schneider Electric Modicon M340 PAC: This is a high-performance PAC from Schneider Electric that offers advanced functions such as motion control, safety, and cybersecurity. It is suitable for a variety of applications, including energy, water treatment, and mining. See picture 7. Picture 7 – Modicon M340 PAC Some other examples of PAC are as follows: ABB AC 800M PAC Yokogawa ProSafe-RS PAC Phoenix Contact PLCnext Technology PAC Bosch Rexroth IndraMotion MLC PAC When is a PLC best fit? And when is a PAC? PLC and PAC are used in different types of automation applications depending on the specific requirements of that application. Here are some general guidelines on where a PLC is best fit and where a PAC is the best fit: PLCs are the best fit at: Discrete control applications: PLCs are best suited for applications that involve discrete control, such as controlling the operation of a conveyor, sorting equipment, or packaging machinery. Simple control systems: PLCs are ideal for applications that have a relatively simple control system that can be programmed using ladder logic or other similar programming languages. Cost-sensitive applications: PLCs are generally less expensive than PACs, which makes them a good choice for applications where cost is a significant factor. Small to medium-sized systems: PLCs are suitable for small to medium-sized control systems, where the number of inputs and outputs is relatively low. A conveyor system in a manufacturing plant is a good example of an automation system where a PLC is the best fit. In this application, the PLC is responsible for controlling the speed and direction of the conveyor, as well as monitoring the status of sensors and other equipment along the conveyor line. The PLC can also be programmed to handle specific production tasks such as sorting, counting, or packing. A conveyor system typically has a fixed structure and a well-defined set of operations that need to be executed in a sequential manner. PLC are well-suited for this type of application because they are designed to handle discrete control tasks and are very reliable in their operation. PLC can be easily programmed and configured to handle different types of sensors, actuators, and communication protocols. PACs are best fit at: Process control applications: PAC best suited for applications that involve process control, such as controlling the operation of a chemical plant, water treatment plant, or power plant. Complex control systems: PAC ideal for applications that have a complex control system that requires advanced algorithms and optimization functions. Large-scale systems: PAC suitable for large-scale control systems, where the number of inputs and outputs is high and the system is distributed over a large area. High-performance applications: PAC capable of handling high-performance applications that require fast data processing, real-time control, and high reliability. A power plant control system is a good example of an automation system where a PAC is the best fit. In this application, the PAC is responsible for controlling and monitoring a large number of complex processes and equipment, such as turbines, generators, boilers, and pumps. The PAC is also responsible for collecting and analyzing data from various sensors and other sources and making decisions based on that data to optimize the plant’s performance. A power plant control system is a very complex and dynamic environment, with many different processes and equipment operating simultaneously. PAC are well-suited for this type of application because they offer advanced functions such as distributed control, redundancy, and fault tolerance, which are essential for ensuring the reliability and safety of the plant. PAC can handle large amounts of data and can be programmed to perform complex algorithms and optimization tasks. Conclusion PLC and PAC are both used in industrial automation applications. They have different capabilities and are best suited for different types of applications. When selecting between PLC and PAC, it is essential to consider the specific requirements of the application. PLC typically used in discrete control applications that have a relatively simple control system. PAC used in process control applications that have a complex control system and require advanced algorithms and optimization functions.
  16. leikang

    How to Read the PLC Datasheet?

    In this article, We will learn how to read the PLC datasheet and important notes about PLC specifications that are useful to automation engineers. Also, we will talk about what different information is provided in a PLC datasheet, and how that can be useful to me as a programmer or as an installation engineer. Contents: What information does a datasheet provide? Examples of the information in a PLC datasheet Current and voltage rating PLC memory Different blocks and data areas addressing Inputs and Outputs Specifications Communication interfaces and protocols Ambient Conditions Important notes on reading the data sheet. What information does a datasheet provide? The datasheet of a PLC will provide you with much information; this information will cover almost every feature that the PLC can provide. But some of this information won’t be as important to you as others, it depends on what is your scope with the PLC. If you are the installation engineer, then you will focus on the technical specs of the PLC like the supply voltage, type of inputs and outputs, and power rating of these IO points. You will also pay more attention to the dimension of the PLC and the Ambient conditions during PLC operation to determine the size of the electrical panel you will use for the PLC and also the cooling methods used for the PLC. How to Read the PLC Datasheet? On the other hand, if you are just the PLC programmer, then the past information might not be as critical to you, instead, you will focus on data related to for example the PLC memory, the number of IO available, and the capability of adding new modules. You will also pay attention to some other information like the programming languages supported by that PLC because not all PLCs support all programming languages. Communication and networking are also other important points you will care about as a programmer. The data sheet of a plc will always start with a general overview description of the PLC. See pictures 1 and 2 for S7-1200 and S7-1500 simple examples. Picture 1 – 1st page of an S7-1500 PLC data sheet. Picture 2 – 1st page of an S7-1200 PLC data sheet. As you can see, a general description of the PLC is given at the beginning of the datasheet. This general description will give you a basic idea about the PLC and if it fits your application or not. Examples of the information in a PLC Datasheet In this article, we will use the data sheet of an S7-1200 PLC to show some of the different information it contains. Current and Voltage Rating In a certain section of the data sheet there must be some information about the PLC voltage and current ratings, some PLCs will need a DC supply while others will require an AC supply, also the inputs and outputs of the PLC might have different ratings, which is exactly the case in our PLC, where the voltage supply to the PLC is 220AC but the ratings for IOs are DC. See picture 3. Picture 3 – Voltage and current ratings. PLC Memory Different memory capabilities of the PLC will be provided in the datasheet, this will show how much work memory you have and whether you can expand it or not, see picture 4. Picture 4 – Memory description of the PLC. Different Blocks and Data Areas Addressing In this section, you will know the different blocks that you can use with your PLC, like timers, counters, FCs, etc. And the maximum number of blocks that you can use. You will also be provided with the data areas’ memory and their retentivity. See picture 5. Picture 5 – CPU blocks are available. Inputs and Outputs Specifications This is another critical data that should be provided, through this information you will know the number of IOs provided with your PLC, and how to connect and use each IO. See pictures 6 and 7. Picture 6 – Digital inputs of the PLC. As you can see, we have 8 DI points in our PLC, 6 of which can be used for HSC (high-speed counting) inputs like encoders. It also tells you that the input voltage is 24vdc which means you can’t directly connect AC sensors of inputs to the PLC. Picture 7 – Digital outputs are available in our PLC. If the PLC has analog IOs then it will be mentioned also in the data sheet. See picture 8 Picture 8 – Analog IOs description. Communication Interfaces and Protocols The communication interfaces available in your PLC, as well as the communication protocols it can support, will also be mentioned in the datasheet. See picture 9. Picture 9 – The communication interface of the PLC. As you can see, the PLC we have only has one communication interface, which is a PROFINET interface provided as an RJ-45 port. However, the PLC itself can support many communication protocols such as PROFIBUS and AS-Interface. See picture 10. Picture 10 – Communication protocols supported. Ambient Conditions This is another very important data you should know about your PLC, as it will help decide the type of enclosure and cooling that will be best suited to your PLC. See picture 11. Picture 11 – Ambient condition of the PLC. Important notes on Reading the DataSheet of a PLC Not all the PLC data sheets contain the same information, as different PLCs will have different features and capabilities and hence, different information to show. Not all the information inside the datasheet will be important to you, that will depend on whether you are a PLC programmer or an installation engineer as we mentioned before. It’s OK if you don’t understand some of the information in the datasheet, as we said the data sheet will provide information about almost all the features supported by your PLC, you might not know about some of these features and you might not even ever need to use it. For example, the OPC UA or the web server features. So if you find some data you don’t understand, it won’t necessarily mean your PLC doesn’t fit your project. Conclusion Reading the PLC datasheet is important to help decide if the PLC is suitable for your application or not. It is also important to decide what types of IOs and voltage supply ratings you can work with. Try reading the datasheet of different PLC models and see if you can understand the basic information provided in the datasheet.
  17. When you hear about PLC programming, the five used languages in it are – ladder logic, structured text, functional block diagram, sequential flow chart, and instruction list. Any language, once understood, can be used for writing an application code and running a machine properly. Best PLC Programming Language Figure – Sample Ladder Logic But often, new PLC programmers get confused as to what to use for writing a program. If he understands a language’s advantages and disadvantages, then he can easily determine what to use for writing a PLC program. So, it is necessary to understand the difference between them and define which language to use for coding. In this post, we will see which language is best for PLC programming. Ladder Logic Ladder Logic is the most basic type of PLC programming language. It can easily be correlated to an electrical wiring control diagram. Traditionally, electrical control wiring was used to operate outputs according to the inputs provided. The ladder Logic drawing consisting of contacts and coils was implemented in the same way in the ladder logic programming. You have a series of rungs, each rung having contacts and coils. When the rung is powered up, the coil, depending upon its type, operates accordingly. You can write as many rungs as required in a program and the code will execute accordingly. When you see it, the resemblance is similar to a ladder, and thus, the name is given ladder logic. Refer to the below diagram for understanding. You can see how simple it is to get through. In the above illustration, inputs associated with a switching device in the relay logic diagram are shown as contacts in the Ladder Diagram. The M1 output coil in the relay logic diagram is represented with an output coil symbol in the Ladder Diagram. The address numbers appearing above each contact/coil symbol in the Ladder Diagram are references to the locations of the external input/output connections to the logic controller. So, in between two end power rails, you can place the required elements and write the logic in them. The rungs execute in a cyclic manner from top to bottom. Structured Text Structured Text can be said as the local IT-level language. The resemblance of structured text language is very similar to codes that we write in a software language. As the name implies, Structured Text is a series of texts written in an assignment way. Instructions must be terminated with semicolons. When an assignment is performed, the current value of a single or multi-element variable is replaced by the result of the evaluation of the expression. An assignment consists of a variable specification on the left side, followed by the assignment operator: =, followed by the expression to be evaluated. Both variables (left and right sides of the assignment operator) must have the same data type. Refer to the below diagram for understanding. As you can see, it has different types of operations and conditions. In the above example, an if-else statement is used to evaluate an expression. If the condition is true, then the variable assigned on the output side turns on and when the condition goes false, then the variable will turn off. ST language is thus best for mathematical calculations, as it looks sober and easy to understand. Sequential Flow Chart A sequential Flow Chart is the most advanced tool when you want to write complex programs in a repetitive way or sequential way. As the name implies, SFC language allows you to write a program through a flow chart. It works in steps, branches, links, jumps, and transitions. An SFC section is a “Status Machine”, i.e. the status is created by the active step and the transitions pass on the switch/change behavior. Steps and transitions are linked to one another through directional links. Two steps can never be directly linked and must always be separated by a transition. The active signal status processes take place along the directional links and are triggered by switching a transition. Refer to the below image for understanding. The direction of the chain process follows the directional links and runs from the end of the preceding step to the top of the next step. Branches are processed from left to right. Every step has zero or more actions. A transition condition is necessary for every transition. The last transition in the chain is always connected to another step in the chain (via a graphic link or jump symbol) to create a closed loop. Step chains are therefore processed cyclically. Functional Block Diagram The Functional Block Diagram (FBD) language that is generally used in microprocessors, is available in a similar format in PLC programming too. It is a diagram of blocks connected with each other, with each block having its input and output. FBD language is very easy to troubleshoot because you can literally view the whole code in a single view, rather than scrolling up and down. This helps in quick maintenance and also increases the efficiency of the programming. Refer to the below image for understanding. As you can see, you can connect various types of functions and blocks easily by lines, which shows how a flow is happening in the logic. You just have to assign input and output pins, connect the lines between these pins and your code works accordingly. Instruction List A program written in Instruction List language consists of a series of instructions that are executed sequentially by the logic controller. Each instruction is represented by a single program line and consists of the following components – line number, current value which can be seen online only, instruction operator, and operand. Refer to the below image for understanding. You can see that each line executes one single operation only. Instead of contacts and coils used in ladder logic, you have load instructions and set/reset instructions corresponding. It is a mixture of ladder logic and structured text. That is why, it is also called as similar to an assembly language. When you go online in the PLC, you can see animated values in this window. When we see these five languages, we see that the most ones that are generally used by programmers are ladder logic, structured text, and functional block diagram. Every language has its merits and demerits. But, these three are simple to understand, interpret, and design. This helps the programmer in designing the logic properly. That does not mean that the remaining two languages are not used. It depends on the skills of the programmer on what he has to use to implement the coding. So, it is difficult to comment on the best language; but yes, out of these three too, the most used is the ladder logic.
  18. When you develop a PLC logic, you always need timers and counters. Any cycle in an automation process is generally incomplete without the use of timers and counters. You need them to execute a task after a certain time or keep the task on / off for a certain time. Its use depends on the application to be developed. And, before going deeply into advanced instructions of PLC, a programmer must first understand these basic blocks to implement them properly and to get assistance in learning the advanced blocks more easily. In this article, we will learn the difference between timers and counters in PLC programming. What is a Timer? A timer is an instruction that is used to turn on or off an output after a certain delay. For example, if you want to turn on a lamp after 5 seconds, then use a timer to execute this task. A timer will take an input and when the input turns on, then its timing will start. After the time of 5 seconds elapses, then the timer output will turn on which turns on the lamp indirectly. This we are talking about is the normal timer on the type. A timer has more two types – timer off and pulse timer. In short, the basic function is the same – execute a task after a certain delay. Refer to the above image for understanding more correctly. A timer has four inputs and outputs – input, set value, current value, and output. An input takes the condition for starting a timer, a set value is used to take the set timer value, the current value shows the current timer value running and the output is used to turn on or off the variable connected to it. When the PLC timer gets the input and if the set value is 5 seconds, the timer starts as 1, 2, and 3, and so on till 5. When 5 seconds have been completed, the output turns on. When the input goes off, the timer’s current value immediately goes to zero. Whether the timer was running or not; if the input is off, then the timer will not start and its output and current value will be zero. This is the functioning of a TON (timer on delay) timer. What is a Counter? A counter is an instruction that is used to turn on an output after a set count has been reached. The count can either increment or decrement. For example, if you want to turn on a lamp after a push button has been pressed five times, then use a counter to execute this task. A counter will take an input and when the input turns on, then its count will increment to 1. When the input goes off, nothing will happen. When it again receives the input, the count will increment to 2. After the count of 5 elapses, then the counter output will turn on which turns on the lamp indirectly. This we are talking about is the counter-up type. A counter has one more type – counter down. In short, the basic function is the same – execute a task after a certain count. Refer to the above image for understanding more correctly. A counter has five inputs and outputs – count input, reset input, set value, current value, and output. A count input takes the condition for counting, reset input takes the condition for resetting the counter, the set value is used to take the set counter value, the current value shows the current counter value running and the output is used to turn on or off the variable connected to it. When the counter gets the count input and if the set value is 5, the counter increments to 1 and so on till 5; at the receipt of each pulse in the count input (means the count input will have to be turned on and off 5 times). When 5 counts have been completed, the output turns on. Now, even if the count input pulse is given, the counter will go on increasing after 5 and the output too will remain on. To again bring back the counter state to zero, you have to give reset input. When this input is given, the counter current value becomes zero and the output too turns off. So, it is similar to latching-type functioning. To unlatch the counter, you will have to reset it. This is the functioning of a CTU (count up) counter. Difference between Timer and Counter The main differences between timers and counters in a PLC are as follows. A timer needs to have its input continuously for turning on a variable, but a counter need not to have its input continuously. So, a timer works on continuous conditions, whereas a counter works on pulse conditions. If the timer input is removed, then its output will go back to zero states; but if the counter input is removed, then to the counter will hold its last value. A timer does not have reset input, whereas a counter requires reset input to get back the counter to its original state. The types of timers are – timer on, timer off, and timer pulse. The types of counters are – counter up and counter down. A timer set value can be in seconds, minutes, or milliseconds; but a counter set value is a fixed integer.
  19. In this advanced PLC logic, detect different part sizes and sort them as per box sizes and place them in the trays. The parts are nothing but different size boxes such as small, medium, and large. The robot places different size boxes randomly on the conveyor. Then the system detects the box size and moves to the respective conveyor and places them in the respective trays. Sorting & Distribution Line PLC Programming The below simulation shows the sorting and distribution line system operation. Inputs and Outputs Type Device No. Device name Operation Input X0 Starting point (Supply) ON when the part is detected. Input X1 Upper ON when the part is detected. Input X2 Middle ON when the part is detected. Input X3 Lower ON when the part is detected at the right end. Input X4 Sensor ON when the part is detected at the right end. Input X5 Sensor The conveyor moves forward when Y1 is ON. Input X6 Detect part ON when the part is detected in front of the pusher. Input X10 arting point (Unload) ON when the unloading robot is at the start point. Input X11 Part on table ON when the part is on the table. Input X12 Robot operation finished ON when the robot operation is finished. Output Y1 Conveyor forward The conveyor moves forward when Y2 is ON. Output Y2 Conveyor forward Moves toward the front when Y3 is ON. Output Y3 rting wing The conveyor moves forward when Y4 is ON. Output Y4 Conveyor forward The conveyor moves forward when Y5 is ON. Output Y5 Conveyor forward Extends when Y6 is ON and retracts when Y6 is OFF. The pusher cannot be stopped in the mid-stroke. Output Y6 Pusher The robot moves part to tray when Y7 is ON. A process cycle begins. Output Y7 Unload command The robot moves the part to tray when Y7 is ON. A process cycle begins. Output Y10 Red Lit when Y10 is ON. Output Y11 Green Lit when Y11 is ON. Output Y12 Yellow Lit when Y12 is ON. Program Description Initiating the push button PB1 (X20) on the control panel triggers the Supply command (Y0), thereby setting the robot in motion for moving the object. Once the robot has completed its task of moving the part and reverting to its original position, the Supply command (Y0) is deactivated. Activating the Supply command (Y0) propels the robot to provide a part. Activating the switch SW1 (X24) on the control panel instigates the conveyors to proceed forward. Conversely, deactivating the switch causes the conveyors to halt. Conveyor-carried parts of varying sizes, namely large, medium, and small, are sorted by input from the Upper (X1), Middle (X2), and Lower (X3) sensors and delivered to designated trays. Large parts are directed to the rear conveyor when the Sorting wing (Y3) on the split conveyor is activated, followed by the part being transported on the conveyor and eventually descending from the right edge. Medium parts are led to the front conveyor when the Sorting wing (Y3) on the split conveyor is deactivated and subsequently transferred to the tray by the robot. Small parts are routed to the rear conveyor upon activation of the Sorting wing (Y3) on the split conveyor. Once the Detect part sensor (X6) in the split conveyor is activated, the conveyor is brought to a halt and the part is nudged onto the tray. When the Robot detects a part on the table (X11), the Unload command (Y7) is activated. Once the robot finishes its operations, indicated by the Robot operation finished (X12) status turning on (which happens when a part is deposited on the tray), the Unload command (Y7) is deactivated. Provided the switch SW2 (X25) on the control panel remains activated, an automatic supply of a new part occurs under the following conditions: When the robot initiates the transportation of a medium part. When a small part is added to the tray, or a large part descends from the right edge of the conveyor. The display lights flash in the following manner: The red light indicates the robot is in the process of supplying a part. Green light signifies the conveyor is in motion. Yellow light is illuminated when the conveyor is at a standstill. PLC Program
  20. In this advanced PLC program, PLC based product sorting machine system is used to carry different products using the lift to separate the parts based on size. Here there are three positions available based on the size like small, medium, and large. The conveyors are used to transfer the products and place them on the trays. PLC Based Product Sorting Machine System The below simulation shows the PLC sorting system using the lift operation. Inputs and Outputs Type Device No. Device name Operation Input X0 Upper ON when part is detected. Input X1 Middle ON when the lift is at a lower position. Input X2 Lower ON when the part is detected. Input X3 Part on lift ON when the part is detected. Input X4 Lower lift position ON when the lift is at the middle position. Input X5 Middle lift position ON when the lift is at middle position. Input X6 Upper lift position ON when the part is on the lift. Input X10 Sensor ON when the part is detected at the left end. Input X11 Sensor ON when the part is detected at the left end. Input X12 Sensor ON when the part is detected at the right end. Input X13 Sensor ON when the part is detected at the left end. Input X14 Sensor ON when the part is detected at the right end. Input X15 Sensor ON when the lift is at the upper position. Output YO Supply command One part is supplied when YO is ON: Metal cylinder repeats in order S, L, M, L, M, S. Output Y1 Conveyor forward ON when the part is detected at the right end. Output Y2 Lift up command The lift moves up when Y2 is ON. The lift stops when Y2 is OFF. Output Y3 Lift down command The lift moves down when Y3 is ON. The lift stops when Y3 is OFF. Output Y4 Lift rotation command The conveyor moves forward when Y1 is ON. Output Y5 Lower conveyor forward Lift rotates to transfer part to conveyor when Y4 is ON. Lifts rotates back to the original position when Y4 is OFF. Output Y6 Middle conveyor forward The conveyor moves forward when Y5 is ON. Output Y7 Upper conveyor forward The conveyor moves forward when Y6 is ON. Program Description The entire system comprises two components: General Control and Lifter Management. General Control: Activating the PB1 (X20) button on the operational panel initiates the Supply command (Y0) for the hopper. Deactivating the PB1 (X20) button turns the Supply command (Y0) off. Upon activation of the Supply command (Y0), the hopper delivers a part. The conveyors initiate movement when the SW1 (X24) on the control panel is activated. Conversely, the conveyors halt movement when the SW1 (X24) is deactivated. Upon detecting a part by the sensor X10, X12, or X14 positioned to the left of the conveyor, the corresponding conveyor initiates, transporting the part to the right-end tray. Three seconds post a part passing by the sensor X11, X13, or X15 to the right of the conveyor, the conveyor halts. Parts of varying sizes (large, medium, small) on the conveyor are sorted by the inputs of the Upper (X0), Middle (X1), and Lower (X2) sensors. Lifter Management: Once the Part on the lift sensor (X3) in the lift is activated, the part is transported to one of the following conveyors based on its size: Large part: Directed to the Upper conveyor Medium part: Directed to the Medium conveyor Small part: Directed to the Lower conveyor The commands for Lifting Up (Y2) and Lifting Down (Y3) are managed based on the lift’s position, detected by the following sensors: Upper: X6 Middle: X5 Lower: X4 Upon the part’s transfer from the lift to the conveyor, the Lifter Rotation command (Y4) is initiated. Post the transfer of a part, the lift returns to its initial position and remains on standby. PLC Logic
  21. leikang

    PLC Fault Diagnosis

    When you are working in a PLC system, it is necessary to understand what faults occur in the PLC modules. If a PLC programmer does not understand what fault is coming in the PLC and how to solve it, then he will take a very long time to troubleshoot the system. Every PLC and its modules have LEDs on them for visual easing and troubleshooting. Their detailed description is also given in their user manuals. So, it is important to understand how these LEDs function and once you get them, fault diagnosis becomes a very easy task for PLC programmers. In this post, we will learn the concept of fault diagnosis in PLC. PLC Fault Diagnosis Let us have a look at some of the most general types of faults which can be identified with PLC LED’s: Run LED is used to denote whether the module is functioning properly or not. If it is on continuously, then it means that the module is working properly. If this LED is off, then the module is faulty or off. Err LED is used to denote whether the module is in error or not. If it is on continuously, then it is an internal module error. If it is flashing, then it means either the module is not configured properly or there is some issue in the PLC hardware connected to it. If it is off, then it means there is no fault in the module. I/O LED is used to denote the exact status of the PLC IOs connected with the module. If it is on continuously, then it means there is some supply voltage error or short circuit. If it is off, then it means there is no error in the IO’s connected. Channel LED is used to show the status of individual channels. If the LED is on continuously, then it means the channel is functioning properly. If it is flashing, then there is some error in it (broken wire or value out of range). If it is off, then it means the channel is not configured at all. Some communication modules like Modbus RTU have a truth table of the LEDs, signifying each value of the same. LED Indications in PLC They are mostly as in the below table: Note: The LED indications may vary based on the PLC model and brand. The above table is an example from one of the PLC models in the market. Some communication modules like Modbus TCP/IP have slightly complicated LED diagnostics. But it is important to understand them for troubleshooting. The module is running if the run LED is on and stopped if the LED is off. If Err LED is flashing, then it means the module is in error and if it is flashing, then it means either the module is not configured properly or there is some issue in the backplane if it is connected. If the network status LED is off, then it means that the module is not communicating with any device; if it is on, then it is communicating with at least one device; if it flashing, then it means some duplicate IP address has been detected or some time out error. In this way, we saw some general fault diagnoses in PLC.
  22. When you are working in a PLC system, you know that the most basic thing to take care of is memory. What program you write, and how much memory has been consumed; is a very important factors in determining PLC performance. For this, it is necessary to understand how memory structure is organized and defined in a PLC. PLC Memory Organization Without knowledge of memory organization, it would be difficult to predict how much exact program you have to write. In this post, we will see memory organization in PLC. Memory in a PLC is divided majorly into two types – data files and program files. Data Files The data file is the location of memory which stores information like memory words, status words, input variables, output variables, communication variables, timers, counters, and other in-built library functions provided by the PLC manufacturer. Let us have a look at each example one by one. Memory words – Memory words are Boolean variables, integer variables, double integer variables, and floating variables. Suppose a PLC has allocated 100 memory variables for usage. Out of these, only 5 variables are used. The first variable is bit type, storing either 0 or 1. The second variable is an integer, signed or unsigned. The third variable is also an integer. The fourth variable is a double integer, signed or unsigned. If a variable is a double integer or float, it consumes two memory variables. So, the fifth memory variable will be a double integer. Status words – Status words store information about PLC. It comes in two types – status bits and status integers. Input variables – They store data regarding digital inputs and analog inputs of the PLC. Output variables – They store data regarding digital outputs and analog outputs of the PLC. Communication variables – They store data regarding communication protocols used in PLC. They can be Modbus, Ethernet, Can-Open, etc. Apart from these, other in-built libraries if used to come in data files memory. They are timers, counters, pulse blocks, etc. Program Files As the name defines, program files store data regarding logic written, subroutines, and interrupts. This is the main consuming part of memory in PLC. If the PLC code written is more, then program file consumption will be large and if the code written is less, then program file consumption will be less. All the logic, be it a ladder, functional block diagram, structured text, sequential flow chart, or instruction list, comes in program files memory. Also, user-defined function blocks and user-defined data types come in program files. Memory organization in PLC is stored in either internal storage or internal and external SD cards. When there arises a situation where the internal memory storage is getting full and you need more data for the writing PLC program, then you need to insert an external SD card for extending program memory. In that case, both the data files and program files are extended. Many PLCs have an online animation window, which shows current memory usage. It can be viewed either online or offline. This helps in better memory planning.
  23. Be it industrial automation or any other PLC system, every device or equipment reaches a stage after a certain period of time, where there arises a need to either change it or upgrade it. Upgrading and Migration A PLC, if served for more than 10 years for example, will reach a stage where its technical support no longer exists or the PLC is not available for replacement as it has become obsolete. In this case, you are left with two options – either to migrate to a completely new set of PLCs or upgrade the firmware and program. This difference is really important to understand, as it helps in choosing the right work for the same. In this post, we will learn the difference between upgrading and migrating PLC systems and understand how to implement the correct one. Why is Migrating or Upgrading PLC Systems Required? Before going into the topic, it is first of all necessary to understand why we need to do the same. Suppose you have been using an “X” PLC for almost 15 years down the line. It is not like the program will start to malfunction suddenly; it is a completely different theory and entirely depends on how the programmer has written the code. PLC Code once written executes the same way for a lifetime as it is. The issue starts with hardware and support. A PLC manufacturer mostly won’t keep this “X” PLC in production for such a long period of time if it is not stable or has many limitations in programming. Sooner, this PLC will start to become obsolete and its replacement will not be available. Even the system integrator or the PLC manufacturer itself will not be able to provide its technical support as the staff for the same will be shifted to a newer brand or its programming cable is also no longer available. In that case, if suddenly the PLC system fails due to some reason, then you are left with no option but to wait for a longer downtime period to end. Also, if you are still able to get this PLC from somewhere, then its cost will be super-high and out of budget. With the current supply chain disruptions and the recent scarcity of new industrial automation solutions and parts, it’s not feasible to estimate exactly how long it might take to source a new unit. In that case, you are left with two options – either to migrate to another brand or upgrade the existing one to a newer firmware CPU or program. So, it is this reason why migration and upgradation play an important role in industrial automation. Also, new solutions bring with them reduced errors, and risks, stronger technical support, service expertise, less capital investment, and efficient operation of plant. What is the Migration of the PLC System? First of all, let us understand the simpler one of the two. Migration means to completely replace an old system with a new system. This is similar to a citizen migrating from his previous city to a new city. Suppose you have an old PLC that has some hardware defects in it after it has been found 10 years old. Two digital inputs of the CPU have become faulty and the CPU is no longer available in the market. Also, due to some bad luck, the system integrator which provided the PLC has shut down his business or shifted to some newer brands. In that case, migrating means you will need to buy a PLC of some other brand. Before buying, you will need to consider factors like IO counts, IO wiring, communication port availability, programming capacity, memory capacity, speed of execution, how much it can be expanded, etc. Once you get through all this, you will then need to buy a new one and write a new program in it according to the manufacturer’s software. Also, you need to share the previous IO list with the new vendor, so that he will do the IO mapping in PLC accordingly and will reduce time to wire the IO’s in the electrical panel. Once done, you can replace the old PLC with the new one and use the system accordingly. Although new and consistent programming standards can’t be fully applied using this approach, the overall functionality remains as close to the original as possible, and the program can be improved to some extent. What is Upgrading of PLC Systems? Let us take a second case of upgrading the PLC system. You have the same PLC of the manufacturer as discussed before and its failure has occurred. Now, you find that some higher level of PLC of the same manufacturer is available, with similar coding style and IO functionalities. Even the vendor is available for support. Instead of changing the vendor to a newer one or completely changing the PLC brand, you will just need to upgrade your system to a newer and higher one. This new CPU will have to be either rewritten with the new coding or just plugged and played, depending on the software. An upgrade thus, requires a more comprehensive IO wiring and PLC coding to be done as we update the system. Also, rewriting new codes from scratch allows the programmer to eliminate the bugs he had observed in older systems and also plan for efficient and reliable logic in a simpler manner. This is a clean slate approach to upgrading a system. Difference between Migrating and Upgrading PLC systems Migration means switching to a completely new PLC manufacturer, whereas upgrading means switching to a newer CPU of the same PLC manufacturer. Migration is cheaper than upgrading, as it requires less downtime, less new hardware, less programming time, and designing infrastructure. Migration is less risky than upgrading, as you already have the program available of the older one, and you just need to copy-paste the same. Though 100% copy is not possible, functionalities can be similar in a large way due to this approach. Migration can lead to new hardware and this can take time for engineers to understand the system quickly so that then they can maintain and troubleshoot it. In this case, upgradation is much easier. Migration is less reliable and efficient than upgrading because you do not know how this new PLC will function now in spite of studying it so much. Migrating and upgrading is a tricky thing to do and requires the detailed expertise of engineers and programmers involved in it. Also, what action to take varies from system to system. Once done, it can make your task completely easier. In this way, we saw the concept of upgrading and migrating PLC systems.
  24. In the last articles, we discussed how to establish a connection between two PLCs using the TCON and TDISCON blocks and how to move data between them using the TSEND and TRCV blocks. Transferring Data Across PLC Systems In this article, we will learn a new instruction that can be used to communicate and transferring data across PLC systems using TSEND_C and TRCV_C blocks. TSEND_C The TSEND_C instruction is a TIA Portal instruction that is used to set up and establish a connection between two PLCs. Once the connection has been set up and established, it will be automatically maintained and monitored by the PLC. The TSEND_C instruction is executed asynchronously and has the following functions: Setting up and establishing a communication connection similar to TCON block. Sending data via an existing communication connection similar to TSEND block. Terminating or resetting the communication connection similar to TDISCON. Hence, the name compact is giving to the TSEND_C as it acts as more than 3 blocks in the same time. TRCV_C The TRCV_C instruction is also a TIA Portal instruction that is used to set up and establish a connection between two PLCs. Once the connection has been set up and established, it will be automatically maintained and monitored by the PLC. The “TRCV_C” instruction is executed asynchronously and implements the following functions in sequence: Setting up and establishing a communication connection similar to TCON. Receiving data via an existing communication connection similar to TRCV. Terminating or resetting the communication connection similar to TDISCON. Hence, the name compact is given to the TRCV_C as it acts as more than 3 blocks at the same time. Using TSEND_C and TRCV_C in our PLC project In the last article, when we needed to establish and move to send data from PLC_1 into PLC_2 we had to use three different blocks in each PLC. See picture 1. picture 1. Logic inside PLC_1 As you can see, we used the TCON and TDISCON blocks to establish and reset the connection and we used TSEND to send the data from PLC_1. And the same was done for the PLC_2. See picture 2. picture 2. Logic of PLC_2 Again, we used the TCON and TDISCON blocks to establish and reset the connection and we used TRCV to receive the data from PLC_1. Now, we want to replace all these blocks and try to use the TSEND_C and TRCV_C instead to achieve the same functionality. First, in PLC_1 where we need to send data, we will use the TSEND_C block, just drag and drop the block inside the main OB1. See picture 3. picture 3. Add TSEND_C block. As the TSEND_C is essentially a function block, you will be asked to create a data instance. See picture 4. picture 4. Create an instance for the TSEND_C The TSEND_C looks similar to the TSEND block in the sense that you need to make some configurations and add some signals. See picture 5. picture 5. TSEND_C block Now, we need a signal for the REQ and Data to send and also to configure the connection. For the REQ signal, we created a SendData tag. Also, we can just drag and drop the data block that we created last article which we need to send it to PLC_2, we can just drag it and drop at the DATA input of the block. See picture 6. picture 6. Configuration of TSEND_C block. To configure the connection parameter for the block, we can press the small configuration icon on top of the block to open the configuration view. The configuration view will look something very similar to that of the TCON block. See picture 7. picture 7. Connection parameter of TSEND_C We already showed how to configure the connection parameter in previous articles, so we can just do the same as we did with the TCON block, see picture 8. picture 8. Configuration of connection parameter With this connection configuration, we finished all configurations of the TSEND_C. Notice how much faster it was compared to configuring TCON, TDISCON, and TSEND blocks. Now, we need to add the TRCV_C to the PLC_2 so it can receive the data sent from PLC_1. In the main OB1 of PLC_1 just drag and drop the TRCV_C into your logic. see picture 9. Remember to create a data instance for the TRCV_C block. picture 9. Add the TRCV_C Once the TRCV_C is added to your logic, we need to configure it. As we did with the TSEND_C we need to add a signal to enable the data receive and also we need to add the data block we will save the data inside. See picture 10. picture 10.TRCV_C We defined a RecieveData tag as the EN_R signal. See picture 11. picture 11. Define EN_R tag Remember to uncheck the “optimized block access” option of the data block or the block won’t work as we showed last articles. Next, we need to configure the connection parameters of the TRCV_C block, as we did with the TSEND_C just keep in mind that the unspecified Partner PLC is now the PLC_1 see picture 12. picture 12. Connection parameter of TRCV_C PLC Project Simulation Now that we have configured the TSEND_C and TRCV_ C block, we want to simulate our project and see how they will work but first, we will create a simple logic to automatically update the data of PLC_1 which will be sent to PLC_2. See picture 13. picture 13. Simple logic to update data automatically. Now let’s compile and start a simulation for our project. The first thing you will notice is that PLC_1 and PLC_2 will try to establish a connection right away because we set up the TSEND_C and TRCV_C they automatically try to establish a connection. That is why there will be a connection between the two PLCs. See picture 14. Picture 14. Connection is established directly. As you can see the connection between the PLCs is directly established, because the CONT parameter in the TSEND_C and TRCV_C is set to TRUE, which means the block will automatically try to establish a connection with the partner PLC. We can put any controlling signal in here to control the connection establishment. The other thing you can see is that the REQ of the TSEND_C and the EN_R of the TRCV_C are set to FALSE, and that is why there will not be any data moving between the PLCs. See picture 15. picture 15. No data transfer between PLCs. If the REQ signal of the TSEND_C is set to true, the PLC_1 will try to send the data but it will wait for the other PLC to enable the data to be received, see picture 16. picture 16. REQ is true. As you can see the SendData is TRUE, but no data was sent because the RecieveData is still false. The PLC_2 will only receive data from PLC_1 only when the ReceiveData is set to true. See picture 17. picture 17. Data is sent to PLC_2 As you can see when the RecieveData is true. Data will be sent from PLC_1 into PLC_2, However, you can see that the data inside the two PLCs are different because the data of PLC_1 changes automatically as per the simple logic we made before. That means the EN_R signal allows the transfer of data one time, when I need to transfer data again this signal has to become false and then true again. Check out the attached TIA Portal project and see the data transfer between PLCs.
  25. In this article, you will learn the PLC example to control LEDs via switches and understand the ladder logic explanation. This PLC example is designed for engineering students to learn and practice the ladder logic. The implementation of the same PLC program for industrial usage will be different. PLC Example Design a PLC ladder logic for the following application. We are using three switches to control three LED’s. If any 1 Switch is ON, then LED I will be ON. If any 2 Switches are ON, then LED II will be ON. If all the 3 Switches are ON, then LED III will be ON. In the previous article, we discussed the same PLC example using toggle switches, Learn the logic. Inputs The required digital inputs are listed below. Switch 1: I0.0 Switch 2: I0.1 Switch 3: I0.2 Outputs The required digital outputs are listed below. Motor 1: Q0.0 Motor 2: Q0.1 Motor 3: Q0.2 Ladder Diagram to Control LEDs Via Switches Ladder Logic Explanation For this application, we have used EcoStruxure Machine Expert Basic v1.2 software for the PLC programming. In the above program, we have used Normally Open Contacts as well as Normally Closed Contacts for Switch 1 (I0.0), Switch 2 (I0.1), and Switch 3 (I0.2) In Rung0, when any 1 switch (Normally Copen Contact) is turned ON and the other 2 switches (Normally Closed Contacts) are OFF, then LED 1 will turn ON. To turn ON LED 2 Rung1, any 2 switches that are as Normally Open Contacts should be ON and the other remaining 1 switch as Normally Closed Contact should be OFF. For LED 3 to be ON, switch 1, switch 2 and switch 3 in Rung2 are connected in series, thus implementing AND logic gate. LED 3 will TURN ON when all the three switches are turned ON. When Any 1 Switch is ON The signal flows through switch 1 as it is in true state. In false state, switch 2 and switch 3 also pass signal to the outputs. Therefore, LED 1 will be ON. LED I will TURN ON when switch 2 is turned ON and switch 1 and switch 3 are OFF as these are in normally closed contact state. When switch 3 will be ON and other 2 switches which are normally closed contacts will be OFF, then LED 1 will turn ON. Turning ON more than one switch will break the circuit. The Normally Closed Contact, when in true state, will not allow signal. As a result, LED 1 will be OFF. When Any 2 Switches are ON LED 2 will TURN ON when switch 1, switch 2 are turned ON and Switch 3 is OFF. The switch 3 as Normally Closed Contact, in false state, will allow signal to pass through it. When switch 1 and switch 3 are turned ON and switch 2 is OFF, LED 2 will turn ON. Switch 2 will allow signal when in false state. The signal flows through switch 2 and switch 3 as these are in true state. In false state, switch 1 also pass signal to the outputs. Therefore, LED 2 will be ON. When more than two inputs are turned ON, the Normally Closed Contact used for the third switch will not close the circuit in true state. Therefore, the LED 2 will get OFF. When All 3 Switches are ON When all the three switches SWITCH 1 (I0.0), SWITCH 2 (I0.1), SWITCH 3 (I0.2) are turned ON, LED 3 will be ON and will turn OFF other Two outputs.
×
×
  • Create New...