LinuxCNC Documentation
This page is 88% translated. Untranslated text is shown in English.

This document provides a reference to the basics of HAL.

1. HAL команды

More detailed information can be found in the man page for halcmd: run man halcmd in a terminal window.

Чтобы просмотреть конфигурацию HAL и проверить состояние контактов и параметров, используйте окно «Конфигурация HAL» в меню «Станок» в AXIS. Чтобы просмотреть статус контакта, откройте вкладку Watch и щелкните каждый контакт, который вы хотите просмотреть, и он будет добавлен в окно просмотра.

Окно конфигурации HAL
Figure 1. Окно конфигурации HAL

1.1. loadrt

The command loadrt loads a real time HAL component. Real time component functions need to be added to a thread to be updated at the rate of the thread. You cannot load a non-realtime component into the realtime space.

loadrt Синтаксис и Пример
loadrt <component> <options>
loadrt mux4 count=1

1.2. addf

The addf command adds a function to a real-time thread. If the StepConf wizard was used to create the configuration, two threads have been created (``base-thread`` and ``servo-thread``).

addf добавляет функцию functname в поток threadname. По умолчанию функции добавляются в том порядке, в котором они находятся в файле. Если position указано, функция добавляется в это место в потоке. Отрицательное значение position указывает положение относительно конца потока. Например, 1 — начало потока, -1 — конец потока, -3 — третий от конца.

Для некоторых функций важно загружать их в определенном порядке, например, функции чтения и записи parport. Имя функции обычно представляет собой имя компонента плюс номер. В следующем примере загружается компонент or2, а show function показывает имя функции or2.

$ halrun
halcmd: loadrt or2
halcmd: show function
Exported Functions:
Owner   CodeAddr  Arg       FP   Users  Name
 00004  f8bc5000  f8f950c8  NO       0   or2.0

You have to add a function from a HAL real time component to a thread to get the function to update at the rate of the thread. Usually there are two threads as shown in this example.

Note

The FP column and the uses_fp parameter are deprecated. All threads now unconditionally save and restore floating point state. The fp/nofp distinction will be removed in a future version.

$ halrun
halcmd: loadrt motmod base_period_nsec=55555 servo_period_nsec=1000000 num_joints=3
halcmd: show thread
Realtime Threads:
     Period  FP     Name               (     Time, Max-Time )
     995976  YES          servo-thread (        0,        0 )
      55332  YES           base-thread (        0,        0 )
  • base-thread (the high-speed thread): This thread handles items that need a fast response, like making step pulses, and reading and writing the parallel port.

  • servo-thread (the slow-speed thread): This thread handles items that can tolerate a slower response, like the motion controller, ClassicLadder, and the motion command handler.

addf Синтаксис и Пример
addf <function> <thread>
addf mux4.0 servo-thread

1.3. initf

The initf command registers a function to run once in realtime context, on a dedicated init cycle of the thread before the cyclic function list runs. It is the realtime-thread analogue of addf, intended for one-shot setup that must execute in the realtime task (for example EtherCAT master activation via lcec.0.activate).

initf adds function functname to the init list of thread threadname. The init list runs once on the first cycle after start, then is drained. The cyclic list begins on the following period. Once the init cycle has run, further initf calls on that thread are rejected. position has the same meaning as in addf.

initf Syntax and Example
initf <function> <thread>
initf lcec.0.activate servo-thread

1.4. loadusr

The command loadusr loads a non-realtime HAL component. Non-realtime programs are their own separate processes, which optionally talk to other HAL components via pins and parameters. You cannot load realtime components into non-realtime space.

Флаги могут быть одним или несколькими из следующих:

-W

дождаться готовности компонента. Предполагается, что компонент имеет то же имя, что и первый аргумент команды.

-Wn <name>

дождаться компонента, который будет иметь заданное <name>. Это применимо только в том случае, если у компонента есть опция имени.

-w

дождаться выхода программы

-i

игнорировать возвращаемое значение программы (с -w)

-n

назвать компонент, если это допустимая опция для этого компонента.

Синтаксис и Примеры loadusr
loadusr <component> <options>
loadusr halui
loadusr -Wn spindle gs2_vfd -n spindle

По-английски это означает loadusr ждет имя шпинделя компонента gs2_vfd имя шпинделя.

1.5. net

The command net creates a connection between a signal and one or more pins. If the signal does not exist net creates the new signal. This replaces the need to use the command newsig. The optional direction arrows <=, => and <=> make it easier to follow the logic when reading a net command line and are not used by the net command. The direction arrows must be separated by a space from the pin names.

Синтаксис и Примеры net
net signal-name pin-name <optional arrow> <optional second pin-name>
net home-x joint.0.home-sw-in <= parport.0.pin-11-in

В приведенном выше примере home-x — это имя сигнала, joint.0.home-sw-in — это контакт Direction IN, <= — необязательная стрелка направления, а parport.0.pin.-11-in — это контакт «Direction OUT». Это может показаться запутанным, но метки входа и выхода для контакта параллельного порта указывают на физический способ работы контакта, а не на то, как он обрабатывается в HAL.

Контакт может быть подключен к сигналу, если он подчиняется следующим правилам:

  • Контакт IN всегда можно подключить к сигналу.

  • Конакт IO можно подключить, если на сигнале нет контакта OUT.

  • Контакт OUT можно подключить только в том случае, если в сигнале нет других контактов OUT или IO.

Одно и то же signal-name можно использовать в нескольких сетевых командах для подключения дополнительных контактов, если соблюдаются приведенные выше правила.

Направление сигнала
Figure 2. Направление сигнала

В этом примере показан сигнал xStep с источником stepgen.0.out и двумя считывателями: parport.0.pin-02-out и parport.0.pin-08-out. По сути, значение stepgen.0.out отправляется в сигнал xStep, а затем это значение отправляется в parport.0.pin-02-out и parport.0.pin-08-out.

#   сигнал    источник            получатель          получатель
net xStep stepgen.0.out => parport.0.pin-02-out parport.0.pin-08-out

Поскольку сигнал xStep содержит значение stepgen.0.out (источник), вы можете использовать тот же сигнал снова, чтобы отправить значение другому получателю. Для этого достаточно использовать сигнал с получателями на другой линии.

#   сигнал       получатель2
net xStep => parport.0.pin-06-out
I/O контакты

Контакт ввода-вывода, такой как encoder.N.index-enable, может быть считан или установлен в соответствии с разрешением компонента.

1.6. setp

The command setp sets the value of a pin or parameter. The valid values will depend on the type of the pin or parameter. It is an error if the data types do not match.

Некоторые компоненты имеют параметры, которые необходимо настроить перед использованием. При необходимости параметры можно установить перед использованием или во время работы. Вы не можете использовать setp на контакте, подключенном к сигналу.

Синтаксис и примеры setp
setp <pin/parameter-name> <value>
setp parport.0.pin-08-out TRUE

1.7. sets

The command sets sets the value of a signal.

Синтаксис и примеры sets
sets <signal-name> <value>
net mysignal and2.0.in0 pyvcp.my-led
sets mysignal 1

It is an error if:

  • Имя сигнала не существует

  • Если у сигнала уже есть источник

  • Если значение не является правильным типом для сигнала

1.8. unlinkp

The command unlinkp unlinks a pin from the connected signal. If no signal was connected to the pin prior running the command, nothing happens. The unlinkp command is useful for trouble shooting.

Синтаксис и примеры unlinkp
unlinkp <pin-name>
unlinkp parport.0.pin-02-out

1.9. Устаревшие команды

Следующие команды устарели и могут быть удалены из будущих версий. Любая новая конфигурация должна использовать команду net. Эти команды включены, поэтому старые конфигурации по-прежнему будут работать.

1.9.1. linksp (устарела)

Команда linksp создает соединение между сигналом и одним контактом.

Синтаксис и примеры linksp
linksp <signal-name> <pin-name>
linksp X-step parport.0.pin-02-out

The linksp command has been superseded by the net command.

1.9.2. linkps (устарела)

Команда linkps создает соединение между одним контактом и одним сигналом. Это то же самое, что и linksp, но аргументы обратные.

Синтаксис и примеры linkps
linkps <pin-name> <signal-name>
linkps parport.0.pin-02-out X-Step

The linkps command has been superseded by the net command.

1.9.3. newsig

команда newsig создает новый сигнал HAL с именем <signname> и типом данных <type>. Тип должен быть бит, s32, u32, s64, u64 или float. Ошибка, если <signame> уже существует.

Синтаксис и примеры newsig
newsig <signame> <type>
newsig Xstep bit

Дополнительную информацию можно найти в руководстве HAL или на страницах руководства halrun.

2. HAL Data

2.1. Bit

A bit value is an on or off.

  • значение bit = true или 1 и false илиr 0 (True, TRUE, true все действительны)

2.2. Float

A float is a floating point number. In other words the decimal point can move as needed.

  • Значения float = 64-битное значение с плавающей запятой, с разрешением примерно 53 бита и более 2 ^ 10 ^ (~ 1000) бит динамического диапазона.

Дополнительную информацию о числах с плавающей запятой см.:

2.3. s32

An s32 number is a whole number that can have a negative or positive value.

  • Значения s32 = целые числа от -2147483648 до 2147483647

2.4. u32

A u32 number is a whole number that is positive only.

  • Значения u32 = целые числа от 0 до 4294967295

2.5. s64

An s64 number is a whole number that can have a negative or positive value.

  • Значения s64 = целые числа от -9,223,372,036,854,775,808 до +9,223,372,036,854,775,807

2.6. u64

A u64 number is a whole number that is positive only.

  • Значения u64 = целые числа от 0 до 18,446,744,073,709,551,615

3. HAL файлы

If you used the Stepper Config Wizard to generate your config you will have up to three HAL files in your config directory.

  • «my-mill.hal» (если ваша конфигурация называется «my-mill»). Этот файл загружается первым, и его не следует изменять, если вы использовали Stepper Config Wizard.

  • custom.hal Этот файл загружается следующим, до загрузки ГИП. Здесь вы помещаете свои собственные команды HAL, которые хотите загрузить до загрузки ГИП.

  • custom_postgui.hal Этот файл загружается после загрузки ГИП. Здесь вы помещаете свои собственные команды HAL, которые хотите загрузить после загрузки ГИП. В нем необходимо разместить любые команды HAL, использующие виджеты PyVCP.

4. HAL Параметр

One pin and two parameters are automatically added to each HAL component when it is created. These allow you to scope the execution time of a component.

.time

Pin time shows in ns how long it took to execute the function.

.tmax

Parameter tmax is the maximum time in ns it took to execute the function.

.tmax-increased

This parameter is set to true for one cycle if tmax increased.

tmax — это параметр чтения/записи, поэтому пользователь может установить его равным 0, чтобы избавиться от первой инициализации во время выполнения функции.

5. Основные логические компоненты

HAL contains several real time logic components. Logic components follow a Truth Table that states what the output is for any given input. Typically these are bit manipulators and follow electrical logic gate truth tables.

Дополнительные компоненты см. в <<sec:hal-comComponents,HAL Components List> или на страницах руководства.

5.1. and2

The and2 component is a two input and-gate. The truth table below shows the output based on each combination of input.

Syntax
and2 [count=N] | [names=name1[,name2...]]
Функции
and2.n
Контакты
and2.N.in0 (bit, in)
and2.N.in1 (bit, in)
and2.N.out (bit, out)
Table 1. Таблица истинности для and2
in0 in1 out

False

False

False

True

False

False

False

True

False

True

True

True

5.2. not

The not component is a bit inverter.

Syntax
not [count=n] | [names=name1[,name2...]]
Функции
not.all
not.n
Контакты
not.n.in (bit, in)
not.n.out (bit, out)
Table 2. Таблица истинности для not
in out

True

False

False

True

5.3. or2

The or2 component is a two input or-gate.

Syntax
or2[count=n] | [names=name1[,name2...]]
Функции
or2.n
Контакты
or2.n.in0 (bit, in)
or2.n.in1 (bit, in)
or2.n.out (bit, out)
Table 3. or2 Таблица истинности
in0 in1 out

True

False

True

True

True

True

False

True

True

False

False

False

5.4. xor2

The xor2 component is a two input xor (exclusive or)-gate.

Syntax
xor2[count=n] | [names=name1[,name2...]]
Функции
xor2.n
Контакты
xor2.n.in0 (bit, in)
xor2.n.in1 (bit, in)
xor2.n.out (bit, out)
Table 4. xor2 Таблица истинности
in0 in1 out

True

False

True

True

True

False

False

True

True

False

False

False

6. Примеры логики

.Example using and2

loadrt and2 count=1
addf and2.0 servo-thread
net my-sigin1 and2.0.in0 <= parport.0.pin-11-in
net my-sigin2 and2.0.in1 <= parport.0.pin-12-in
net both-on parport.0.pin-14-out <= and2.0.out

В приведенном выше примере одна копия and2 загружается в пространство реального времени и добавляется в сервопоток. Следующий контакт pin-11 параллельного порта подключен к биту in0 вентиля"И". Следующий контакт pin-12 подключен к биту in1 вентиля "И". Наконец, мы подключаем выходной бит and2 к параллельному порту pin-14. Итак, следуя таблице истинности для and2, если контакт 11 и контакт 12 включены, то выходной контакт 14 будет включен.

7. Компоненты преобразования

7.1. weighted_sum

The weighted sum converts a group of bits into an integer. The conversion is the sum of the weights of the bits present plus any offset. It’s similar to binary coded decimal but with more options. The hold bit interrupts the input processing, so that the sum value no longer changes.

Синтаксис загрузки компонента weighted_sum
loadrt weighted_sum wsum_sizes=size[,size,...]

Создает группы ``weighted_sum``, каждая с заданным количеством входных битов (размером).

Чтобы обновить weighted_sum, process_wsums должен быть прикреплен к потоку.

Добавьте process_wsums в поток сервопривода
addf process_wsums servo-thread

При этом обновляется компонент weighted_sum.

В следующем примере, копия окна конфигурации AXIS HAL, биты 0 и 2 имеют значение TRUE, они не имеют смещения. Вес (weight) бита 0 равен 1, бита 2 — 4, поэтому сумма равна 5.

Table 5. Контакты компонента weighted_sum
Владелец Type Dir Value Имя

10

бит

In

TRUE

wsum.0.bit.0.in

10

s32

I/O

1

wsum.0.bit.0.weight

10

бит

In

FALSE

wsum.0.bit.1.in

10

s32

I/O

2

wsum.0.bit.1.weight

10

бит

In

TRUE

wsum.0.bit.2.in

10

s32

I/O

4

wsum.0.bit.2.weight

10

бит

In

FALSE

wsum.0.bit.3.in

10

s32

I/O

8

wsum.0.bit.3.weight

10

бит

In

FALSE

wsum.0.hold

10

s32

I/O

0

wsum.0.offset

10

s32

Out

5

wsum.0.sum