Heterogeneous Multi-core Embedded CNC System

CN120010383BActive Publication Date: 2026-08-14CHONGQING UNIV
View PDF 1 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-02-13
Publication Date
2026-08-14

AI Technical Summary

Technical Problem

[0002]数控系统正朝着多轴联动、智能化、绿色化方向发展,嵌入式数控对处理器的性能、功耗、实时性等指标的需求日益提高,单核处理器已经无法满足嵌入式数控系统日益提高的实时运算性能需求,多处理器分离式架构虽在一定程度上缓解了了性能不足的问题,但仍存在系统结构复杂,维护成本高,处理器间物理通信延迟高、不稳定等缺陷

Benefits of technology

[0028]综上所述,由于采用了上述技术方案,本发明将嵌入式软PLC分为开发子系统和运行子系统部署到多核嵌入式处理器不同核心上,实现了独立于PC运行的嵌入式软PLC,提出并实现了一种对梯形图直接解释执行的方法,无需将梯形图转化为指令表程序,降低了梯形图编译和解释执行的算法复杂度,提高了数控PLC执行效率。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120010383B_ABST
    Figure CN120010383B_ABST
Patent Text Reader

Abstract

This invention proposes an embedded CNC system based on heterogeneous multi-core processors, comprising a development system, a runtime system, and a bus servo drive unit. The data output terminal of the development system is connected to the data input terminal of the runtime system, and the data transmission terminal of the runtime system is connected to the data transmission terminal of the bus servo drive unit. The development system is used for programming and monitoring tasks, while the runtime system is used to execute control logic and control external devices. It receives the compiled control program from the development system and controls the input / output devices in the field according to the instructions in the program, realizing industrial automation control. This invention divides the embedded soft PLC into a development subsystem and a runtime subsystem, deploying them on different cores of a multi-core embedded processor, realizing an embedded soft PLC that runs independently of a PC. It proposes a method for directly interpreting and executing ladder diagrams, eliminating the need to convert ladder diagrams into instruction list programs, reducing the algorithmic complexity of ladder diagram compilation and interpretation, and improving the execution efficiency of the CNC PLC.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of embedded numerical control system technology, and in particular to an embedded numerical control system based on heterogeneous multi-core. Background Technology

[0002] Numerical control systems are developing towards multi-axis linkage, intelligence, and green technology. Embedded CNC systems are increasingly demanding higher performance, power consumption, and real-time capabilities from processors. Single-core processors can no longer meet the ever-increasing real-time computing performance requirements of embedded CNC systems. While multi-processor discrete architectures have alleviated the performance shortage to some extent, they still suffer from drawbacks such as complex system structure, high maintenance costs, and high latency and instability in physical communication between processors. Furthermore, PLCs play a crucial role in CNC machine tool control. The development of embedded soft PLC technology in domestically produced CNC systems has lagged behind, resulting in relatively closed control functions. They can only provide basic components and function instructions, making it difficult to meet the needs of complex logic control. Control program editing largely relies on PC platforms, resulting in low flexibility. Moreover, the program compilation process is cumbersome, the algorithm complexity is high, and the large amount of computation involved in execution leads to high CPU load, affecting system performance and response speed. Summary of the Invention

[0003] The present invention aims to at least solve the technical problems existing in the prior art, and in particular, innovatively proposes an embedded numerical control system based on heterogeneous multi-core.

[0004] To achieve the above-mentioned objectives of the present invention, the present invention provides an embedded CNC system based on heterogeneous multi-core, including a development system, a running system and a bus servo drive unit. The data output terminal of the development system is connected to the data input terminal of the running system, and the data transmission terminal of the running system is connected to the data transmission terminal of the bus servo drive unit.

[0005] The development system, similar to the host computer in a traditional PLC, is used for programming and monitoring. The runtime system, similar to the slave computer in a traditional PLC, executes control logic and controls external devices. It receives the compiled control program from the development system and controls the input / output devices in the field according to the instructions in the program, realizing industrial automation control. Its operation is as follows: the user first writes and debugs the control program in the development system, then calls the compilation module to convert the user program into intermediate code that the runtime system can recognize. The development system transmits the intermediate code to the runtime system through shared memory. The runtime system interprets and executes the intermediate code, and outputs the results of the logical operations to the remote I / O module via EtherCAT, thereby realizing the control of the field devices. During this process, the operating status of the external devices is also periodically fed back to the development system via the bus through inter-core communication between the runtime system and the core for the user to view.

[0006] Preferably, the development system and the runtime system run on two different cores of the same processor. This deployment allows each system to focus on its own task, achieving high real-time performance while improving the integration of the soft PLC system. Data exchange between the development and runtime systems via shared memory ensures overall system reliability and response speed. The development system uses a Cortex-A7 core, and the runtime system uses a Cortex-M4 core. The runtime system may also include a lower-level chip, or it may only use a Cortex-M4 core.

[0007] Preferably, the Cortex-A7 core is used for tasks such as human-computer interaction, code preprocessing, G-code parsing, tool compensation processing, file management, and parameter setting. These task modules have low real-time requirements and are related to graphics display. Therefore, these task modules are divided into a task set and assigned to the Cortex-A7 core for operation.

[0008] The Cortex-M4 core is used for interpolation calculations, position control, bus driving, PLC tasks and other real-time periodic tasks. These tasks are divided into a task set and assigned to the Cortex-M4 core for execution. For real-time bursty tasks such as handwheel control and keyboard response, they are also assigned to the Cortex-M4 core to ensure the system can respond to these tasks in real time.

[0009] Preferably, the Cortex-A7 core and the Cortex-M4 core communicate with each other via shared memory and an inter-core interrupt mechanism. Specifically, this communication is achieved through OpenAMP, a software framework for communication between Linux and RTOS. An inter-core communication driver module is loaded in the Linux kernel, and an inter-core communication driver is installed in the M4 core. Applications on both cores can transfer data by calling the API interfaces provided by the communication components.

[0010] Based on the above software architecture, the system adopts a mechanism that synchronizes interpolation and bus driving. In the interpolation interrupt service function on the M4 end, the program directly sends the position control command to the servo drive unit through the bus, and sends the position and I / O data to the A7 end in the communication service program. The two cores work together to give full play to their respective advantages, achieve a balance between high performance and real-time performance, and meet the various complex and real-time application requirements of CNC systems.

[0011] Preferably, in the development system, the ladder diagram is mapped into multiple structure arrays through an intermediate code conversion unit, one of which stores the information of a ladder level in the ladder diagram; finally, these structure arrays are packaged into data frames and sent to the runtime system.

[0012] After the operating system receives a data frame, the storage management module of the operating system obtains all the information of the ladder diagram by identifying the data frame of the intermediate code. In order to achieve efficient interpretation and execution of the intermediate code, the storage management module records the starting address of the storage unit of each data frame while saving the intermediate code.

[0013] Preferably, the step of mapping the ladder diagram into multiple structure arrays through the intermediate code conversion unit includes: starting from the first element of the main road, scanning horizontally from left to right, and saving the information of the elements in the form of structures in the array according to the position and type of the elements; when a node has a branch, scanning is performed using a depth-first search method, scanning each branch vertically according to the vertical connecting line, and saving the element information structure in the array in order.

[0014] Preferably, it includes:

[0015] (1) Start from the main road of the ladder and scan from left to right. Once a branch node is encountered, move to the next line to make a judgment and determine whether the perpendicular line of the current branch node is the left perpendicular line or the right perpendicular line.

[0016] (2) If it is a left vertical line, determine whether its right side is an output element. If it is, perform the conversion and then return to the previous branch node to scan and convert to the right. If it is not an output element, return directly to the branch node and scan to the right.

[0017] (3) If it is a right vertical line, scan to the left until a left vertical line or left parent line is encountered. The graphic elements between the two vertical lines are parallel modules. The parallel branch is scanned and converted from left to right. At the same time, the number of graphic elements in the branch is recorded, and it is determined whether the branch has a branch node. If it does, continue to execute operation (3). If it does not, after the branch is converted, return to the branch node and continue to scan to the right until the last column of the trunk is converted.

[0018] In this context, the left perpendicular line indicates that the right angle formed by the lines opens to the left, and the right perpendicular line indicates that the right angle formed by the lines opens to the right.

[0019] During the above scanning process, we can calculate the depth of the current step by the number of branch nodes, thereby determining the number of rows in that step. After completing the scanning and conversion of that step, we can directly jump to the row of the trunk road of the next step based on the number of rows occupied by that step, and start the scanning and conversion of the next step. Repeat the above steps until the conversion of all steps is completed.

[0020] As described above, the ladder diagram compilation module (which mainly consists of a logic checking unit and an intermediate code conversion unit) converts each ladder level into a structure array and packages it into a data frame for transmission to the runtime system. When packaging the data for each ladder level, the total number of condition elements and the total number of execution elements for that level must also be added to the data frame for the runtime system to parse and execute. The packaged byte stream information is considered intermediate code. The data frame format for a ladder level includes a frame header, data type, number of condition elements, and number of output elements.

[0021] Preferably, before the ladder diagram is mapped into multiple structure arrays by the intermediate code conversion unit, a logic check is performed by the logic check unit:

[0022] (1) Short circuit: Use the sequential scanning ladder diagram program to find two parallel vertical lines based on the downward cascading mark of the elements, and then count the number of elements between the two parallel lines. If it is zero, it means there is a short circuit error.

[0023] (2) Broken circuit: A broken circuit means that a certain main or branch of the ladder diagram is missing a graphic element. Scan the ladder diagram sequentially and record the position where the graphic element is empty. If there are graphic elements on both the left and right sides, it means that there is a broken circuit error.

[0024] (3) Constant output: A constant output error refers to a situation where there is only an output coil and no normally open or normally closed contact on the main circuit of a certain step of the ladder diagram. Scan each element in sequence and determine its component type. If only the output coil is scanned and no contact is found, it indicates that there is a constant output error.

[0025] (4) Missing parameters for function blocks: For function blocks such as timers or logic operation modules, users need to manually set instructions or parameters. Determine whether the parameters of the function block are default values. If so, this error exists.

[0026] Preferably, the storage management module of the operating system obtains all information about the ladder diagram by identifying the data frames of the intermediate code, including:

[0027] First, following the prescribed communication protocol, the number of conditional elements and execution elements for each ladder level are read from the data frame. The storage structure of each element is read using pointer offset to obtain its type, name, address, and whether it is cascaded downwards. Next, the status of the corresponding registers is read to obtain the on / off state of each conditional element. The on / off state of each conditional element is determined one by one according to the number of elements, and logical operations are performed with the results of the previous stage. Finally, the output condition is determined based on the logical operation results of all conditional elements. If the output condition is met, the corresponding function is called sequentially according to the number of output elements (the corresponding function is: calling functions based on the element status (on or off) in the ladder diagram, and pre-defined functions (set to 1 for on, 0 for off, and parallel / series connections). This allows these elements to participate in logical operations in the code, and the output condition is determined based on the operation results). The value of the software register is modified. If the output condition is not met, the ladder diagram... Figure 1 The process of interpreting and executing each tier is now complete.

[0028] In summary, by adopting the above technical solutions, this invention divides the embedded soft PLC into a development subsystem and a running subsystem, which are deployed on different cores of a multi-core embedded processor. This realizes an embedded soft PLC that runs independently of a PC. It also proposes and implements a method for directly interpreting and executing ladder diagrams, eliminating the need to convert the ladder diagrams into instruction list programs. This reduces the algorithmic complexity of ladder diagram compilation and interpretation, and improves the execution efficiency of CNC PLCs.

[0029] A direct interpretation and execution method for ladder diagram primitive mapping matching is proposed, which simplifies the ladder diagram compilation and interpretation and execution process and improves the system running efficiency.

[0030] Additional aspects and advantages of the invention will be set forth in part in the description which follows, and in part will be obvious from the description, or may be learned by practice of the invention. Attached Figure Description

[0031] The above and / or additional aspects and advantages of the present invention will become apparent and readily understood from the description of the embodiments taken in conjunction with the following drawings, in which:

[0032] Figure 1 This is a schematic diagram of task division in the multi-core CNC system of the present invention.

[0033] Figure 2 This is a block diagram of the system software architecture of the present invention.

[0034] Figure 3 This is a hierarchical diagram of the human-computer interaction function structure of the present invention.

[0035] Figure 4 This is the main page of the human-computer interface coordinates of this invention.

[0036] Figure 5 This is a flowchart of the interface refresh procedure of the present invention.

[0037] Figure 6 This is a schematic diagram of the program directory interface of this invention.

[0038] Figure 7 This is a schematic diagram of the program editing interface of this invention.

[0039] Figure 8 This is a page diagram of the tool length compensation method of the present invention.

[0040] Figure 9 This is a schematic diagram of the tool length compensation value modification window of the present invention.

[0041] Figure 10 This is a schematic diagram of the G-code parsing process of this invention.

[0042] Figure 11 This is a flowchart of the lexical checking process of the present invention.

[0043] Figure 12 This is a flowchart of the syntax checking process of this invention.

[0044] Figure 13 This is a schematic diagram of the G and M instruction storage structure of the present invention.

[0045] Figure 14 This is a schematic diagram of the tool radius compensation model of the present invention.

[0046] Figure 15 This is a schematic diagram of the linear tool radius compensation of the present invention.

[0047] Figure 16 This is a schematic diagram of the radius compensation for the circular arc cutting tool according to the present invention.

[0048] Figure 17 This is a schematic diagram of the linear tool radius compensation for the linear adapter of the present invention.

[0049] Figure 18 This is a schematic diagram of the linear-to-circular-arc tool radius compensation of the present invention.

[0050] Figure 19 This is a schematic diagram of the radius compensation for the circular arc transition to the circular arc tool according to the present invention.

[0051] Figure 20 This is a flowchart of the tool radius compensation program of the present invention.

[0052] Figure 21 This invention relates to the structure of an embedded soft PLC system.

[0053] Figure 22 This is a schematic diagram of the logical structure model of the development system of this invention.

[0054] Figure 23 This is the ladder diagram editing interface of the present invention.

[0055] Figure 24 This is a flowchart of the ladder diagram drawing process of the present invention.

[0056] Figure 25 This is a flowchart of the ladder diagram saving process of the present invention.

[0057] Figure 26 This is a schematic diagram of a ladder diagram short-circuit error according to the present invention.

[0058] Figure 27 This is a schematic diagram of a ladder diagram open circuit error according to the present invention.

[0059] Figure 28 This is a schematic diagram of a ladder diagram with a constant output error.

[0060] Figure 29 This is a schematic diagram illustrating the error of unconfigured parameters in the functional block of this invention.

[0061] Figure 30 This is a schematic diagram of the ladder diagram traversal and storage structure of the present invention.

[0062] Figure 31 This is a schematic diagram of the ladder diagram data frame format of the present invention.

[0063] Figure 32 This is the operating system structure of the present invention.

[0064] Figure 33 This is a schematic diagram of the pipeline operation of the operating system of the present invention.

[0065] Figure 34 This is a ladder diagram for interpreting and executing the ladder.

[0066] Figure 35 This is an example of the ladder diagram steps of the present invention.

[0067] Figure 36 This is a flowchart of the inter-core communication program of the present invention.

[0068] Figure 37 This is a schematic diagram of the inter-core communication program data frame of the present invention.

[0069] Figure 38 This is a schematic diagram of the inter-core communication control command data frame of the present invention. Detailed Implementation

[0070] Embodiments of the present invention are described in detail below. Examples of these embodiments are shown in the accompanying drawings, wherein the same or similar reference numerals denote the same or similar elements or elements having the same or similar functions throughout. The embodiments described below with reference to the accompanying drawings are exemplary and are only used to explain the present invention, and should not be construed as limiting the present invention.

[0071] 1. System software architecture design

[0072] Different cores in a heterogeneous multi-core processor have different architectures and performance characteristics. By employing specific strategies, different types of tasks in a CNC system can be assigned to cores with different architectures, thus providing optimized processing results for different task types. By distributing various tasks across these cores according to a defined strategy, each core can independently execute its assigned task, significantly improving the parallel processing capability of the CNC system. This means the system can handle more tasks simultaneously without being limited by the performance bottleneck of a single-core processor, improving system efficiency and ensuring the real-time performance of critical tasks. A reasonable task allocation strategy is crucial for CNC systems based on heterogeneous multi-core processors. When allocating tasks, it is essential to comprehensively consider the characteristics and requirements of the tasks, as well as the architecture and performance characteristics of the different cores in the heterogeneous multi-core processor.

[0073] This paper utilizes the STM32MP157 heterogeneous multi-core processor, which integrates two different architectures: Cortex-A7 and Cortex-M4. The Cortex-A7 core, as a high-performance application processor, demonstrates exceptional capabilities in handling complex transactions and user interface customization. The Cortex-M4 core, on the other hand, is renowned for its stringent real-time requirements and low power consumption, primarily used for executing real-time tasks and optimizing power performance. This paper leverages the heterogeneous multi-core capabilities of the STM32MP157 to deploy an embedded Linux operating system on the Cortex-A7 core, leveraging its powerful transaction processing capabilities and user interface customization advantages. The FreeRTOS real-time operating system runs on the Cortex-M4 core to meet the demands of real-time tasks for accurate response and low latency, while simultaneously optimizing system power consumption.

[0074] When allocating tasks, this paper adopts a task-characteristic-first allocation strategy: ① Divide the CNC system tasks into multiple subsets according to real-time requirements, and assign different task sets to cores with corresponding performance characteristics; ② Divide tasks that frequently communicate with each other into one subset and assign them to the same core to ensure that the data exchange overhead between cores is minimized; ③ Assign high-priority tasks to cores with better real-time performance to ensure that the system can respond to and process task requests in a timely manner; ④ Balance the load on different processor cores as much as possible. Based on the analysis of the CNC system task characteristics above and the task allocation strategy in this paper, the determined task partitioning diagram is as follows: Figure 1 As shown.

[0075] Human-computer interaction tasks, code preprocessing, file management, parameter setting, and other task modules have lower real-time requirements and are related to graphics display. Therefore, these task modules are divided into one task set and assigned to the Cortex-A7 core for execution. Real-time periodic tasks such as interpolation calculations, position control, and PLC tasks are divided into another task set and assigned to the Cortex-M4 core for execution. For real-time bursty tasks such as handwheel control and keyboard response, they are also assigned to the Cortex-M4 core to ensure the system's real-time response to these types of tasks. In summary, the system software architecture diagram is as follows: Figure 2 As shown.

[0076] In the CNC system software architecture presented in this paper, the Cortex-A7 core runs an embedded Linux 5.4.31 kernel. Multi-tasking is implemented based on Linux, employing a time-slice round-robin scheduling algorithm to handle human-computer interaction, G-code parsing, tool compensation processing, and data management tasks. The Cortex-M4 core is ported to the open-source real-time operating system FreeRTOS, using a fixed-priority preemptive scheduling mechanism to execute bus drivers, interpolation operations, position control, and PLC execution tasks. Inter-core data exchange between the two cores is achieved through shared memory and inter-core interrupt mechanisms. Specifically, communication is implemented through OpenAMP, a software framework for communication between Linux and the RTOS. An inter-core communication driver module is loaded in the Linux kernel, and the inter-core communication driver is implemented in the M4 kernel. Applications on both cores can transmit data by calling the API interfaces provided by the communication components.

[0077] Based on the above software architecture, the system adopts a mechanism that synchronizes interpolation and bus driving. In the interpolation interrupt service function on the M4 end, the program directly sends the position control command to the servo drive unit through the bus, and sends the position and I / O data to the A7 end in the communication service program. The two cores work together to give full play to their respective advantages, achieve a balance between high performance and real-time performance, and meet the various complex and real-time application requirements of CNC systems.

[0078] 2. Implementation of System Functional Modules

[0079] 2.1 Human-Computer Interaction Function Design and Development

[0080] In the construction of embedded CNC systems, a well-designed human-machine interface is crucial to the stability and ease of use of the CNC system. The human-machine interface is responsible for providing users with real-time operating status information, machining process data, and error alarm information, while ensuring that users can complete all operations of the machine tool through the human-machine interface.

[0081] The human-machine interface of the CNC system designed in this paper is developed based on the Qt framework and adopts a multi-level menu. According to the system software modules and functional divisions, the entire system interface is divided into five primary function menus: Position, Program, Tool Compensation, Parameters, and Diagnostics. Each menu has corresponding secondary or tertiary sub-menus. The hierarchical structure of the human-machine interface of the CNC system designed in this paper is as follows: Figure 3 As shown.

[0082] The human-machine interaction function can be divided into four key functional modules: status monitoring, NC program editing and management, tool information management, and soft PLC subsystem.

[0083] 2.1.1 Status Monitoring

[0084] The main interface after system startup is the coordinate interface. This interface primarily serves to display and provide feedback. It returns in real-time the absolute coordinate values ​​of each axis motor on the machine tool, current tool information, and the valid status of commonly used M codes. Simultaneously, users can select and establish coordinate systems via the menu buttons at the bottom of the page. After the workpiece coordinate system is established, the interface will also display the relative coordinate values ​​of the axes to this workpiece coordinate system. In addition, the interface will display the current spindle speed and feed rate information, i.e., the current spindle speed (S value) and feed rate (F value). During actual machining operations, this interface will also provide real-time feedback on the current machining code line, helping users determine which machining instruction is currently being executed. The main coordinate interface is shown below. Figure 4 As shown.

[0085] The HMI program initialization calls relevant driver functions to start the M4 kernel and load the application firmware. After the M4 kernel program starts running, it uses a timer interrupt task to collect the absolute encoder value of the motor, the port status of remote I / O, and operating parameters such as spindle speed and feed rate through the EtherCAT bus. It saves this information into a fixed data structure and transmits it to the HMI program running on the A7 kernel through a virtual serial port. The HMI program receives data frames from the M4 end in real time through the virtual serial port, parses them according to the communication protocol, and updates the data structure variables in the buffer.

[0086] For window refresh, this article uses QTimer from the Qt framework to implement timed refresh of various types of information. By connecting the timeout() function of the QTimer object to the corresponding slot function, and reading the updated structure variable from the buffer and reassigning the information display control in the slot function, timed window refresh can be achieved. The specific program flow is as follows: Figure 5 As shown.

[0087] 2.1.2 NC Program Editing and Management

[0088] The human-machine interface program designed in this paper supports two ways to obtain NC program code. The first is to download the code that has been written on the PC to the CNC system through USB flash drive or serial port transmission. The second is to manually write the code directly on the human-machine interface using the keyboard.

[0089] To facilitate the management of code files in the operating system, this paper designs a file resource management system based on the Qt framework. Users can access and edit files through the program menu interface. The interface is mainly divided into a file display area and a program path area. The file display area presents program files and folders in the system directory in list form. The Qt framework's built-in QDir and QFileInfoList classes are used to distinguish files and folders in the system storage path, and the entryInfoList() function is used to filter file types, displaying only machining program files and folders with the suffixes NC, nc, and txt in the program directory. The program directory interface looks like this: Figure 6 As shown.

[0090] By overriding the double-click event function of the QListView control class, the functionality of opening NC program files by double-clicking was implemented. When the user double-clicks an NC directory list option, the program determines whether the current item is a file or a folder. If it is a folder, it navigates to the folder directory; if it is a program file, the directory list control is hidden, a QPlainTextEdit control is instantiated in this area, and the program content is loaded into it. The user can then edit and modify the content using the keyboard. The program editing page is as follows: Figure 7 As shown.

[0091] 2.1.3 Tool Information Management

[0092] In low-end CNC systems, due to functional limitations, only a single tool is typically supported. However, with the development of CNC technology and the increasing demands of applications, mid- to high-end CNC systems are generally equipped with powered tool magazines to achieve automatic tool changing of multiple tools, thereby improving machining efficiency and flexibility. The embedded CNC system studied in this project is applied to a multi-axis machining center with a powered tool changer, therefore, the possibility of supporting multiple tools must be considered.

[0093] In machining centers and CNC milling machines, tool information mainly includes length compensation values ​​and radius compensation values. Considering that different machining centers are equipped with different numbers of tools, this system allows users to set the number of tools. Each tool can be set with four tool length compensation values ​​and four radius compensation values. The radius compensation values ​​and length compensation values ​​of the corresponding tools can be called through H1-H4 and D1-D4 in the machining program. When the tool length and radius wear down during the machining process, the user can set and modify these compensation values.

[0094] The system's tool information is stored in the system storage as a text file. When the user switches to the tool compensation interface, the program calls the corresponding page initialization function to load and extract the compensation information of all tools from the tool compensation information file. The compensation value of each tool is then displayed to the user in a table format using a QTableWidget control. When the number of tools changes, only the row number of the table control needs to be modified, and the initial tool compensation value data is added according to the row index. The tool length compensation page works as follows: Figure 8 As shown.

[0095] By adding a mouse double-click event capture to the QTableWidget control, users can modify the compensation value by double-clicking to open the parameter settings window, as shown in the example. Figure 9 As shown, users can select the compensation value number to be modified using the ComboBox control. After clicking OK, the compensation value will be updated, and the program will save the updated compensation value in the table to the system storage as a text file.

[0096] 2.2 NC Program Analysis

[0097] CNC machining programs are typically generated by CAD / CAM systems or manually written by engineers and then imported into the control system of CNC machine tools. Machining programs usually consist of a series of numerical control instructions. These instructions describe information such as the geometry of the workpiece, machining path, cutting speed, feed rate, and tool selection. These program instructions cannot be directly executed by the machine tool. They need to be interpreted and processed into data structures that can be recognized by the system's motion control module before subsequent path planning and interpolation calculations can be performed.

[0098] The program interpretation in this system is completed at the Cortex-A7 end of the processor. After the NC program is processed by the code parsing module, it is stored in the buffer in the form of a linked list of structures. Then it enters the tool compensation processing unit to correct the data in the buffer. The obtained instruction set is then sent to the Cortex-M4 end through shared memory. When machining begins, the application program on the Cortex-M4 end decodes these instruction sets and performs speed planning and interpolation calculations to control the machine tool machining.

[0099] 2.2.1 NC Program Code Structure Analysis

[0100] A complete CNC machining program consists of multiple program segments, each containing a series of G-codes, M-codes, and other instructions. These instructions guide the machine tool to perform corresponding actions and operations, thereby completing the machining of the workpiece. Each program segment contains the machining coordinates of the workpiece's outline and also includes auxiliary operations to ensure successful machining. The general format for a program segment is as follows:

[0101] Nxx G__X__Y__Z__I__J__K__R__F__S__T__M__H__D__

[0102] The meanings of each part of the program segment are as follows:

[0103] Nxx: Line numbers, used to identify each line in the program. Although they can be omitted in some simple cases, in practical applications, line numbers are helpful for finding, debugging, and modifying the program.

[0104] G__: G-commands represent motion modes or functions. Each G-command corresponds to a machine tool motion or function. For example, G00 represents rapid positioning, G01 represents linear interpolation, and G02 and G03 represent circular interpolation, etc.

[0105] M__: M commands indicate auxiliary functions or program control. M commands include functions such as starting / stopping the spindle, tool changing, and turning on the coolant. For example, M03 indicates forward spindle rotation, and M05 indicates spindle stop.

[0106] X__Y__Z__: Represents the coordinate values ​​of the workpiece in the corresponding coordinate axis directions. These coordinate values ​​define the position of points on the workpiece, thereby determining the path of the machining tool.

[0107] F__: Feed rate, which defines the speed at which the tool moves along the trajectory during machining.

[0108] S__: Spindle speed, which defines the rotational speed of the spindle.

[0109] T__: Tool number for tool change. When the system includes tool change functionality, this defines the tool number used to select the replacement tool.

[0110] I__J__K__: Offset for circular interpolation, defining the position of the center of the arc relative to the starting point.

[0111] R__: Defines the radius of the arc.

[0112] H__D__: Tool length and radius compensation value number

[0113] The G and M code function instructions include both modal and non-modal types. Non-modal instructions are valid only in the current program line, while modal instructions retain their functionality in their current program line and subsequent program lines until they are replaced by another modal instruction within the same group. The same operation type may contain multiple modal instructions, such as M03 (spindle clockwise), M04 (spindle counter-clockwise), and M05 (spindle stop); these are all modal instructions. The instruction system groups modal instructions of the same type into a modal group, and only one of these groups can be executed at any given time. Modal codes are mainly used to set the machine tool's motion state, operating mode, and some parameters for use in subsequent instructions, thereby simplifying program writing and improving efficiency.

[0114] 2.2.2G Code Analysis Research

[0115] CNC code parsing is one of the crucial tasks in a CNC system. The code parsing module identifies the instructions, parameters, and other information in the G-code file, converting them into a format recognizable by the motion control module. This provides correct instructions and parameters for subsequent machining operations, ensuring the CNC system performs machining as expected. Its main tasks are to identify different types of instructions in the G-code file, such as motion instructions (G-code), auxiliary functions (M-code), and tool compensation, then extract parameter values ​​from the instructions, including coordinates, speed, and compensation values. The extracted instructions and parameters are then validated to ensure they conform to the machine tool's operating range and requirements, avoiding unreasonable instructions or parameters. The G-code parsing process designed in this paper mainly includes three steps: lexical checking, syntax checking, and data extraction.

[0116] Lexical analysis refers to the lexical analysis of G-code files, dividing the character sequences in the file into lexical units, such as instructions and parameters. During lexical analysis, various instructions and parameters need to be identified and converted into internal representations for subsequent syntax analysis and processing. Syntax analysis involves performing syntax analysis on lexical units to check whether they conform to the syntax rules of G-code. During syntax analysis, it is necessary to verify the correctness of the relationships between instructions and parameters, and to identify any syntax errors or unreasonable parts. If syntax errors are found, appropriate error messages need to be provided. Data extraction involves extracting the instructions and data from the G-code and storing them in specific structure variables to facilitate the motion control system in obtaining machining parameter information. The G-code parsing process is as follows: Figure 10 As shown.

[0117] The code parsing module designed in this paper scans the program file line by line. Each line of code is processed through the three steps mentioned above, stored in a structure, and inserted into the structure linked list in the buffer. This process is repeated until the entire program is parsed. The parsed instruction set is then transmitted to the tool compensation module for processing. Finally, the processed instruction set is sent to the M4 terminal in the form of a byte stream, which is then called by the motion control module program for interpolation machining.

[0118] 2.2.3 NC Program Analysis Software Design

[0119] (I) Lexical Analysis

[0120] Lexical checking is a crucial step in the entire code parsing process. Its role is to break down the G-code string into individual lexical units and verify whether the instructions, parameters, and structures in the code conform to the specifications of the G-code language. For example, instructions in G-code typically begin with the letter G or M, followed by one or more numbers, representing different functions or operations. The syntax checker verifies whether the instructions conform to this format requirement to ensure correct recognition and parsing.

[0121] Regular expressions can help us accurately find specific characters or substrings within strings. Given the strict programming conventions and standards of G-code, regular expressions can conveniently and quickly extract key information such as instructions and parameters from G-code. Therefore, this paper uses the QRegExp class of the Qt framework to implement the program design for G-code preprocessing. The workflow diagram of lexical checking is as follows. Figure 11 As shown.

[0122] First, a regular expression pattern table is established according to the programming specifications of G-code. Then, a line of code is read from the program file, separated by newline characters. Each phrase is checked according to the lexical character matching table. If there is a mismatched phrase, it means that the program used instructions that the CNC machine tool cannot recognize, and a pop-up window will display the relevant error message on the human-machine interface. If all phrases in the entire line of code pass the match, the line of code is saved to a string as the source code for the next stage of syntax checking.

[0123] G-code phrases are typically composed of address characters and numbers. Address characters are letters with specific meanings, such as preparation function words (G function words), size words (X, Y, Z), feed function words (F), etc. The number is the digit immediately following the address. Different function words are followed by different numbers with different meanings and value ranges [51-52]. The lexical analysis regular expression designed based on this rule is as follows:

[0124] QRegExp gCodePattern1("[GM]\\d{1,2}"); / / G and M code function words

[0125] QRegExp gCodePattern2("[XYZIJKR][+-]?\\d{1,4}([.]\\d{0,3})?"); / / size character

[0126] QRegExp gCodePattern3("[NFST]\\d{1,4}"); / / Accessibility code

[0127] QRegExp gCodePattern4("^%\\s*$") ; / / Beginning and end of the code segment

[0128] gCodePattern1 is used to match G and M code function words, followed by two integers ranging from 00 to 99. gCodePattern2 is used to match coordinate-related information; size function words can be followed by integers or decimals, ranging from -0000.000 to +9999.999. gCodePattern3 is used to match program segment numbers, feed rates, instruction speeds, etc., followed by unsigned one to four integers. gCodePattern4 is used to match the beginning and end of the program.

[0129] (II) Grammar Check

[0130] After a line of code obtained from the program file undergoes lexical analysis, it enters a syntax check. The syntax check includes verifying that function codes within the same modal group appear only once, and that all function codes appearing in the same line are valid (e.g., whether G00 and G01 appear on the same line, whether coordinate instruction data exists after G00 and G01, and whether tool compensation was canceled during tool changes). The syntax check also uses regular expressions, similar to the lexical check stage. If the line of code passes the syntax check, the passed program segment is saved in a string for data extraction. If it fails, a pop-up window displays the relevant error information on the human-machine interface, prompting the user to correct the program segment. The syntax check process is as follows: Figure 12 As shown

[0131] (III) Data Extraction

[0132] If there are errors in the lexical analysis or syntax checking of the program segment, the user should make the necessary modifications to the program according to the error message. If there are no errors, the code parser will extract the instructions and data in the program segment, including identifying function instructions and extracting the parameter values ​​related to these instructions. Then, the extracted instructions and data are stored in structure variables and stored in a structure linked list. After the entire program is parsed, the linked list is sent to the M4 terminal in the form of a byte stream. When the system needs to perform machining operations, the decoding unit of the motion control module will read the variables in these data structures to obtain the required machining motion parameter information and control the machine tool to perform machining accordingly.

[0133] After extraction is complete, the data storage structure for saving a line of NC code is as follows:

[0134]

[0135] For G and M instructions, this paper uses a flag format for storage. The char data type can represent an 8-bit binary number. A combination of one or more binary digits represents the valid state of an instruction function word. This definition method greatly reduces the data size and can significantly reduce the storage space required in the buffer. The storage structure of G and M instructions is illustrated below. Figure 13 As shown.

[0136] 2.3 Tool radius compensation

[0137] 2.3.1 Concept of Tool Radius Compensation

[0138] The CNC system processes the workpiece according to the motion trajectory parsed by the NC program. The CNC machining code generated by the software is generally designed according to the outline and dimensions of the workpiece. However, in the actual machining process, the tool has a certain radius length, and this radius value will also change as the tool wears during the machining process. Therefore, there will be an offset between the motion trajectory of the tool center and the actual contour trajectory of the workpiece. Therefore, we need to correct the trajectory of the tool center according to this offset so that the actual machined part is consistent with the shape and size of the part expected when programming.

[0139] Tool compensation is divided into left compensation (G41 command) and right compensation (G42 command). When using the G41 command, the tool automatically shifts to the left by a set compensation amount during cutting. Conversely, the G42 command causes the tool to automatically shift to the right by a set compensation amount during cutting. Left compensation is typically used when machining the workpiece clockwise or when the tool is on the left side of the workpiece, while right compensation is typically used when machining counterclockwise or when the tool is on the right side of the workpiece. A schematic diagram of the tool radius compensation model is shown below. Figure 14 As shown.

[0140] 2.3.2 Research on Tool Radius Compensation

[0141] Radius compensation essentially utilizes the coordinate difference between the actual and programmed positions of the tool, employing coordinate transformation to correct the tool's trajectory. Depending on the type of machining contour, it can be categorized into linear tool compensation and circular tool compensation. Based on the transition method between two trajectory segments, it can be further divided into three types: linear-to-linear, linear-to-circular, and circular-to-circular.

[0142] 1. Linear tool radius compensation calculation

[0143] like Figure 15 As shown, point P0(X0,Y0) is the starting point of the workpiece's linear contour trajectory. e (X e ,Y e () is the endpoint of the straight line trajectory, the tool radius is r, and assuming the system is performing tool right compensation, then the compensated straight line trajectory is P'0P'. e Therefore, we need to calculate the starting coordinates P0'(X0',Y0') and ending coordinates P of this trajectory segment. e '(X e ',Y e ').

[0144] Hypothesis vector If the coordinates of P'0 are (ΔX, ΔY), then the coordinates of P'0 can be expressed as (3.1):

[0145]

[0146] And because there is

[0147]

[0148] Therefore, the coordinates of the starting point of the new straight trajectory after tool right compensation are calculated as shown in equation (3.3):

[0149]

[0150] Simply replace the coordinates of point P0 with P e The coordinates of the point can be used to determine the coordinates of the endpoint of the new trajectory after compensation. The above calculation is based on the assumption that the tool is on the right side of the straight line segment for compensation. If the tool is on the left side, the direction of compensation will be reversed, and the coordinates of the left tool compensation starting point P″0 are calculated as shown in equation (3.4):

[0151]

[0152] 2. Calculation of radius compensation for circular arc cutting tools

[0153] like Figure 16 As shown, point A(X) a ,Y a Point B(X) is the starting point of the workpiece's circular arc trajectory. b ,Y b The endpoint of the circular arc trajectory is A′(X′). The origin O is the center of the circular arc trajectory. The radius of the arc is R, and the tool radius is r. Assuming the system performs right tool compensation, the starting point and ending point of the compensated circular arc trajectory are A′(X′). a ,Y′ a ) and B′(X′ b ,Y′ b Their coordinates are calculated as follows:

[0154] Let vector Let the projection on the X-axis be ΔX, and the projection on the Y-axis be ΔY. Then we have...

[0155]

[0156] From geometric relations, we can obtain equation (3.6):

[0157]

[0158] Therefore, the coordinates of the starting point of the new circular trajectory after tool right compensation are calculated as shown in equation (3.7):

[0159]

[0160] Similar to linear compensation, the coordinates of the new arc trajectory endpoint can be obtained simply by substituting the coordinates of point B. If left-hand compensation is performed, the coordinates of the new arc trajectory starting point are calculated as shown in equation (3.8):

[0161]

[0162] 3. Inter-segment transition calculation

[0163] In continuous machining, in order to connect two machining paths, it is necessary to calculate the coordinates of the tool compensation connection point to ensure that the tool can smoothly transition from one path segment to another, avoiding unnecessary pauses or jumps at the connection point.

[0164] (a) Transition between straight lines

[0165] In CNC machining, when two straight line segments are connected, their transition point is the common endpoint of the two lines. When performing tool compensation calculations, for the case of a straight line transitioning to another straight line, the coordinates of the transition point are still determined by the common endpoint of the two lines. For example... Figure 17 As shown:

[0166] The two segments of the continuous machining program are both straight-line trajectories. The new trajectory after adding tool compensation to the first segment AB is A1B1, and the new trajectory after adding tool compensation to the second segment BC is B2C1. Let's assume that the trajectory function of A1B1 is y = k1x + b1, and the trajectory function of B2C1 is y = k2x + b2. By combining the two trajectory functions, we can find the intersection point X of the two trajectories. This intersection point is the transition point of the two straight-line tool-compensated trajectories. The calculation process is shown in equation (3.9).

[0167]

[0168] (b) Transition between straight line and circular arc

[0169] A schematic diagram of a straight line transitioning to an arc is shown below. Figure 18 As shown

[0170] The workpiece trajectory is a straight line AB transitioning to an arc BC, and the intersection point between the two trajectories is B(X). b ,Y b The first straight line trajectory AB, after adding tool compensation, becomes the new trajectory A1B1, and the second circular arc trajectory BC, after adding tool compensation, becomes the new trajectory B2C1. Let's assume the trajectory function of A1B1 is y = kx + b, and the trajectory function of B2C1 is (xm). 2 +(yn) 2 =R 2 , combine the two trajectory functions

[0171]

[0172] The coordinates of the intersection point M of the two trajectories can be obtained by solving:

[0173]

[0174] There are two solutions to the system of equations. As can be clearly seen from the figure, the point closer to point B is the actual intersection point M. Substituting the x-coordinate of M into the trajectory function will give us the coordinate value of M.

[0175] (c) Arc-to-arc transition

[0176] A schematic diagram of a circular arc transition is shown below. Figure 19 As shown:

[0177] The workpiece trajectory is a circular arc AB transitioning to a circular arc BC. The new trajectory after adding tool compensation to the first segment AB is A1B1, and the new trajectory after adding tool compensation to the second segment BC is B1C1. Let's assume that the trajectory function of A1B1 is (x-m1). 2 +(y-n1) 2 =R1 2 The trajectory function of B1C1 is (x-m2). 2 +(y-n2) 2 =R2 2 Solve the system of two trajectory functions simultaneously:

[0178]

[0179] Solving this equation yields equation (3.13):

[0180]

[0181] make

[0182]

[0183] Substituting k and t, we can find the x-coordinate of the transition point M. Similar to the transition from a straight line to an arc, there are two solutions. The point closer to point B is the actual tool-complementary intersection point M. Substituting the x-coordinate of M into the trajectory function, we can obtain the coordinate value of M.

[0184] In tool compensation implementation, the transition (transfer) method of the tool center trajectory from one programming segment to another is further subdivided into three types: extension type, shortening type, and insertion type. Considering the vector angle between the two programming trajectories (the angle between the two programming trajectories at the intersection on the non-machining side) and the different tool compensation directions, there can be as many as 54 transition types. All of these need to be considered when designing the tool compensation algorithm, but they are all based on the above three basic transition types. Due to space limitations, this article will not go into detail here.

[0185] 2.3.3 Design and Implementation of Tool Radius Compensation

[0186] The key to tool radius compensation lies in determining the transition relationship between two consecutive tool paths through the program processing module. In the previous section on the design of the CNC code preprocessing module, data was extracted from the program segments that passed lexical analysis and syntax checking, and the machining data in the NC program segments was saved to a buffer according to a specific data structure. Tool radius compensation processing involves converting the machining path data in the buffer according to the tool center offset. During this process, the data storage structure remains unchanged. The flowchart of the tool radius compensation processing program is shown below. Figure 20 As shown.

[0187] To accurately determine the transition type between two trajectory segments in the NC program code, when implementing tool radius compensation, we first need to continuously read two machining path information segments from the buffer, which are labeled Current_Buffer and Next_Buffer respectively. Next, we parse the G instructions in Next_Buffer. If it does not contain G41 or G42 (i.e., does not contain tool radius compensation instructions), then no special processing is needed for the data in Current_Buffer; it can be directly written to the intermediate file.

[0188] If Next_Buffer contains G41 or G42 instructions, the new toolpath coordinates need to be calculated based on the currently used tool radius and compensation direction (left or right). Then, by analyzing the function words in the two code segments, the transition type of the trajectory can be determined. Based on the transition type, the transition point coordinates of the two trajectories are calculated, and the endpoint coordinates in Current_Buffer and Next_Buffer are updated accordingly, thereby achieving precise correction of the actual tool trajectory.

[0189] After processing the current two code segments, we need to update Current_Buffer and Next_Buffer. Data in Next_Buffer is passed to Current_Buffer as the first code segment to be processed, and the next code segment is read from the buffer as the new Next_Buffer. This process continues until the entire NC program is completed. If a G40 instruction (cancel tool radius compensation) is encountered in a subsequent read of Next_Buffer, tool compensation processing will not be performed.

[0190] 2.4 Research and Implementation of Internuclear Collaboration

[0191] The Cortex-A7 core of this system runs an embedded Linux operating system, performing non-real-time tasks such as human-machine interface, code parsing, and parameter management. The Cortex-M4 core runs a FreeRTOS real-time operating system, performing real-time tasks such as interpolation and bus driving. The two cores communicate with each other through shared memory to achieve coordinated processing between various tasks of the CNC system. The data exchanged between the cores is stored in the shared memory space. After the sending core sends data, it notifies the receiving core through an inter-core interrupt. The application program of the receiving core reads the data from the shared memory and processes it through the interrupt service routine.

[0192] 2.4.1 Design of Inter-core Communication Mechanism

[0193] For the STM32MP157, A7 is called the main processor and M4 is called the coprocessor or remote processor. As mentioned earlier, user programs on A7 and M4 can send data by calling the API provided by RPMsg. However, this requires specifying the RPMsg endpoint, the user data to be sent, the data length (in bytes), and the source or destination address, which is not convenient or flexible. Therefore, this paper adopts the virtual serial port provided by the OpenAMP library to implement this in the program design. The RPMsg communication mechanism is encapsulated into a serial port-like interface. The creation, configuration, and management of the RPMsg channel are encapsulated into a serial port-like API. Applications on both A7 and M4 can send and receive data using serial port operations, but the transmitted data is still stored in shared memory. The flowchart of the program for inter-core data interaction through the virtual serial port in this system is as follows: Figure 36 As shown.

[0194] The system's A7-side human-machine interface application is developed based on Qt. After the A7 kernel boots, the human-machine interface program uses the QProcess class to call the Linux command line to load and run the M4 firmware in the storage unit. In the M4 application, an RPMsg endpoint is created by calling the virtual serial port initialization function VIRT_UART_Init() in the OpenAMP library. When the endpoint's service name matches the name attribute in rpmsg_driver_tty_id_table[] under the Linux kernel source code, the A7 kernel establishes an RPMsg channel, thereby enabling communication between the two kernels. In the applications of both kernels, corresponding callback functions are bound to the virtual serial port. When the virtual serial port receives data, the bound callback function is executed.

[0195] In this system, the data exchanged between the two cores mainly falls into two categories: one is large-volume data such as preprocessed machining program data or compiled PLC programs, whose data frame format is as follows: Figure 37 As shown. Another type is a simple data frame containing system mode switching or processing control command information, whose data frame format is as follows: Figure 38 As shown. To avoid the time overhead caused by frequent inter-core communication, for large amounts of data like the former, A7 sends them to M4 via a virtual serial port. M4 writes them into its dedicated memory. When performing workpiece machining, the data is read from M4's dedicated memory. This avoids frequent interruptions affecting the execution of motion control tasks. For control commands, the M4 application calls the corresponding function module based on the command number.

[0196] 3. Research and Implementation of Soft PLC Subsystem

[0197] 3.1 Soft PLC Structure and Working Principle

[0198] In terms of system structure, soft PLCs share many similarities with traditional PLCs. The overall system is divided into two parts: a development system and a runtime system. The functions of these two parts correspond to the host computer and slave computer in a traditional PLC. The subsystem structure of an embedded soft PLC is as follows: Figure 21 As shown.

[0199] The development system is similar to the host computer in a traditional PLC, primarily responsible for programming and monitoring. It allows users to create and edit the PLC's control logic using a ladder diagram editor. The execution system, on the other hand, is similar to the slave computer in a traditional PLC, mainly responsible for executing the control logic and controlling external devices. It receives the compiled control program from the development system and controls the input / output devices in the field according to the instructions in the program, thereby realizing industrial automation control.

[0200] The development system and the runtime system designed in this paper run on two different cores of the same processor. With this deployment method, the development system and the runtime system can focus on their own tasks, achieving high efficiency and real-time performance while improving the integration of the soft PLC system. The development system and the runtime system exchange data through shared memory to ensure the overall reliability and response speed of the system.

[0201] This paper describes an embedded soft PLC implemented using an embedded microprocessor to handle PLC data and program storage, logic operations, and control. It utilizes a remote I / O module based on the EtherCAT bus to acquire data from field input devices and control output signals. The process involves the user first writing and debugging the control program on the development system. Then, the compilation module converts the user program into intermediate code that the runtime system can recognize. The development system transmits the intermediate code to the runtime system via shared memory. The runtime system interprets and executes the intermediate code, outputting the results of the logic operations to the remote I / O module via EtherCAT, thus controlling the field devices. During this process, the operating status of external devices is periodically fed back to the development system via the bus through inter-core communication between the runtime system and the core, allowing the user to view the data.

[0202] 3.2 Design of Soft PLC Development System

[0203] 3.2.1 Framework of Soft PLC Development System

[0204] PLCs have a variety of programming languages, including ladder diagrams, function blocks, statement lists, sequential function charts, etc.

[57] . Among them, ladder diagram programming is favored by electrical engineers because it is highly similar to the circuit diagram of traditional relay control systems. It uses the terms of contacts, coils, and series and parallel connections of traditional relays, which makes it easier for electrical personnel with a relay control background to understand and apply it. In daily PLC use, ladder diagram programming is also the most widely used. Therefore, this paper adopts ladder diagrams conforming to the IEC61131-3 standard as the programming language for soft PLC functions.

[0205] The development system includes an editing module and a compilation module. The editing module allows users to write and edit control programs in ladder diagram format via a human-machine interface. After the user completes the ladder diagram program editing, the compilation module converts the user-written ladder diagram program into intermediate code that the runtime system can recognize. During this process, the compilation module performs logical checks on the program. If the checks are error-free, the intermediate code is sent to the runtime system via shared memory for interpretation and execution. If errors are found, the user is prompted through the human-machine interface. The logical structure model of the development system is as follows: Figure 22 As shown:

[0206] 3.2.2 Trapezoid Diagram Editing Area Design

[0207] The soft PLC designed in this paper is an embedded soft PLC subsystem within a CNC system. Therefore, its development system software is also based on Qt. The ladder diagram editing function is embedded in the CNC system's human-machine interface program as one of its function menus. Clicking the "Ladder Diagram Editing" button under the diagnostic first-level menu enters the PLC ladder diagram editing interface. When the system enters the ladder diagram editing interface, the function buttons at the bottom of the page will change to graphic element buttons. Different graphic element buttons correspond to different PLC component types. The ">>" key can be used to flip through the graphic element button area. The ladder diagram editing interface is as follows: Figure 23 As shown.

[0208] The ladder diagram editing and display area is implemented using the Qt predefined drawing device class QWidget. To ensure the orderliness and readability of the ladder diagram program, the ladder diagram drawing area is laid out in a grid. Each ladder diagram element occupies one grid, and each grid has fixed coordinates in the drawing area, which can be mapped to the row and column positions of the ladder diagram elements in the drawing area.

[0209] By reimplementing the mouse press event function `mousePressEvent(QMouseEvent*event)` of the `QWidget` class, the coordinates of the mouse click in the ladder diagram drawing area can be obtained. When the user clicks the location where a component is to be placed in the drawing area, the program obtains the coordinates of that location, converts them into row and column position information, and highlights the grid area at that location. The corresponding component can be added to the grid at the mouse click location by clicking the PLC component button in the menu bar. This system uses a 1000*10 grid in the ladder diagram editing area, meaning each ladder diagram program can have a maximum of 1000 lines, with each line containing a maximum of 10 elements.

[0210] The above design approach assigns specific row and column position information to each ladder diagram component, allowing users to intuitively and conveniently edit and modify the ladder diagram program, while reducing the difficulty of storing and converting the program. By obtaining the row and column position information of the components, all components of the entire ladder diagram can be easily saved and converted.

[0211] 3.2.3 Trapezoidal Diagram Element Design

[0212] To achieve ladder diagram drawing, this paper abstracts the ladder diagram components involved in the system into visual elements in the software, namely ladder diagram primitives. These primitives represent the components in the PLC (Programmable Logic Controller) using graphical symbols and attributes. Each primitive corresponds to a specific graphical symbol.

[0213] Considering the diversity of graphical elements, the graphical elements of the CNC system soft PLC designed in this paper are divided into basic instruction graphical elements and function instruction graphical elements according to their instruction functions. An object-oriented design approach is adopted to abstract the common attributes of all graphical elements and create a base class for each element. This base class is built based on Qt's QWidget class. By deriving concrete classes from the base class, unique attributes and methods can be defined according to the characteristics of different graphical elements. A PLCElement class is created to describe the common attributes of all graphical elements. The base class defines common attributes such as element name, element type, and element number, as well as drawing methods. The code is as follows:

[0214]

[0215] In the above base class design, the tool_Type variable represents the component type, the tool_Name variable represents the component name, the tool_Num variable represents the component number, and the tool_Branch variable represents the branch state of the component. Different values ​​of the member variables correspond to different definitions. The comparison between the values ​​and definitions of the class member variables is shown in Table 4.1.

[0216] Table 4.1 Comparison of Values ​​and Definitions of Member Variables in a Element Class

[0217]

[0218] The base class PLCElementBase defines the name, type, and number of each element, which are common attributes of ladder diagram elements. Based on the specific ladder diagram element type (such as input relays, output relays, etc.), specific subclasses can be derived from PLCElement, adding attributes for different element types to each subclass. Each subclass inherits the common attributes of PLCElement and can add its own unique attributes. By reimplementing the drawing event handling function paintEvent(QPaintEvent*event) included in each subclass, the drawing of graphic symbols corresponding to different elements can be achieved.

[0219] This paper categorizes the graphical primitives in the system into simple primitive classes and complex primitive classes. Simple primitive classes refer to those primitives with no parameters or few parameter types. These primitives typically have relatively simple structures and functions, and usually only perform single bitwise operations during interpretation and execution, such as horizontal lines, vertical lines, normally open and normally closed contacts, direct output coils, and set / reset coils. These simple primitive classes inherit from the primitive base class, thus inheriting its common attributes and methods. For simple primitive classes, the internal parameter types are not significantly different from those of the primitive base class; only their unique drawing methods need to be considered, so they will not be discussed here.

[0220] Complex primitives refer to primitives with many parameter types or those used to implement specific logical operations or control functions, such as timers, counters, data comparison, and data shifting. These primitives often have more parameters and more complex logic processing requirements, thus requiring separate data structures to meet these specific needs. Because there are many primitive types, this section will only take the logic operation function block as an example to introduce its class design.

[0221] The logic operation function block is used to process and control input signals and generate output signals according to logical relationships. Through the logic operation function block, the soft PLC can realize complex logical operations such as data comparison, data shifting, and addition, subtraction, multiplication, and division. The class design code of the logic operation function block is as follows:

[0222] class logic_Operation:publicPLCElement

[0223] {

[0224] public:

[0225] logicOperation();

[0226] unsigned char logic_Type;

[0227] unsigned char ctrl_Condition;

[0228] unsigned int Para_A;

[0229] unsigned int Para_B;

[0230] unsigned int Para_C;

[0231] virtual~PLCElementBase();

[0232] }

[0233] The variable `logic_Type` represents the type of logical operation; different values ​​correspond to different logical operation types. The variable `ctrl_Condition` represents the control condition; different control conditions correspond to different operation rules. `Para_A`, `Para_B`, and `Para_C` are the parameters of the function block, where parameter C is always an address. The types of parameters A and B can be addresses or constants, depending on the value of the control condition variable. The two variables, logical operation type and control condition, together determine the specific operation rules of the logical operation. A comparison of the values ​​and definitions of the logical operation type variable is shown in Table 4.2.

[0234] Table 4.2 Comparison of Logical Operation Type Parameter Values ​​and Definitions

[0235]

[0236] 3.2.4 Trapezoid Diagram Editing and Drawing

[0237] When editing a ladder diagram, first click the area where you want to place a component. The program will capture this event, calculate the row and column information of that location within the ladder diagram editing area based on the clicked position, and highlight the corresponding grid. You can then draw the component within that grid by clicking the component button at the bottom of the page. To configure or change the component's properties, simply double-click the component to bring up the component property configuration window. This window allows users to modify and configure component properties, and the corresponding element properties within the grid will be updated. For ease of editing, after editing a component, the pointer will automatically move to the next grid, automatically incrementing the column. If the added component is an output type, horizontal connecting lines will be added to the current column up to the ninth column of the current row, and the output component will be added to the last column. When the number of columns exceeds the maximum limit, the pointer will move to the next row.

[0238] Users can edit and modify ladder diagrams through the above steps. After completion, users need to click the save button at the bottom of the page. The system will prompt whether to save, and users can decide whether to save the changes based on the actual situation. The ladder diagram drawing process is as follows: Figure 24 As shown:

[0239] When designing graphic elements, each element class includes corresponding drawing methods and double-click response functions. When a user clicks the corresponding element button in the menu bar at the bottom of the page, the program calls the drawing function of the corresponding element class based on the button ID, thereby drawing the ladder diagram element in the grid. For element attribute configuration, the program designed an element attribute editing dialog box. When an element is double-clicked, the double-click response function is called, and the attribute values ​​set in the dialog box are updated to the element.

[0240] To facilitate program modification, the system has set up "delete element" and "delete row" buttons in the menu bar at the bottom of the page. The logic is the same as adding elements. First, click on the element to be deleted, and then select the delete button. The program will delete the element instance at the current position according to the current cursor position and refresh the window. The same applies when deleting a row. The program will delete all element instances in the current row according to the current cursor position.

[0241] 3.2.5 Saving and Loading Ladder Diagrams

[0242] In practical applications, users do not frequently modify ladder diagram programs. They typically reuse ladder diagrams that have already been edited and saved in the system. Therefore, to improve operational convenience, this system can save the user-edited ladder diagram code in the system memory as a binary file. This file contains all relevant information about the ladder diagram program, including the structure of the ladder diagram, the position and attributes of each element, and the logical relationships between elements. During system startup initialization, all ladder diagram data is loaded from the aforementioned binary file. Then, based on this data, the corresponding element objects are reconstructed and filled into the corresponding positions, thereby accurately redrawing the previously stored ladder diagram program in the editing area for the user to continue editing or using.

[0243] In ladder diagram programming, there are usually multiple rungs, and each rung contains a series of primitives, such as contacts, coils, and function blocks. To accurately and completely save the entire ladder diagram program, we need to store and process each rung individually. For a single rung, we need to record and store all the primitive information it contains, as well as the logical relationships between these primitives. Considering that each primitive has similar attributes, including type, name, number, and parameters, this paper uses a unified data structure to store primitive attributes for ease of program design. The primitive storage data structure is defined as follows:

[0244] typedef struct

[0245] {

[0246] short row_Num; / / Row number of the component

[0247] short col_Num; / / Column number of the component

[0248] char m_Type; / / Component type

[0249] char m_Name; / / Component name

[0250] short m_Number; / / Component address

[0251] char m_Branch; / / Branch state

[0252] int params[3]; / / Parameter information of the storage element

[0253] short param_Count; / / Number of parameters

[0254] LadderElement

[0255] The primitive storage data structure defined above clearly and completely reflects the primitive information. The `m_Type` member stores the primitive type, `m_Name` stores the primitive name, `m_Number` represents the primitive number, the `params` member stores various parameter information related to the primitive, the `paramCount` member represents the number of parameters and is used to indicate the size of the parameter list, and the `row_Num` and `col_Num` members represent the row and column numbers of the primitive in the ladder diagram editing area, respectively. These two variables are crucial for the positional layout when reconstructing the ladder diagram. This structure can be used to store instances of each primitive class in the ladder diagram.

[0256] To save all the elements in the ladder diagram, additional data structures are needed to store these element structures. This paper chooses to use a simple data structure, an array, to store all the element information in the ladder diagram. When the user finishes writing the ladder diagram and clicks save, the program creates a structure array `LadderElementArray`. Then, starting from the first row and first column of the ladder diagram, it scans each grid sequentially from left to right and top to bottom. If an element class instance exists in the grid, the element information is saved to the structure instance, and the structure instance is added to the `LadderElementArray` array, until the entire ladder diagram editing area has been scanned. The flowchart of the ladder diagram saving program is as follows: Figure 25 As shown.

[0257] To enable the restoration of the ladder diagram during system restart initialization, the aforementioned structure array needs to be saved as a binary file. During system initialization, the program can read the ladder diagram information from this file and reconstruct the primitives. Thanks to the convenience of the Qt framework, Qt provides the QDataStream class for data serialization and deserialization. Therefore, we can use QDataStream to write the structure array containing the ladder diagram program information into a byte stream, thereby achieving serialization and writing it to a file. When the ladder diagram needs to be loaded, the program will read the structure array from the aforementioned binary file through deserialization, and then restore all primitives sequentially based on the structure information in the array.

[0258] 3.2.6 Ladder Diagram Compilation Module

[0259] The ladder diagram compilation module is a core component of the development system. This paper designs a ladder diagram compilation module mainly composed of two parts: a logic checking unit and an intermediate code conversion unit. The logic checking unit is primarily responsible for logically checking the user-written ladder diagram to ensure its correctness and rationality. During this process, the logic checking unit analyzes each element in the ladder diagram and their connections, determining whether there are any logical conflicts or errors. If problems are found, the logic checking unit will display relevant error messages to help the user locate and fix these issues. After the ladder diagram passes the logic check, it enters the intermediate code conversion unit. This unit converts the logic-checked ladder diagram into intermediate code that the running system can recognize. During the conversion process, the program generates the corresponding intermediate code based on the element types and connection relationships of the ladder diagram.

[0260] (I) Logic Check Unit

[0261] During ladder diagram editing, some errors are inevitable, such as short circuits, open circuits, and other syntax and logic errors, or missing function block parameters. These errors may not only cause PLC malfunctions, but may also damage hardware devices in severe cases. Therefore, the compiler module will carefully check the ladder diagram before converting it to ensure its accuracy. The following are common ladder diagram error types and the checking methods described in this article.

[0262] Short circuit: A short circuit occurs when current flows directly through the ladder diagram without undergoing logical processing. This can cause program logic to malfunction, such as... Figure 26 As shown, for short-circuit errors, the method described in this paper is to sequentially scan the ladder diagram program, find two parallel perpendicular lines based on the downward cascading markers of the elements, and then count the number of elements between the two parallel lines. If the count is zero, it indicates a short-circuit error.

[0263] A broken circuit: A broken circuit refers to a situation where a certain main or branch path in a ladder diagram is missing a graphic element, such as... Figure 27 As shown, the method for checking open circuits in this paper is to sequentially scan the ladder diagram and record the positions where the elements are empty. If there are elements on both the left and right sides, it indicates that there is an open circuit error.

[0264] Constant output: A constant output error refers to a situation where a certain step in a ladder diagram has only an output coil but no normally open or normally closed contacts, such as... Figure 28 As shown, the method for checking constant output is to scan each element sequentially and determine its component type. If only the output coil is scanned and there are no contacts, it indicates that there is a constant output error.

[0265] Missing parameters for function blocks: Function blocks such as timers or logic operation modules require users to manually set instructions or parameters. If these are not configured, the ladder diagram execution will be affected. For example, with a comparison module, if no parameters are configured, the element will display the default parameter value (invalid value). Figure 29 As shown, the method for detecting this error is to determine whether the parameter is the default value. If it is, then this error exists.

[0266] (II) Intermediate Code Conversion Unit

[0267] A ladder diagram program consists of several rungs, each of which can be used to implement an independent task or function, such as input detection, logical judgment, and output control. The rungs are divided based on whether there is a parallel relationship between two rows of elements in the program. If there is no parallel relationship between two rows of elements in a ladder diagram, they can be classified as two different rungs. For each rung, the main path of that rung connects all the branches.

[0268] This paper does not use instruction list language as intermediate code. Instead, based on the ladder diagram storage structure introduced above, it proposes a ladder diagram direct interpretation and execution method based on primitive mapping matching. Primitive mapping matching means that the ladder diagram is mapped into a structure array in the intermediate code conversion unit. Taking the ladder level as the conversion unit, the system starts from the first primitive of the main path and scans horizontally from left to right. When a node has a branch, the system scans each branch vertically according to the vertical connection line and saves the primitive information structure into the array in a certain order.

[0269] Following the above approach, each step of the ladder diagram is stored in a structure array. Each element of the array is a pointer to a LadderElement structure. The LadderElement structure instance pointed to by the pointer contains the attribute information of a certain grid element in that step. The ladder diagram traversal and data storage structure instances are shown below. Figure 30 As shown.

[0270] When converting a ladder diagram, for ladder levels without parallel branches, we only need to scan the main path from left to right and save its information in an array as a structure based on the position and type of the elements. For ladder levels with parallel branches, a depth-first search method is used for scanning, which can be divided into the following steps:

[0271] (1) Start scanning from left to right from the main road of the ladder. Once a branch node is encountered, switch to the next line and determine whether the perpendicular line of the current branch node is the left perpendicular line or the right perpendicular line.

[0272] (2) If it is a left vertical line, determine whether its right side is an output element. If it is, perform the conversion and then return to the previous branch node to scan and convert to the right. If it is not an output element, return directly to the branch node and scan to the right.

[0273] (3) If it is a right vertical line, scan to the left until a left vertical line or left parent line is encountered. The elements between the two vertical lines are parallel modules. Scan and transform the parallel branch from left to right, record the number of elements in the branch, and determine whether the branch has a branch node. If it does, continue to execute operation (3). If it does not, return to the branch node after the branch is transformed and continue to scan to the right until the last column of the trunk is transformed.

[0274] Specifically: In Figure 30 In the diagram, the X-side lines are all left perpendicular lines because right angles point to the left, and the Y-side lines are all right perpendicular lines because right angles point to the right. First, enter (1), move X1, X2, and encounter a branch connecting to the next row. According to the rules, enter the next row, move X5 and encounter a branch connecting to the next row, enter the next row, move X7, and there is no branch connecting to the next row. Determine that the branch encountered after moving X7 is a left perpendicular line, and enter rule (2). If the right side of X7 is not an output element, return to the previous branch (second row), scan to the right, and after moving X6, encounter a branch. Determine that it is a left perpendicular line, and the right side of X6 is not an output element, return to the previous branch (first row), scan to the right, and after moving X3, X4, encounter a left perpendicular line. Determine that the right side is an output element, and convert to (1). Once a branch connecting to the next row is encountered... The branch node of the row enters the next row. When a branch is encountered, it enters the second row. When another branch is encountered, it enters the third row. There is no branch node connecting to the next row. It is determined that the branch of the third row is a right vertical line. Enter (3). The third row is scanned to the left until the left bus (main road). The primitives between the two vertical lines are connected in parallel. This means that the output primitive on the right side of the right vertical line of the third row is connected in parallel with the output primitive of the first row. The right side of the right vertical line of the third row is scanned to obtain Y3. Return to the branch node of the second row and continue to execute operation (3). Scan out Y2. Return to the branch node of the first row and execute operation (3) to obtain Y1. The conversion of the last column of the main road (the last column refers to the rightmost column) is completed. The number of rows of the ladder that has just been scanned can be determined according to the number of branch nodes. Enter the next ladder according to the number of rows and repeat the above scanning process.

[0275] During the above scanning process, we can calculate the depth of the current step by the number of branch nodes, thereby determining the number of rows in that step. After completing the scanning and conversion of that step, we can directly jump to the row of the trunk road of the next step based on the number of rows occupied by that step, and start the scanning and conversion of the next step. Repeat the above steps until the conversion of all steps is completed.

[0276] As described above, the compilation module converts each rung into a structure array and packages it into a data frame before sending it to the runtime system. When packaging the data for each rung, the total number of conditional elements and total number of execution elements for that rung must also be added to the data frame so that the runtime system can parse and execute it. The packaged byte stream information is considered intermediate code, and the format of a rung's data frame is as follows: Figure 31 As shown.

[0277] The operating system can directly interpret and execute ladder diagrams by parsing data frames to read the number of conditional elements and output elements contained in a ladder level, as well as all the attributes of the elements contained in that level. This makes it easier to track and locate errors because the processing of each element is independent, so when an element has a problem, it is easier to find the source of the problem. Furthermore, this allows for more customized and integrated element types because all element information is saved in the data structure during the intermediate code conversion stage, allowing for the design of data structures to accommodate different types of elements.

[0278] In contrast, instruction lists, as a more abstract representation, require simplification or approximation of the behavior of certain graphical elements, potentially resulting in the loss of some details or specific functions. Therefore, directly storing element information can expand the richness of element types, thereby reducing the complexity of ladder diagram programming and enabling developers to understand and implement control logic more quickly. More importantly, this method of directly interpreting and executing ladder diagrams can improve the efficiency of logical operations. It can terminate the execution of certain branches early based on logical conditions or skip unnecessary calculations based on input states, thus improving the system's execution efficiency.

[0279] 3.3 Design of Soft PLC Operating System

[0280] The soft PLC operating system designed in this paper consists of a storage management module and an interpretation module. The storage management module receives intermediate code transmitted from the development system and saves it to the dedicated storage of the M4 kernel. When the PLC system starts running, the storage management module reads the corresponding intermediate code from memory and passes it to the interpretation module. The interpretation module reconstructs the intermediate code into graphical information, performs logical operations based on the values ​​of the corresponding software registers, and updates the PLC's input / output registers based on the results of the logical operations, thereby achieving control of external devices. The operating system structure is as follows: Figure 32 As shown

[0281] 3.3.1 Storage Management Module

[0282] The storage management module primarily handles data interaction with the development system. After completing program editing in the development system, the user needs to download the intermediate code to the development system. During the operation of the soft PLC, the status of each relay also needs to be transmitted to the running system in real time. Data interaction between the development system and the running system is achieved through shared memory. When the user completes the ladder diagram editing in the development system's editing interface and clicks the compile button, the development system sends a program transmission request to the running system. Upon receiving this request, the running system sends an acknowledgment signal to the development system, indicating that it is ready to receive the program. Subsequently, the development system sends the intermediate code converted from the ladder diagram to the running system frame by frame, according to a pre-defined communication protocol, in units of ladder levels. Each data frame not only contains all the element information of that ladder level but also indicates the number of conditional elements and execution elements in that ladder level.

[0283] To achieve efficient interpretation and execution of intermediate code, the storage management module records the starting address of each data frame storage unit while saving the intermediate code. When the runtime system needs to read program instructions, it can quickly locate the corresponding storage location. After all program instructions have been received, the runtime system generates an instruction address table in the program storage area. This address table records the location of each level of intermediate code in the storage area. During runtime, the program execution module can quickly retrieve and interpret the intermediate code using pointers based on this address table.

[0284] After the soft PLC starts running, the operating system needs to provide real-time feedback on the effective status of each relay to the development system. This data is also transmitted through shared memory. The operating system adopts a periodic sending mechanism, which is handled by the task scheduling unit of the M4 kernel application. Every 10ms, it sends the data of the current input / output image register to the development system. After receiving the status information, the operating system parses it and reflects the results on the human-machine interface.

[0285] 3.3.2 Data Exchange Area

[0286] To ensure the soft PLC operating system can accurately parse the logical relationships of the intermediate code, the consistency of input data must be ensured within a single scan cycle. During the input sampling phase, all input state data acquired via the bus is saved to memory. In the remaining phases of the scan cycle, regardless of changes in the input state, the data in memory should not be modified until the start of the next sampling cycle. Simultaneously, since the states of output relays and auxiliary relays change during program execution, dedicated memory space is also required to record these states. Therefore, this paper defines a data storage area in memory to store this state data, mainly divided into input registers, output registers, and intermediate registers. The intermediate registers further include auxiliary registers and timer and counter data registers.

[0287] 3.3.3 Explanation of the running module

[0288] The interpretation and execution module is the core of the execution system, primarily responsible for restoring intermediate code into graphical information and performing logical operations. At the start of a scan cycle, the ladder diagram storage management module sequentially reads the PLC program data frames for each ladder level from the program storage area according to the instruction address table mentioned earlier, and performs parsing and logical operations. The execution system employs a classic five-stage pipeline approach when interpreting intermediate code: instruction fetch, instruction decode, register access, execution, and write-back. These five stages operate in parallel; that is, while one stage is processing an instruction, the next stage is already ready to process the next instruction. This significantly reduces the waiting time between instruction executions, improving the overall system throughput and execution efficiency. A schematic diagram of the execution system pipeline is shown below. Figure 33 As shown.

[0289] For a ladder level of a PLC program, the interpretation and execution process involves performing logical operations based on the state of conditional elements and determining whether the output conditions are met. Since the soft PLC system designed in this paper does not use an instruction list as intermediate code, the ladder diagram is directly interpreted and executed according to the "element matching and judgment" approach during decoding and logical operations. "Element matching and judgment" means matching the element attributes of each element in a ladder level, calling the corresponding function to determine the state of the conditional element, and then using bitwise logic operations to determine whether the output conditions are met. If met, all output conditions for that ladder level are executed sequentially; otherwise, the interpretation and execution of the next ladder level begins directly.

[0290] As mentioned earlier, when converting ladder diagrams into intermediate code, all types of primitives use a unified data structure, so the memory space occupied by each primitive is the same. Therefore, after the running system extracts a PLC program data frame for a ladder level, it first reads the number of condition elements and execution elements for that level from the data frame according to the specified communication protocol. It then reads the storage structure of each primitive using pointer offset to obtain its type, name, address, and whether it is cascaded downwards. Next, it reads the status of the corresponding registers to obtain the on / off status of each condition element. Based on the number of condition elements, it judges the on / off status of each condition element one by one and performs logical operations with the results of the previous level. Finally, it judges whether the output conditions are met based on the logical operation results of all condition elements. If the output conditions are met, it calls the corresponding function to modify the value of the software register according to the number of output elements. If the output conditions are not met, the ladder diagram... Figure 1The interpretation and execution process for each ladder level is now complete. After the interpretation and execution module finishes interpreting and executing one ladder level, the runtime system reads the data frame of the next ladder level from the program storage area for parsing and execution, repeating this process until the system stops running. Figure 1 The interpretation and execution process of each tier is as follows: Figure 34 As shown.

[0291] A depth-first scanning approach is adopted when performing logical operations on conditional elements. First, the logical operation results (Res) of all conditional elements are initialized to 1, and Res is used as the first-level logical operation result, meaning the output condition is satisfied by default. Then, starting from the first element of the ladder, each element is matched and judged one by one. During the entire matching and operation process, the logical operation result of each element without branches is always ANDed with the result of the previous element. When matching and judging the conditional elements of the ladder trunk, if a branch node is encountered, the current operation result is pushed onto the stack, and the trunk scanning is stopped. Instead, the scan and matching of the next branch begins. If a branch point is encountered again in a branch, the scanning stops, and the operation result of the current line is pushed onto the stack. After completing the scanning of the current branch, the result of the branch is ORed with the operation result at the top of the stack, and a pop operation is performed. Then, the process continues from the previous branch point, judging the results of the conditional elements and performing logical operations. The above process continues until all input elements are judged and calculated, and the final logical operation result is obtained. If it is 1, it means that the output condition is met; if it is 0, it means that the output condition is not met.

[0292] To illustrate the logical operation process of the running system more specifically, a ladder diagram example will be used below for detailed explanation. The ladder diagram is as follows: Figure 35 As shown: After completing the extraction of primitive information and sampling of input state, the logical operation process of the ladder diagram shown in the figure is as follows.

[0293] 1) Read the values ​​corresponding to X1 and X2 from the input registers sequentially, perform a bitwise AND operation, and push the result Res onto the analog stack. The cascade flag for X2 is 1, so the logic value of the cascade branch must be calculated first;

[0294] 2) Read the value corresponding to X5 from the input register, save it to ConcaLogic1, and push it onto the analog stack. The X5 cascade flag is 1, so the logic value of the cascaded branch must be calculated first.

[0295] 3) Read the value of X7 in the register. There are no components to the right of X7, so the cascade branch judgment is completed. Pop ConcaLogic1 from the analog stack, perform an OR operation between the two and save the result to ConcaLogic1.

[0296] 4) Read the value corresponding to X6 in the register, perform an AND operation with ConcaLogic1, and save the result to ConcaLogic1;

[0297] 5) Pop Res from the simulation stack, perform an OR operation with the variable ConcaLogic1, and save the result back to Res. At this point, the logic values ​​of the cascaded branches have been calculated.

[0298] 6) Read the values ​​of X3 and X4 from the input register in sequence and perform a bitwise AND operation with Res, then save the result to Res;

[0299] 7) Complete the logical operation and output the value of Res to the output register mapped by Y1.

[0300] Although embodiments of the invention have been shown and described, those skilled in the art will understand that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the claims and their equivalents.

Claims

1. An embedded numerical control system based on heterogeneous multi-core architecture, characterized in that, It includes a development system, a runtime system, and a bus servo drive unit. The data output terminal of the development system is connected to the data input terminal of the runtime system, and the data transmission terminal of the runtime system is connected to the data transmission terminal of the bus servo drive unit. The development system is used for programming and monitoring tasks; The operating system is used to execute control logic and control external devices. It receives the compiled control program from the development system and controls the input and output devices on site according to the instructions in the program to realize industrial automation control. The development system includes a ladder diagram compilation module, which consists of a logic checking unit and an intermediate code conversion unit. Before mapping, the logic checking unit performs logic checks on the ladder diagram, including short-circuiting, open-circuiting, constant output, and missing parameters in function blocks. The intermediate code conversion unit maps the ladder diagram into multiple structure arrays, where each structure array stores information about a ladder level. These structure arrays are packaged into a custom data frame format containing a frame header, data type, number of condition elements, and number of output elements, and sent to the runtime system via shared memory. The operating system includes a storage management module and an interpretation and execution module. The storage management module obtains all information of the ladder diagram by identifying the data frames of the intermediate code. While saving the intermediate code, it records the starting address of the storage unit of each data frame and generates an instruction address table. The interpretation and execution module directly interprets and executes the ladder diagram using a primitive matching judgment method, without converting the ladder diagram into an instruction table program. The interpretation and execution module reads the data frames of each ladder level sequentially from the program storage area according to the instruction address table. It reads the storage structure of each primitive using a pointer offset method to obtain its type, name, address, and whether it is cascaded downwards. It judges the on / off state of each condition element one by one according to the number of condition elements, and performs logical operations with the result of the previous level. Finally, it judges whether the output condition is satisfied based on the logical operation results of all condition elements.

2. The embedded CNC system based on heterogeneous multi-core according to claim 1, characterized in that, The development system and the runtime system run on two different cores of the same processor. The development system uses a Cortex-A7 core, and the runtime system uses a Cortex-M4 core.

3. The embedded CNC system based on heterogeneous multi-core according to claim 2, characterized in that, The Cortex-A7 core is used for human-machine interaction tasks, code preprocessing, G-code parsing, tool compensation processing, file management, and parameter setting; the Cortex-M4 core is used for interpolation calculations, position control, bus driving, and PLC tasks.

4. An embedded CNC system based on heterogeneous multi-core according to claim 2, characterized in that, The Cortex-A7 core and the Cortex-M4 core communicate with each other through shared memory and an inter-core interrupt mechanism. Specifically, they communicate through a virtual serial port provided by the OpenAMP framework, encapsulating the RPMsg communication mechanism into a serial port-like interface. Applications on both the A7 and M4 sides send and receive data using serial port operations, and the transmitted data is stored in shared memory.

5. An embedded CNC system based on heterogeneous multi-core according to claim 1, characterized in that, The Cortex-M4 core employs a mechanism that synchronizes interpolation operations with bus driving. In the interpolation interrupt service function, the program directly sends position control instructions to the servo drive unit via the bus, and in the communication service program, it sends position and I / O data to the A7 terminal.

6. An embedded CNC system based on heterogeneous multi-core according to claim 5, characterized in that, The process of mapping the ladder diagram into multiple structure arrays through the intermediate code conversion unit includes: starting from the first element of the main path, scanning horizontally from left to right, and saving the information of the elements in the form of structures into the array according to the position and type of the elements; when a node has a branch, scanning is performed using a depth-first search method, scanning each branch vertically according to the vertical connecting line, and saving the element information structure into the array in order.

7. An embedded CNC system based on heterogeneous multi-core according to claim 6, characterized in that, include: (1) Start from the main road of the ladder and scan from left to right. Once a branch node is encountered, switch to the next line to make a judgment and determine whether the perpendicular line of the current branch node is the left perpendicular line or the right perpendicular line. (2) If it is a left vertical line, determine whether its right side is an output element. If it is, perform the conversion and then return to the previous branch node to scan and convert to the right. If it is not an output element, return directly to the branch node and scan to the right. (3) If it is a right vertical line, scan to the left until a left vertical line or left parent line is encountered. The graphic elements between the two vertical lines are parallel modules. The parallel branch is scanned and converted from left to right. At the same time, the number of graphic elements in the branch is recorded, and it is determined whether the branch has a branch node. If it does, continue to execute operation (3). If it does not, after the branch is converted, return to the branch node and continue to scan to the right until the last column of the trunk is converted. In this context, the left perpendicular line indicates that the right angle formed by the lines opens to the left, and the right perpendicular line indicates that the right angle formed by the lines opens to the right.

8. An embedded CNC system based on heterogeneous multi-core according to claim 1, characterized in that, The interpretation and execution module uses a five-stage pipeline to interpret and execute the ladder diagram. The five-stage pipeline includes instruction fetch, instruction decoding, register access, execution, and write-back. The five stages work in parallel, so when one stage is processing an instruction, the next stage is ready to process the next instruction.

9. An embedded CNC system based on heterogeneous multi-core according to claim 1, characterized in that, The explanation and operation module adopts a depth-first scan combined with a simulated stack mechanism when performing logical operations on conditional elements: First, it initializes the logical operation results of all conditional elements to 1 as the first-level logical operation result, and then matches and judges them one by one starting from the first element of the ladder. The logical operation result of each element without branches is always ANDed with the result of the previous element. When a branch node is encountered, the current operation result is pushed onto the stack and the trunk scan is stopped to enter the next branch to start a new scan. After the current branch scan is completed, the result of the branch is ORed with the result of the operation at the top of the stack and a pop operation is performed; the above process continues until the judgment and operation of all input elements are completed, and the final logical operation result is obtained.

10. An embedded CNC system based on heterogeneous multi-core according to claim 1, characterized in that, When saving intermediate code, the storage management module of the operating system generates an instruction address table in the program storage area. This address table records the location of each level of intermediate code in the storage area. The program execution module quickly retrieves the intermediate code for interpretation and execution using pointers based on this address table.

Citation Information

Patent Citations

  • Ladder diagram matrix compiling and interpreting method based on PLC

    CN104820393A