Industrial automation is a field of rigor and precision, where every detail makes a difference to process efficiency. On the factory floor, the synchronization between equipment, production lines, and software is built by complex, but almost invisible systems, and the PLC, the key equipment that guarantees reliability, continuity, and operational intelligence, commands this silent operation. Its programming languages, such as those defined by the IEC 61131-3 standard, are optimized to ensure that every command is executed in the correct order and time, without failures.
However, the Industry 4.0 era has brought a new paradigm where the relentless pursuit of efficiency has evolved. Now, industries seek not only to control the present but also to predict the future: anticipate equipment failures, optimize production in real time based on market data, and integrate factories with management systems. It is in this context that Python emerges not as a substitute, but as an operations partner. The programming language acts as a fluid bridge between the ruggedness and determinism of the control hardware, and the flexibility and power of data analysis and operational intelligence.
In this article, we will explore how Python can be integrated into existing automation environments, and we will analyze the advantages and challenges of integration.
The convergence between IT and OT
Historically, OT (Operational Technology) focused on the real-time control of physical machines and processes, using specific hardware and software to ensure safety and continuous operation. In contrast, IT (Information Technology) deals with data, corporate networks, and business management systems (ERP and CRM, for example).
Now, Industry 4.0 seeks to unite these two worlds, enabling data generated by sensors and controllers on the factory floor to be accessed and analyzed by increasingly complex and connected software systems, enabling production optimization, predictive maintenance, and process personalization, and for this fusion to occur effectively, tools are needed that can bridge the gap between the rigorous demands of industrial control and the flexibility of equipment.
IEC 61131-3: the real-time control standard
This global standard defines five programming languages: Structured Text (ST), Function Block Diagram (FBD), Ladder Diagram (LD), Sequential Function Chart (SFC), and Instruction List (IL). Altus' MasterTool IEC XE, for example, is a development environment that natively supports these languages.
The differentiator of IEC 61131-3 lies in its ability to guarantee the deterministic and real-time behavior of control equipment. Its languages are designed for Boolean logic, sequencing, and mathematical calculation tasks in a rugged and predictable way, which is essential for maintaining operational safety. While it is possible to use languages like ST for more complex logic, graphical languages like LD and FBD are better for visualizing and debugging the control flow intuitively. Choosing the right language for the right task is one of the premises of this standard, which has become the main safety requirement in the automation industry.
In contrast, Python, an interpreted programming language, has emerged as a powerful solution for the other end of the spectrum. The use of Python in automation is an increasingly present reality, and its popularity grows thanks to the ability to integrate with different equipment, databases, devices, and platforms. It is especially effective in executing repetitive tasks with simple syntax, high readability, and a vast collection of libraries and frameworks.
Thus, Python is becoming the preferred choice for developers and data analysts who seek agility and efficiency.
Why Python: the power of code in a world of interfaces
Python's programming syntax stands out for facilitating code learning and understanding. For example, while Ladder Diagram (LD) or Structured Text (ST) are ideal for deterministic control logic, Python's concise syntax enables scripts that perform everything from file handling to data analysis to be developed with greater agility.
This ease combined with the other available resources functions as a strategic toolkit for solving complex problems where codes can be used for tasks such as:
- – Communication: To connect with the control hardware, libraries such as PyModbus and OpenOPC are fundamental. They allow Python to act as a communication client, reading and writing variables in PLCs that function as servers.
- – Data analysis: The collection of sensor and process data generates enormous volumes of raw information, but it is necessary to transform this data into knowledge. The NumPy library can be used for high-performance numerical operations, while Pandas offers data structures that facilitate manipulation, cleaning, and analysis.
- – Failure prevention: For the creation of predictive models, the Scikit-Learn library is a standard choice in the industry, as it provides a broad set of classification and clustering algorithms, applicable in areas such as predictive maintenance.
- – Computer vision: In applications involving visual inspection, the OpenCV library provides a rugged set of tools for image and video processing.
Mas, a questão central, então, não é se Python pode substituir as linguagens IEC 61131-3, mas como as duas podem trabalhar juntas para criar arquiteturas mais eficientes e inteligentes. As linguagens IEC são insuperáveis em sua capacidade de controle determinístico, garantindo a segurança e a confiabilidade. O Python, por sua vez, é inigualável em sua capacidade de manipular, analisar e contextualizar grandes volumes de dados, além de automatizar as tarefas de desenvolvimento.
Let's illustrate this complementarity below::
| Feature | IEC 61131-3 | Python |
| Real-time control logic | Ideal. Deterministic reliability, predictable scan cycles, optimized for machine control. | Inadequate. Interpreted language, not deterministic. Ideal for tasks that do not require real-time. |
| Logic complexity | High, but focused on controlling logic and sequencing. | High, but with strong support for complex algorithms, AI, and machine learning. |
| Library ecosystem | Closed environment, with manufacturer-specific libraries. | Vast open ecosystem for data analysis, communication, web, etc. |
| Ease of integration | Focused on industrial protocols like Modbus, Profibus, etc. | Flexibility to integrate with IT APIs, databases, and web services. |
| Learning curve | Requires specific automation knowledge. | Low for basic tasks, but high for complex data applications. |
| Common use | Process control, safety, machine sequencing. | Automation of engineering tasks, data analysis, predictive maintenance, report generation. |
Note: in the MasterTool IEC XE, the software incorporates high-performance libraries specifically developed by the Altus team (such as NextoPIDA or LibMQTT), which, because they are optimized for the hardware and essential for specific functionalities, have closed code, ensuring the system's reliability and stability.
Por outro lado, a plataforma não restringe a criatividade do usuário. É totalmente possível incorporar bibliotecas abertas, aquelas encontradas em comunidades e fóruns de desenvolvimento, e até mesmo criar bibliotecas personalizadas, sob medida para as necessidades exclusivas de cada projeto.
This hybrid model offers the best of both worlds: the security and performance of proprietary libraries for critical control functions, and the adaptability and expansion potential of open and customized libraries for engineering and data integration functions.
Python for equipment engineering
As emphasized before, one of the most significant differentiators of the language, especially in a development environment with a PLC, lies in its readable and easy-to-use syntax. This characteristic accelerates development and facilitates collaboration between teams, as the code can be maintained and shared with greater clarity, and the ability to execute special scripts allows the user to reduce equipment hours and simplify project development stages, such as:
- – File manipulation and report generation: in Python, libraries can automate the creation, organization, and processing of files. This includes extracting data from spreadsheets or CSV files to generate detailed reports, a task that would be susceptible to errors if done manually.
- – Interface control and automated tests: for graphical interface automation tasks, such as filling out forms in a software or performing a sequence of clicks, libraries like PyAutoGUI and PyWinAuto are ideal. They enable scripts to simulate mouse and keyboard interaction, facilitating the creation of automated equipment tests. For web applications, libraries like Selenium and Splinter allow for the creation of tests that simulate user navigation and interaction.
Integrating legacy equipment with new technologies
One of the most challenging realities in automation is the presence of architectures with equipment and equipment from different manufacturers operating side by side. Python offers an integrated solution for this problem, functioning as a universal communication bridge. Instead of trying to force interoperability between different software, a Python script can use specific libraries to communicate with each of them, consolidating data from all sources into a single platform.
Consider, for example, an automated process with different PLCs producing vital data for production monitoring. A Python program can be designed to read the variables from each of these controllers through their respective protocols, transforming the data into a standardized format and storing it in a centralized database. This approach not only solves the problem of communication between distinct equipment but also makes the data accessible for analysis.
Here is a summary of some of the most important libraries for industrial data analysis in Python:
| Library | Main function | Example |
| Pandas | Manipulation and analysis of tabular data. | Cleaning and pre-processing of sensor data, analysis of production logs. |
| NumPy | Numerical computing and operations with multidimensional arrays. | Execution of high-performance mathematical calculations on machine vibration data. |
| Matplotlib | Static data visualization. | Creation of temperature or pressure trend graphs for performance analysis. |
| Scikit-learn | Machine learning. | Training of models for anomaly detection and predictive maintenance. |
| Skforecast | Time series forecasting. | Optimization of equipment failure forecasts and maintenance planning. |
Although Python is not suitable for real-time control, it plays an important role in the communication layer for diagnostic, configuration, and data acquisition tasks with its dedicated libraries. The application of Python in the equipment and equipment interaction layer, therefore, does not compete with the deterministic control code, but complements it.
Saiba mais sobre as bibliotecas de Python: 10 Bibliotecas Python Para Automação e Web Scraping
Connection and Control in MasterTool IEC XE
One of the biggest doubts among automation professionals is how a language like Python can be effectively integrated into an already established and optimized PLC programming environment. The answer to this question lies in the scripting functionality, a feature that operates on a layer above the PLC programming.
It is worth noting that MasterTool IEC XE não possui, especificamente, um ambiente nativo para a execução de scripts Python dentro da lógica de controle do CLP. Esta não é uma limitação, mas sim uma característica de design que promove uma arquitetura de “distinção de funções”. O CLP, programado com as linguagens determinísticas do IEC 61131-3, mantém o funcionamento de tarefas de controle em tempo real e a segurança do sistema.
O Python, por sua vez, atua como um sistema supervisor externo, ou um cliente de dados, interagindo com o CLP por meio de protocolos de comunicação. Essa abordagem previne que os códigos não determinísticos interfiram na execução crítica dos processos, garantindo a integridade do sistema como um todo.
Mas, a chave para essa integração, no entanto, é o CODESYS Development System. A plataforma, na qual o MasterTool está baseado, oferece o plug-in ScriptEngine que permite a automação de comandos e operações complexas do programa através de scripts baseados em IronPython ou Python.NET.
Assim, o ScriptEngine permite que, utilizando Python, uma série de tarefas que, de outra forma, exigiriam a interação manual, sejam automatizadas. Em vez de atuar sobre o código de controle, o ScriptEngine atua sobre o projeto como um todo, manipulando objetos de programação, configurações de hardware e fluxos de trabalho. Assim, é possível criar scripts para carregar, criar, salvar, fechar e compilar projetos, acessar objetos de programação, configurar dispositivos e gerenciar.
Communication between Python and Altus' PLC can be established through open and widely supported protocols, as MasterTool offers compatibility with different protocols, which simplifies and expands the possibilities for integration:
- – Modbus TCP: the MasterTool platform supports the configuration of the Modbus Ethernet protocol, allowing PLC variables to be mapped to Modbus registers. A Python script, using the PyModbus library, can act as a client, reading and writing these registers to monitor or interact with the process.
- – OPC UA: o OPC UA é um protocolo ideal para a troca de grandes volumes de dados e para a integração de sistemas de controle com plataformas de nível superior, como Sistemas de Execução de Manufatura (MES) e Sistemas de Planejamento de Recursos Empresariais (ERP). A biblioteca Python OPC-UA é a ferramenta de referência para a criação de clientes que podem navegar no espaço de endereços do servidor do CLP e ler ou escrever nós de dados.
In addition, to reinforce security the MasterTool platform offers mechanisms such as user and group management for the project and for the PLC itself, in addition to Secure Login, which requires authentication before command execution, ensuring that only authorized scripts and users can interact with the equipment.
The PLC as an Edge Controller: Python execution via Docker
The Docker platform, present in advanced NX PLCs such as NX3008,elevates Python's role in automation, transforming the controller into a powerful Edge Controller, as Docker enables the virtualization and installation of external programs with a Linux operating system directly on the CPU.
Thanks to this architecture, the powerful 64-bit ARM processor of the NX3008, with 1 GHz and 4 GBytes of dedicated memory for Docker, can execute complex Python algorithms locally, without relying on external servers or the cloud. This Edge Computing capability can be a game-changer in operations, as it allows for:
- – On-site data analysis: Libraries like Pandas, NumPy, and even machine learning modules can be executed inside a Docker container. This enables predictive analysis and the processing of large volumes of data (Big Data) to happen at the source, with low latency, which is essential for real-time control and immediate responses to operational changes.
- – Reduced cloud dependency: By executing the intelligence and data processing logic locally, the equipment ensures greater operational reliability and continuity.
- – Advanced customization: Docker support enables the customization of the user's application, going far beyond traditional control logic to include sophisticated data logging and analysis solutions.
Docker, therefore, offers the rugged IT infrastructure necessary for Python to operate in conjunction with the deterministic reliability of the IEC control logic.
The next level of industrial automation
A análise desenvolvida ao longo deste artigo evidencia que o Python não compete com os sistemas determinísticos, mas atua como uma camada de inteligência complementar, se destacando como uma ferramenta poderosa para extrair, processar e interpretar os dados gerados pelos controladores, possibilitando a otimização de processos e o desenvolvimento de sistemas de supervisão mais avançados. E dentro desse contexto, a plataforma do MasterTool da Altus oferece uma base confiável para sustentar essa integração.
The next level of automation is not only about increasingly rugged hardware, but also about the intelligence that directs the operation, combining the precision of control with the flexibility of programming.












