LinuxCNC обзор принципа работы и интерфейсов.
LinuxCNC — это набор настраиваемых приложений для управления станками с числовым программным управлением (ЧПУ), 3D-принтерами, роботами, лазерными резаками, плазменными резаками и другими автоматизированными устройствами.
1. Как работает LinuxCNC
LinuxCNC способен обеспечить согласованное управление по 9 осям движения. По своей сути программа состоит из нескольких ключевых компонентов, которые объединены вместе и образуют единую целостную систему:
- графический интерфейс пользователя (GUI), который образует основной интерфейс между оператором, программным обеспечением и самим станком с ЧПУ;
- уровень аппаратной абстракции (HAL), который обеспечивает метод связывания всех различных внутренних виртуальных сигналов, генерируемых и принимаемых LinuxCNC, с внешним миром;
- контроллеры высокого уровня, которые координируют создание и выполнение управления движением станка с ЧПУ, а именно контроллер движения (EMCMOT), контроллер дискретного ввода / вывода (EMCIO) и исполнитель задач (EMCTASK).
На иллюстрации ниже представлена простая блок-схема, показывающая, как может выглядеть типичный 3-осевой фрезерный станок с ЧПУ с шаговыми двигателями:
Компьютер под управлением LinuxCNC отправляет последовательность импульсов через параллельный порт на шаговые приводы, к каждому из которых подключен один шаговый двигатель. Каждый привод получает два независимых сигнала; один сигнал, чтобы дать команду приводу перемещать связанный с ним шаговый двигатель по часовой стрелке или против часовой стрелки, и второй сигнал, который определяет скорость, с которой этот шаговый двигатель вращается.
Проиллюстрированная система шагового двигателя под управлением параллельного порта, система LinuxCNC также может использовать преимущества широкого спектра специализированных аппаратных интерфейсов управления движением для увеличения скорости и возможностей ввода-вывода.
В большинстве случаев пользователи создают конфигурацию, специфичную для настройки своего станка с ЧПУ, используя либо Stepper Configuration Wizard (для систем ЧПУ, работающих с параллельным портом компьютеров), либо Mesa Hardware Wizard (для более продвинутых систем, использующих Mesa Anything I / O PCI карта). Запуск любого из мастеров создаст несколько папок на жестком диске компьютеров, содержащих ряд файлов конфигурации, специфичных для этого станка с ЧПУ, и значок, расположенный на рабочем столе, чтобы облегчить запуск LinuxCNC.
Например, если мастер настройки шагового двигателя использовался для создания настройки для 3-осевого фрезерного станка с ЧПУ, показанного выше и названного My_CNC , папки, созданные мастером, обычно будут содержать следующие файлы:
- Папка: My_CNC
- My_CNC.ini
- Файл INI содержит всю основную информацию об оборудовании, касающуюся работы фрезерного станка с ЧПУ, такую как количество шагов, которые каждый шаговый двигатель должен повернуть, чтобы совершить один полный оборот, максимальная скорость, с которой может работать каждый шаговый двигатель, пределы перемещения каждой оси или конфигурации и поведения концевых выключателей на каждой оси.
- My_CNC.hal
- Этот файл HAL содержит информацию, которая сообщает LinuxCNC, как связать внутренние виртуальные сигналы с физическими соединениями за пределами компьютера. Например, указание вывода 4 на параллельном порту для отправки сигнала направления шага оси Z или указание LinuxCNC прекратить движение двигателя оси X при срабатывании концевого выключателя на выводе 13 параллельного порта.
- custom.HAL
- Настройки конфигурации фрезера, выходящие за рамки мастера, могут быть выполнены путем включения дополнительных ссылок на другие виртуальные точки в LinuxCNC в этот файл HAL. При запуске сеанса LinuxCNC этот файл читается и обрабатывается до загрузки графического интерфейса. Пример может включать в себя инициирование связи Modbus с двигателем шпинделя, чтобы он был подтвержден как работоспособный до отображения графического интерфейса пользователя.
- custom_postgui.hal
- Файл custom_postgui HAL допускает дальнейшую настройку LinuxCNC, но отличается от custom.HAL тем, что он обрабатывается после отображения графического интерфейса пользователя. Например, после установления связи Modbus с двигателем шпинделя в custom.hal LinuxCNC может использовать файл custom_postgui, чтобы связать считывание скорости шпинделя с моторного привода с гистограммой, отображаемой в графическом интерфейсе пользователя.
- postgui_backup.hal
- Он предоставляется в качестве резервной копии файла custom_postgui.hal, чтобы пользователь мог быстро восстановить ранее работавшую конфигурацию postgui HAL. Это особенно полезно, если пользователь хочет снова запустить Мастер настройки под тем же именем My_CNC , чтобы изменить некоторые параметры станка. Сохранение конфигурации в мастере перезапишет существующий файл custom_postgui, а файл postgui_backup останется нетронутым.
- tool.tbl
- Файл таблицы инструментов содержит параметризованный список любых режущих инструментов, используемых на фрезерном станке. Эти параметры могут включать диаметр и длину фрезы и используются для предоставления каталога данных, которые сообщают LinuxCNC, как компенсировать его движение для инструментов разного размера в рамках операции фрезерования.
- My_CNC.ini
- Папка: nc_files
- Папка nc_files предоставляется как место по умолчанию для хранения программ G-кода, используемых для управления станком с ЧПУ. Он также включает ряд подпапок с примерами G-кода.
2. Графические пользовательские интерфейсы LinuxCNC
Графический пользовательский интерфейс — это часть LinuxCNC, с которой взаимодействует оператор станка. LinuxCNC поставляется с несколькими типами пользовательских интерфейсов, которые можно выбрать, отредактировав определенные поля, содержащиеся в файле INI :
Axis — стандартный графический интерфейс клавиатуры. Это также графический интерфейс по умолчанию, запускаемый, когда мастер настройки используется для создания средства запуска значков на рабочем столе:
Touchy — графический интерфейс с сенсорным экраном:
LinuxCNC User Introduction
1. How LinuxCNC Works
LinuxCNC is a suite of highly-customisable applications for the control of a Computer Numerically Controlled (CNC) mills and lathes, 3D printers, robots, laser cutters, plasma cutters and other automated devices. It is capable of providing coordinated control of up to 9 axes of movement.
At its heart, LinuxCNC consists of several key components that are integrated together to form one complete system:
a Graphical User Interface (GUI), which forms the basic interface between the operator, the software and the CNC machine itself;
the Hardware Abstraction Layer (HAL), which provides a method of linking all the various internal virtual signals generated and received by LinuxCNC with the outside world; and,
the high level controllers that coordinate the generation and execution of motion control of the CNC machine, namely the motion controller (EMCMOT), the discrete input/output controller (EMCIO) and the task executor (EMCTASK).
The below illustration is a simple block diagram showing what a typical 3-axis, CNC mill with stepper motors might look like:
A computer running LinuxCNC sends a sequence of pulses via the parallel port to the stepper drives, each of which has one stepper motor connected to it. Each drive receives two independent signals; one signal to command the drive to move its associated stepper motor in a clockwise or anti-clockwise direction, and a second signal that defines the speed at which that stepper motor rotates.
While a stepper motor system under parallel port control is illustrated, a LinuxCNC system can also take advantage of a wide variety of dedicated hardware motion control interfaces for increased speed and I/O capabilities. A full list of interfaces supported by LinuxCNC can be found on the Supported Hardware page of the Wiki.
In most circumstances, users will create a configuration specific to their mill setup using either the Stepper Configuration Wizard (for CNC systems operating using the computers’ parallel port) or the Mesa Hardware Wizard (for more advanced systems utilising a Mesa Anything I/O PCI card). Running either wizard will create several folders on the computers’ hard drive containing a number of configuration files specific to that CNC machine, and an icon placed on the desktop to allow easy launching of LinuxCNC.
For example, if the Stepper Configuration Wizard was used to create a setup for the 3-axis CNC mill illustrated above entitled My_CNC, the folders created by the wizard would typically contain the following files:
The INI file contains all the basic hardware information regarding the operation of the CNC mill such as the number of steps each stepper motor must turn to complete one full revolution, the maximum rate at which each stepper may operate at, the limits of travel of each axis or the configuration and behaviour of limit switches on each axis.
This HAL file contains information that tells LinuxCNC how to link the internal virtual signals to physical connections beyond the computer. For example, specifying pin 4 on the parallel port to send out the Z axis step direction signal, or directing LinuxCNC to cease driving the X axis motor when a limit switch is triggered on parallel port pin 13.
Customisations to the mill configuration beyond the scope of the wizard may be performed by including further links to other virtual points within LinuxCNC in this HAL file. When starting a LinuxCNC session, this file is read and processed before the GUI is loaded. An example may include initiating Modbus communications to the spindle motor so that it is confirmed as operational before the GUI is displayed.
The custom_postgui HAL file allows further customisation of LinuxCNC, but differs from custom.HAL in that it is processed after the GUI is displayed. For example, after establishing Modbus communications to the spindle motor in custom.hal, LinuxCNC can use the custom_postgui file to link the spindle speed readout from the motor drive to a bargraph displayed on the GUI.
This is provided as a backup copy of the custom_postgui.hal file to allow the user to quickly restore a previously-working postgui HAL configuration. This is especially useful if the user wants to run the Configuration Wizard again under the same My_CNC name in order to modify some parameters of the mill. Saving the mill configuration in the Wizard will overwrite the existing custom_postgui file while leaving the postgui_backup file untouched.
A tool table file contains a parameterised list of any cutting tools used by the mill. These parameters can include cutter diameter and length, and is used to provide a catalogue of data that tells LinuxCNC how to compensate its motion for different sized tools within a milling operation.
The nc_files folder is provided as a default location to store the G-code programs used to drive the mill. It also includes a number of subfolders with G-code examples.
2. Graphical User Interfaces
A graphical user interface is the part of the LinuxCNC that the machine tool operator interacts with. LinuxCNC comes with several types of user interfaces which may be chosen from by editing certain fields contained in the INI file:
Axis, the standard keyboard GUI interface. This is also the default GUI launched when a Configuration Wizard is used to create a desktop icon launcher:
Gscreen, a user-configurable touch screen GUI:
GMOCCAPY, a touch screen GUI based on Gscreen. GMOCCAPY is also designed to work equally well in applications where a keyboard and mouse are the preferred methods of controlling the GUI:
NGCGUI, a subroutine GUI that provides wizard-style programming of G code. NGCGUI may be run as a standalone program or embedded into another GUI as a series of tabs. The following screen shot shows NGCGUI embedded into Axis:
3. Virtual Control Panels
As mentioned above, many of LinuxCNC’s GUIs may be customised by the user. This may be done to add indicators, readouts, switches or sliders to the basic appearance of one of the GUIs for increased flexibility or functionality. Two styles of Virtual Control Panel are offered in LinuxCNC:
PyVCP, a Python-based virtual control panel that can be added to the Axis GUI. PyVCP only utilises virtual signals contained within the Hardware Abstraction Layer, such as the spindle-at-speed indicator or the Emergency Stop output signal, and has a simple no-frills appearance. This makes it an excellent choice if the user wants to add a Virtual Control Panel with minimal fuss.
GladeVCP, a Glade-based virtual control panel that can be added to the Axis or Touchy GUIs. GladeVCP has the advantage over PyVCP in that it is not limited to the display or control of HAL virtual signals, but can include other external interfaces outside LinuxCNC such as window or network events. GladeVCP is also more flexible in how it may be configured to appear on the GUI:
4. Languages
LinuxCNC uses translation files to translate LinuxCNC User Interfaces into many languages including French, German, Italian, Finnish, Russian, Romanian, Portuguese and Chinese. Assuming a translation has been created, LinuxCNC will automatically use whatever native language you log in with when starting the Linux operating system. If your language has not been translated, contact a developer on the IRC, the mailing list or the User Forum for assistance.
5. Modes of Operation
When LinuxCNC is running, there are three different major modes used for inputting commands. These are Manual, Auto, and Manual Data Input (MDI). Changing from one mode to another makes a big difference in the way that the LinuxCNC control behaves. There are specific things that can be done in one mode that cannot be done in another. An operator can home an axis in manual mode but not in auto or MDI modes. An operator can cause the machine to execute a whole file full of G-codes in the auto mode but not in manual or MDI.
In manual mode, each command is entered separately. In human terms a manual command might be turn on coolant or jog X at 25 inches per minute. These are roughly equivalent to flipping a switch or turning the hand wheel for an axis. These commands are normally handled on one of the graphical interfaces by pressing a button with the mouse or holding down a key on the keyboard. In auto mode, a similar button or key press might be used to load or start the running of a whole program of G-code that is stored in a file. In the MDI mode the operator might type in a block of code and tell the machine to execute it by pressing the or key on the keyboard.
Some motion control commands are available concurrently and will cause the same changes in motion in all modes. These include Abort, Emergency Stop, and Feed Rate Override. Commands like these should be self explanatory.
The AXIS user interface hides some of the distinctions between Auto and the other modes by making Auto-commands available at most times. It also blurs the distinction between Manual and MDI because some Manual commands like Touch Off are actually implemented by sending MDI commands. It does this by automatically changing to the mode that is needed for the action the user has requested.