СИНОПСИС
См. раздел config modparam ниже для настройки карты Mesa. Обычно хостmot2 загружается без параметров, если не требуется отладка.
loadrt hostmot2 [ debug_idrom=N ] [ debug_module_descriptors=N ] [ debug_pin_descriptors=N ] [ debug_modules=N ]
- debug_idrom [по умолчанию: 0]
-
Только для разработчиков/отладки! Включите ведение журнала отладки заголовка IDROM HostMot2.
- debug_module_descriptors [по умолчанию: 0]
-
Только для разработчиков/отладки! Включает ведение журнала отладки дескрипторов модулей HostMot2.
- debug_pin_descriptors [по умолчанию: 0]
-
Только для разработчиков/отладки! Включает ведение журнала отладки дескрипторов контактов HostMot2.
- debug_modules [по умолчанию: 0]
-
Только для разработчиков/отладки! Включает ведение журнала отладки используемых модулей HostMot2.
- use_serial_numbers [по умолчанию: 0]
-
При создании контактов HAL для устройств с smart-serial интерфейсом называйте контакты по серийному номеру платы, а не по тому, к какой плате и порту они подключены. Если для этой опции установлено значение 1, контакты будут иметь имена типа
hm2_8i20.1234.current, а неhm2_5i23.0.8i20.0.1.current. Идентификатор состоит из последних 4 цифр серийного номера платы, который обычно указан на наклейке на плате. Это сделает конфигурации менее переносимыми, но означает, что платы можно будет повторно подключать менее осторожно.
ОПИСАНИЕ
hostmot2 — это драйвер устройства, который связывает прошивку Mesa или Litehm2 HostMot2 с LinuxCNC HAL. Этот драйвер сам по себе ничего не делает, платы, на которых фактически работает прошивка, требуют собственных драйверов, прежде чем что-либо произойдет. В настоящее время доступны драйверы для карт с интерфейсом PCI, Ethernet, SPI и EPP.
Прошивка HostMot2 предоставляет такие модули, как энкодеры, генераторы ШИМ, генераторы step/dir и контакты ввода-вывода общего назначения (GPIO). Эти вещи называются «Модули». Во время компиляции встроенное ПО настраивается так, чтобы предоставлять ноль или более экземпляров каждого из этих модулей.
Контакты ввода/вывода платы
Прошивка HostMot2 работает на плате FPGA. Плата взаимодействует с компьютером через PCI, Ethernet, SPI или EPP, а также взаимодействует с оборудованием управления движением, таким как сервоприводы и шаговые двигатели, через контакты ввода-вывода на плате.
Каждый контакт ввода-вывода во время загрузки драйвера платы может быть настроен для использования одной из двух целей: либо в качестве конкретного контакта конкретного экземпляра модуля (encoder, pwmgen, Stepgen и т. д.), либо в качестве цифрового контакта ввода-вывода общего назначения. По умолчанию все экземпляры модулей включены, и все контакты платы используются экземплярами модуля.
Пользователь может отключить экземпляры модуля во время загрузки драйвера платы, указав modparam строки конфигурации hostmot2. Любые контакты, принадлежащие отключенным экземплярам модуля, автоматически становятся GPIO.
Все контакты ввода-вывода имеют некоторое присутствие HAL, независимо от того, принадлежат ли они к активному экземпляру модуля или являются полными GPIO. GPIO можно переключать (во время выполнения) между входами, нормальными выходами и открытыми стоками, а также иметь гибкий интерфейс HAL. Контакты ввода-вывода, принадлежащие активным экземплярам модуля, ограничены требованиями модуля-владельца и имеют более ограниченный интерфейс в HAL. Это описано в разделе «Ввод-вывод общего назначения» ниже.
config modparam
Все модули драйверов платы (hm2_pci, hm2_eth и т. д.) во время загрузки принимают modparam в виде массива строк с именем "config". Этот массив имеет одну строку конфигурации для каждой платы, которую должен использовать драйвер. Строка конфигурации каждой платы передается и анализируется драйвером hostmot2, когда драйвер платы регистрирует плату.
Строка конфигурации может содержать пробелы, поэтому обычно рекомендуется заключить ее в двойные кавычки (символ ").
Символ запятой (,) отделяет элементы массива конфигурации друг от друга.
Например, если на вашем управляющем компьютере есть одна 5I20 и одна 5I23, вы можете загрузить драйвер hm2_pci с помощью команды HAL (в halcmd) примерно так:
loadrt hm2_pci config="firmware=hm2/5i20/SVST8_4.BIT num_encoders=3 num_pwmgens=3 num_stepgens=3,firmware=hm2/5i23/SVSS8_8.BIT sserial_port_0=0000 num_encoders=4"
Примечание: Предполагается, что драйвер hm2_pci сначала обнаруживает 5I20, а затем 5I23. Если порядок обнаружения не соответствует порядку строк конфигурации, драйвер hostmot2 откажется загружать прошивку, а драйвер платы (hm2_pci и т. д.) не сможет загрузиться. Насколько мне известно, невозможно предсказать порядок, в котором платы PCI будут обнаружены драйвером, но порядок обнаружения будет постоянным, пока платы PCI не будут перемещаться. Лучше всего попробовать загрузить его и посмотреть, каков порядок обнаружения.
Допустимые записи в строке формата:
-
[firmware=F]
-
[num_dplls=N]
-
[num_encoders=N]
-
[ssi_chan_N=abc%nq]
-
[biss_chan_N=abc%nq]
-
[fanuc_chan_N=abc%nq]
-
[num_inmux=N]
-
[num_inms=N]
-
[num_resolvers=N]
-
[num_pwmgens=N]
-
[num_3pwmgens=N]
-
[num_oneshots=N]
-
[num_periodms=N]
-
[num_rcpwmgens=N]
-
[num_stepgens=N]
-
[stepgen_width=N]
-
[sserial_port_0=00000000]
-
[num_bspis=N]
-
[num_leds=N]
-
[num_ssrs=N]
-
[num_outms=N]
-
[num_xy2mods=N]
-
[enable_raw]
- firmware [опционально]
-
Загрузите прошивку, указанную буквой F, в FPGA на этой плате. Если строка "firmware=F" не указана, FPGA не будет перепрограммироваться, но может продолжать использовать ранее загруженную прошивку.
Запрошенную прошивку _F_получает программа udev, которая ищет прошивку в системном пути поиска прошивки, обычно /lib/firmware. _F_обычно имеет форму "hm2/<BoardType>/file.bit"; типичное значение _F_может быть "hm2/5i20/SVST8_4.BIT". Файлы прошивки hostmot2 поставляются с пакетами прошивки hostmot2, доступными на linuxcnc.org , и обычно их можно установить, введя команду "sudo apt-get install hostmot2-firmware-5i23", чтобы установить файлы поддержки, например, для 5I23.
Карты FPGA более поздней версии поставляются с предварительно запрограммированной прошивкой, и с этими картами не следует использовать строку "firmware=". Для смены прошивки на этих картах следует использовать утилиту "mesaflash". Совершенно правильно и разумно загружать эти карты вообще без строки конфигурации.
- num_dplls [опционально, по умолчанию: -1]
-
hm2dpll — это модуль таймера с фазовой автоподстройкой частоты, который можно использовать для уменьшения колебания времени выборки и записи для некоторых модулей hm2. Этот параметр можно использовать для отключения hm2dpll, установив его число равным 0. Существует только один модуль этого типа с 4 каналами таймера, поэтому другие допустимые числа: -1 (разрешить все) и 1, и то и другое в конечном итоге означает одно и то же.
- num_encoders [опционально, по умолчанию: -1]
-
Включите только первые N энкодеры. Если N равно -1, все энкодеры включены. Если N равно 0, энкодеры не включены. Если N больше, чем количество энкодеров, доступных в прошивке, плата не сможет зарегистрироваться.
- ssi_chan_N [опционально, по умолчанию: ""]
-
Указывает, как будет интерпретироваться поток битов от устройства Synchronous Serial интерфейса. Для каждого подключенного устройства должна быть запись. Будут включены только каналы со спецификатором формата (поскольку программное обеспечение не может угадать скорость передачи данных и длину битов).
- biss_chan_N [опционально, по умолчанию: ""]
-
Что касается ssi_chan_N, то для устройств BiSS.
- fanuc_chan_N [опционально, по умолчанию: ""]
-
Указывает, как будет интерпретироваться битовый поток от абсолютного энкодера Fanuc. Для каждого подключенного устройства должна быть запись. Будут включены только каналы со спецификатором формата (поскольку программное обеспечение не может угадать скорость передачи данных и длину битов).
- num_resolvers [опционально, по умолчанию: -1]
-
Включите только первые N резольверов. Если N = -1, то все резольверы включены. Этот модуль не работает с универсальными резольверами (в отличие от модуля энкодера, который работает с любым энкодером). На момент написания эта функция Hostmot2 Resolver работает только с картой Mesa 7I49.
- num_pwmgens [опционально, по умолчанию: -1]
-
Включите только первые N pwmgens. Если N равно -1, все pwmgens включены. Если N равно 0, pwmgens не включены. Если N больше количества генераторов импульсов, доступных в прошивке, плата не сможет зарегистрироваться.
- num_3pwmgens [опционально, по умолчанию: -1]
-
Включите только первые N трехфазных pwmgens. Если N равно -1, все 3pwmgen включены. Если N равно 0, pwmgens не включены. Если N больше количества pwmgens, доступных в прошивке, плата не сможет зарегистрироваться.
- num_rcpwmgens [опционально, по умолчанию: -1]
-
Включите только первые N pwmgen RC. Если N равно -1, все rcpwmgen включены. Если N равно 0, rcpwmgen’ы не включены. Если N больше количества rcpwmgen, доступного во встроенном ПО, плата не сможет зарегистрироваться.
- num_stepgens [опционально, по умолчанию: -1]
-
Включите только первые N stepgens. Если N равно -1, все stepgens включены. Если N равно 0, stepgens не включены. Если N больше количества stepgens, доступных в прошивке, плата не сможет зарегистрироваться.
- num_xy2mods [опционально, по умолчанию: -1]
-
Включите только первые N xy2mods. Если N равно -1, все xy2mods включены. Если N равно 0, xy2mods не включены. Если N больше, чем количество модулей xy2, доступных в прошивке, плата не сможет зарегистрироваться.
- stepgen_width [опционально, по умолчанию: 2]
-
Используется для маскировки дополнительных, нежелательных контактов Stepgen. Для шаговых приводов обычно требуется только два контакта (step и dir), но Stepgen Hostmot2 может управлять до 8 выходными контактами для специализированных приложений (в зависимости от прошивки). Этот параметр применяется ко всем экземплярам Stepgen. Неиспользуемые замаскированные контакты будут доступны как GPIO.
- sserial_port_N (N = 0 .. 3) [опционально, по умолчанию: 00000000 для всех портов]
-
Up to 32 Smart Serial devices can be connected to a Mesa Anything I/O board, depending on the firmware used and the number of physical connections on the board. These are arranged in 1-4 ports (N) of 1 to 8 channels. Some Smart Serial (SSLBP) cards offer more than one load-time configuration, for example all inputs, or all outputs, or offering additional analogue input on some digital pins. To set the modes for port 0 use for example sserial_port_0=0120xxxx. A "0" in the string sets the corresponding channel to mode 0, a "1" to mode 1, and so on up to mode 9. An "x" in any position disables that channel and makes the corresponding FPGA pins available as GPIO. The string can be up to 8 characters long, and if it defines more modes than there are channels on the port then the extras are ignored. Channel numbering is left to right so the example above would set sserial device 0.0 to mode 0, 0.1 to mode 1, 0.2 to mode 2, 0.3 to mode 0 and disables channels 0.4 onwards. The sserial driver will auto-detect connected devices, no further configuration should be needed. Unconnected channels will default to GPIO, but the pin values will vary semi-randomly during boot when card-detection runs, to it is best to actively disable any channel that is to be used for GPIO. See sserial(9) for more information.
- num_bspis [опционально, по умолчанию: -1]
-
Включите только первые N драйверов SPI с буферизацией. Если N равно -1, то все драйверы включены. Каждый драйвер BSPI может адресовать 16 устройств.
- num_leds [опционально, по умолчанию: -1]
-
Включите только первые N светодиодов на плате FPGA. Если N равно -1, то для всех светодиодов будут созданы контакты HAL. Если N=0, то контакты добавляться не будут.
- num_ssrs [опционально, по умолчанию: -1]
-
Включите только первые N модулей SSR на плате FPGA. Если N равно -1, то будут созданы контакты HAL для всех выходов SSR. Если N=0, то контакты добавляться не будут.
- enable_raw [опционально]
-
Если указано, включается режим необработанного доступа, в котором пользователь может просматривать и скачивать прошивку из HAL. См. режим Raw ниже.
dpll
The hm2dpll module has pins and parameters like hm2_<BoardType>.<BoardNum>.dpll It is likely that the pin-count will decrease in the future and that some pins will become parameters. This module is a phase-locked loop that will synchronise itself with the thread in which the hostmot2 "read" function is installed and will trigger other functions that are allocated to it at a specified time before or after the "read" function runs. This can be applied to the three absolute encoder types, quadrature encoder, stepgen, and xy2mod. In the case of the absolute encoders this allows the system to trigger a data transmission just prior to the time when the HAL driver reads the data. In the case of stepgens, quadrature encoders, and the xy2mod, the timers can be used to reduce position sampling jitter. This is especially valuable with the ethernet-interfaced cards.
Pins:
- .NN.timer-us (real, in)
-
This pin sets the triggering offset of the associated timer. There are 4 timers numbered 01 to 04, represented by the NN digits in the pin name. The units are microseconds (µs). Generally the value for reads will be negative, and positive for writes, so that input data is sampled prior to the main hostmot read and output data is written some time after the main hostmot2 read.
For stepgen and quadrature encoders, the value needs to be more than the maximum variation between read times. -100 will suffice for most systems, and -50 will work on systems with good performance and latency.
For serial encoders, the value also needs to include the time it takes to transfer the absolute encoder position. For instance, if 50 bits must be read at 500 kHz then subtract an additional 50/500 kHz = 100 µs to get a starting value of -200.
The xy2mod uses 2 DPLL timers, one for read and one for write. The read timer value can be the same as used by the stepgen and quadrature encoders so the same timer channel can be shared. The write timer is typically set to a time after the main hostmot2 write this may take some experimentation.
- .base-freq-khz (real, in)
-
This pin sets the base frequency of the phase-locked loop. By default it will be set to the nominal frequency of the thread in which the PLL is running and will not normally need to be changed.
- .phase-error-us (real, out)
-
Indicates the phase error of the DPLL. If the number cycles by a large amount it is likely that the PLL has failed to achieve lock and adjustments will need to be made.
- .time-const (uint, in)
-
The filter time-constant for the PLL. The default value is a compromise between insensitivity to single-cycle variations and being resilient to changes to the Linux CLOCK_MONOTONIC timescale, which can instantly change by up to ±500ppm from its nominal value, usually by timekeeping software like ntpd and ntpdate. Default 2000 (0x7d0).
- .plimit (uint, in)
-
Sets the phase adjustment limit of the PLL. If the value is zero then the PLL will free-run at the base frequency independent of the servo thread rate. This is probably not what you want. Default 4194304 (0x400000) Units not known…
- .ddsize (uint, out)
-
Used internally by the driver, likely to disappear.
- .prescale (uint, out)
-
Prescale factor for the rate generator. Default 1.
Энкодер
Encoders have names like hm2_<BoardType>.<BoardNum>.encoder.<Instance>. "Instance" is a two-digit number that corresponds to the HostMot2 encoder instance number. There are "num_encoders" instances, starting with 00.
Так, например, контакт HAL, который имеет текущую позицию второго энкодера первой платы 5I25: hm2_5i25.0.encoder.01.position (при этом предполагается, что прошивка на этой плате настроена так, что этот объект HAL доступен).
Каждый энкодер использует три или четыре контакта ввода-вывода, в зависимости от того, как была скомпилирована прошивка. Трехконтактные энкодеры используют A, B и Index (иногда также известный как Z). Четырехконтактные энкодеры используют A, B, Index и Index-mask.
Представление энкодера hm2 аналогично описанному в Canonical Device Interface (в документе HAL Общий справочник) и компоненту программного кодера. Каждый экземпляр энкодера имеет следующие контакты и параметры:
Pins:
- .count (sint, out)
-
Number of encoder counts since the previous reset. 32-bit truncation of the 64-bit internal counter; position is computed from the full-width internal value so it does not wrap.
- .position (real, out)
-
Encoder position in position units (count / scale).
- .position-interpolated (real, out)
-
Encoder interpolated position in position units (count / scale). Only valid when velocity is approximately constant and the time between counts is less than the velocity timeout parameter value. Do not use for position control. Useful for spindle synchronized moves with low resolution encoders.
- .position-latched (real, out)
-
Encoder latched position in position units (count / scale).
- .velocity (real, out)
-
Estimated encoder velocity in position units per second.
- .velocity-rpm (real, out)
-
Estimated encoder velocity in position units per minute.
- .reset (bool, in)
-
When this pin is True, the count and position pins are set to 0 (the value of the velocity pin is not affected by this). The driver does not reset this pin to FALSE after resetting the count to 0, that is the user’s job.
- .index-enable (bool, io)
-
When this pin is set to True, (and no_clear_on_index is false) the count (and therefore also position) are reset to zero on the next Index (Phase-Z) pulse. At the same time, index-enable is reset to zero to indicate that the pulse has occurred.
- .no_clear_on_index (bool, in)
-
When this pin is set to True, the count (and therefore also position) are NOT reset to zero on the next Index (Phase\-Z) pulse. On an index event the latched count and position will be set to indicate the count and position where the index occured.
- .probe-enable (bool, in)
-
When this pin is set to True, the encoder count (and therefore also position) are latched on the the next probe active edge. At the same time, probe-enable is reset to zero to indicate that latch event has occurred. (only present if supported by firmware)
- .probe-invert (bool, in)
-
If set to True, the rising edge of the probe input pin triggers the latch event (if probe-enable is True). If set to False, the falling edge triggers. (only present if supported by firmware)
- .rawcounts (sint, out)
-
Total number of encoder counts since the start, not adjusted for index or reset. Truncated view of the internal 64-bit counter.
- .count-latched (sint, out)
-
Encoder count at latch event (index or probe). Truncated view of the internal 64-bit latched count.
- .input-a, .input-b, .input-index (bool, out)
-
Real time filtered values of A,B,Index encoder signals
- .quad-error-enable (bool, in)
-
When this pin is True quadrature error reporting is enabled. When False, existing quadrature errors are cleared and error reporting is disabled.
- .quad-error (bool, out)
-
This bit indicates that a quadrature sequence error has been detected. It can only be set if the corresponding quad-error-enable bit is True.
The following pins are global to the encoder module and have no instance number in the name:
- .sample-frequency (uint, in)
-
This is the sample frequency that determines all standard encoder channels digital filter time constant (see filter parameter).
- .muxed-sample-frequency (uint, in)
-
This is the sample frequency that determines all muxed encoder channels digital filter time constant (see filter parameter). This also sets the encoder multiplexing frequency.
- .muxed-skew (uint, in)
-
This sets the muxed encoder sample time delay (in ns) from the multiplex signal. Setting this properly can increase the usable multiplex frequency and compensate for cable delays (suggested value is 3* cable length in feet +20).
- .hires-timestamp (bool, in)
-
When this pin is True the encoder timestamp counter frequency is ca. 10 MHz. When False the timestamp counter frequency is ca. 2 MHz. This should be set True for frequency counting applications to improve the resolution. It should be set False when servo thread periods longer than 1 ms are used.
- .timer-number (default: -1) (sint, in)
-
Sets the hm2dpll timer instance to be used to latch encoder counts. A setting of -1 does not latch encoder counts. A setting of 0 latches at the same time as the main hostmot2 read. A setting of 1..4 uses a time offset from the main hostmot2 read according to the dpll’s timer-us setting.
Обычно timer-us должно быть отрицательным числом с величиной, большей, чем наибольшая задержка (например, -100 для системы со средней задержкой, -50 для системы с хорошей задержкой). Отрицательное число указывает фиксацию указанного времени до номинального времени чтения Hostmot2.
Если в прошивке FPGA отсутствует модуль DPLL или если модуль энкодера не поддерживает DPLL, то этот контакт не создается.
Если эта функция доступна, ее обычно следует включить. Это обычно уменьшает количество последующих ошибок.
Parameters:
- .scale (real, rw)
-
Converts from "count" units to "position" units.
- .index-invert (bool, rw)
-
If set to True, the rising edge of the Index input pin triggers the Index event (if index-enable is True). If set to False, the falling edge triggers.
- .index-mask (bool, rw)
-
If set to True, the Index input pin only has an effect if the Index-Mask input pin is True (or False, depending on the index-mask-invert pin below).
- .index-mask-invert (bool, rw)
-
If set to True, Index-Mask must be False for Index to have an effect. If set to False, the Index-Mask pin must be True.
- .counter-mode (bool, rw)
-
Set to False (the default) for Quadrature. Set to True for Step/Dir (in which case Step is on the A pin and Dir is on the B pin).
- .filter (bool, rw)
-
If set to True (the default), the quadrature counter needs 15 sample clocks to register a change on any of the three input lines (any pulse shorter than this is rejected as noise). If set to False, the quadrature counter needs only 3 clocks to register a change. The default encoder sample clock runs at approximately 25 to 33 MHz but can be changed globally with the sample-frequency or muxed-sample-frequency pin.
- .vel-timeout (real, rw)
-
When the encoder is moving slower than one pulse for each time that the driver reads the count from the FPGA (in the hm2_read() function), the velocity is harder to estimate. The driver can wait several iterations for the next pulse to arrive, all the while reporting the upper bound of the encoder velocity, which can be accurately guessed. This parameter specifies how long to wait for the next pulse, before reporting the encoder stopped. This parameter is in seconds.
Синхронный последовательный интерфейс (Synchronous Serial Interface (SSI))
(Не путать с интерфейсом Smart Serial Interface )
SSI pins and parameters use the prefix hm2_XXXX.N.ssi.MM. One pin is created for each SSI instance regardless of data format:
- .data-invalid (bool, out)
-
This pin will be set "True" if the module was still transferring data when the value was read. When this problem exists there will also be a limited number of error messages printed to the UI. This pin should be used to monitor whether the problem has been addressed by config changes. Solutions to the problem depend on whether
-
the encoder read is being triggered by the hm2dpll phase-locked-loop timer (described above)
-
or by the trigger-encoders function (described below).
-
Имена контактов, созданных модулем SSI, будут полностью зависеть от строки формата для каждого канала, указанной в командной строке loadrt. Типичная строка формата может быть ssi_chan_0=error%1bposition%24g.
This would interpret the LSB of the bit-stream as a bool-type pin named "error" and the next 24 bits as a Gray-coded encoder counter. The encoder-related HAL pins would all begin with "position".
В строке формата не должно быть пробелов, поскольку они используются в качестве разделителя в коде низкого уровня.
Формат состоит из строки буквенно-цифровых символов, которые образуют имена контактов HAL, за которыми следуют символ %, количество бит и тип данных. Все биты в пакете должны быть определены, даже если они не используются. Есть ограничение в 64 бита всего.
Допустимые символы формата и контакты, которые они создают:
- p: (Pad)
-
Не создает никаких выводов, используется для игнорирования ненужных участков потока битов.
- b: (Boolean).
-
(bool, out) .<name>.
If any bits in the designated field width are non-zero then the HAL pin will be "True".
(bool, out) .<name>-not.
An inverted version of the above, the HAL pin will be "True" if all bits in the field are zero. - u: (Unsigned)
-
(real, out) .<name>. The value of the bits interpreted as an unsigned integer then scaled such that the pin value will equal the scalemax parameter value when all bits are high. (for example if the field is 8 bits wide and the scalmax parameter was 20 then a value of 255 would return 20, and 0 would return 0.
- s: (Signed)
-
(real, out) .<name>.
The value of the bits interpreted as a 2s complement signed number then scaled similarly to the unsigned variant, except symmetrical around zero. - f: (bitField)
-
(bool, out) .<name>-NN.
The value of each individual bit in the data field. NN starts at 00 up to the number of bits in the field.
(bool, out) .<name>-NN-not.
An inverted version of the individual bit values. - e: (Encoder)
-
(sint, out) .<name>.count.
The lower 32 bits of the total encoder counts. This value is reset both by the …reset and the …index-enable pins.
(sint, out) .<name>.rawcounts.
The lower 32 bits of the total encoder counts. The pin is not affected by reset and index.
(real, out) .<name>.position.
The encoder position in machine units. This is calculated from the full 64-bit buffers so will show a True value even after the counts pins have wrapped. It is zeroed by reset and index enable.
(bool, io) .<name>.index-enable.
When this pin is set "True" the module will wait until the raw encoder counts next passes through an integer multiple of the number of counts specified by counts-per-rev parameter and then it will zero the counts and position pins, and set the index-enable pin back to "False" as a signal to the system that "index" has been passed. this pin is used for spindle-synchronised motion and index-homing.
(bool, io) .<name>.reset.
When this pin is set high the counts and position pins are zeroed. - h: (Split encoder, high-order bits)
-
Некоторые энкодеры (включая Fanuc) размещают отсчеты неполных и полных оборотов энкодера в отдельных несмежных полях. Этот тег определяет старшие биты такого модуля энкодера. На канале может быть только один тег h и один тег l, поведение с несколькими такими каналами будет неопределенным.
- l: (Split encoder, low-order bits)
-
Младшие биты (см. «h»)
- g: (Gray-code)
-
Это модификатор, который указывает, что следующая строка формата закодирована в коде Грея. Это действительно только для энкодеров (e, h l) и типов данных unsigned (u).
- m: (Multi-turn)
-
Это модификатор, указывающий, что следующая строка формата является многооборотным энкодером. Это справедливо только для энкодеров (e, h l). Скачок положения энкодера более чем на половину полной шкалы интерпретируется как полный оборот и отсчеты переносятся. В случае многооборотного энкодера это может быть всего лишь сбой данных и приведет к необратимому смещению. Этот флаг гарантирует, что такие энкодеры никогда не будут выполнять перенос.
Parameters
Два параметра создаются универсально для всех экземпляров SSI
- .frequency-khz (real, rw)
-
This parameter sets the SSI clock frequency. The units are kHz, so 500 will give a clock frequency of 500,000 Hz.
- .timer-number (uint, rw)
-
This parameter allocates the SSI module to a specific hm2dpll timer instance. This pin is only of use in firmwares which contain a hm2dpll function and will default to 1 in cases where there is such a function, and 0 if there is not. The pin can be used to disable reads of the encoder, by setting to a nonexistent timer number, or to 0.
Остальные параметры зависят от типов данных, указанных в строке конфигурации.
- p: (Pad)
-
Нет параметров.
- b: (Boolean)
-
Нет параметров.
- u: (Unsigned)
-
(real, rw) .<name>-scalemax. The scaling factor for the channel.
- s: (Signed)
-
(real, rw) .<name>-scalemax. The scaling factor for the channel.
- f: (bitField)
-
Нет параметров.
- e: (Encoder)
-
(real, rw) .<name>.scale. The encoder scale in counts per machine unit. (uint, rw) .<name>.counts-per-rev. Used to emulate the index behaviour of an incremental+index encoder. This would normally be set to the actual counts per rev of the encoder, but can be any whole number of revs. Integer divisors or multipliers of the true PPR might be useful for index-homing. Non-integer factors might be appropriate where there is a synchronous drive ratio between the encoder and the spindle or ballscrew.
BiSS
BiSS is a bidirectional variant of SSI. Currently only a single direction is supported by LinuxCNC (encoder to PC). BiSS pins and parameters use the prefix hm2_XXXX.NN.biss.MM. One pin is created for each BiSS instance regardless of data format:
- .data-invalid (bool, out)
-
This pin will be set "True" if the module was still transferring data when the value was read. When this problem exists there will also be a limited number of error messages printed to the UI. This pin should be used to monitor whether the problem has been addressed by config changes. Solutions to the problem depend on whether the encoder read is being triggered by the hm2dpll phase-locked-loop timer (described above) or by the trigger-encoders function (described below).
Имена контактов, созданных модулем BiSS, будут полностью зависеть от строки формата для каждого канала, указанной в командной строке loadrt, и точно соответствовать формату, определенному выше для SSI. В настоящее время пакеты данных длиной до 96 бит поддерживаются драйвером LinuxCNC, хотя модуль Mesa Hostmot2 может обрабатывать 512-битные пакеты. Возможно расширить количество пакетов, поддерживаемых драйвером, если в этом есть необходимость.
Fanuc encoder
The pins and format specifier for this module are identical to the SSI module described above, except that at least one pre-configured format is provided. A modparam of fanuc_chan_N=AA64 (case sensitive) will configure the channel for a Fanuc Aa64 encoder. The pins use the prefix hm2_XXXX.N.fanuc.MM and are:
- .batt_fail (bool, out)
-
indicates battery state
- .batt_fail-not (bool, out)
-
inverted version of above
- .comm (uint, out)
-
The 0-1023 absolute output for motor commutation
- .crc (uint, out)
-
The CRC checksum. Currently HAL has no way to use this
- .encoder.count (sint, out)
-
Отсчеты энкодера
- .encoder.index-enable (bool, io)
-
Simulated index. Set by counts-per-rev parameter
- .encoder.position (real, out)
-
Отсчеты масштабируются по параметру …scale
- .encoder.rawcounts (sint, out)
-
Raw counts, unaffected by reset or index
- .encoder.reset (bool, io)
-
If high/True then counts and position = 0
- .pos_invalid (bool, out)
-
Indicates that the absolute position is not valid
- .pos_invalid-not (bool, out)
-
Инвертированная версия
resolver
Резольверы имеют имена типа hm2_<BoardType>.<BoardNum>.resolver.<Instance>. <Instance> — это двухзначное число, которое для платы 7I49 будет находиться в диапазоне от 00 до 05. Эта функция работает только с интерфейсными платами Mesa Resolver (единственным примером которых на момент написания является 7I49). Эта плата использует интерфейс SPI для карты FPGA и будет работать только с правильной прошивкой. Выделенные контакты будут перечислены в выводе dmesg, но вряд ли их можно будет проверить с помощью инструментов HAL.
Pins:
- .angle (real, out)
-
This pin indicates the angular position of the resolver. It is a number between 0 and 1 for each electrical rotation.
- .position (real, out)
-
Calculated from the number of complete and partial revolutions since startup, reset, or index-reset multiplied by the scale parameter.
- .velocity (real, out)
-
Calculated from the rotational velocity and the velocity-scale parameter. The default scale is electrical rotations per second.
- .velocity-rpm (real, out)
-
Simply velocity scaled by a factor of 60 for convenience.
- .count (sint, out)
-
This pins outputs a simulated encoder count at 224 counts per rev (16777216 counts).
- .rawcounts (sint, out)
-
This is identical to the counts pin, except it is not reset by the "index" or "reset" pins. This is the pin which would be linked to the bldc HAL component if the resolver was being used to commutate a motor.
- .reset (bool, in)
-
Resets the position and counts pins to zero immediately.
- .joint-pos-fb (real, in)
-
The Mesa resolver driver has the capability of emulating an absolute encoder using a position file (see the INI-config section of the manual) and the single-turn absolute operation of resolvers. At startup, and only if the use-position-file parameter is set to "True", the resolver driver will wait for a value to be written by the system to the axis.N.joint-pos-fb pin (which must be netted to this resolver pin) and will calculate the number of full turns that best matches the current resolver position. It will then pre-load the driver output with this offset. This should only be used on systems where axis movement in the unpowered state is unlikely. This feature will only work properly if the machine is initially homed to "index" and if the axis home positions are exactly zero.
- .index-enable (bool, io)
-
When this pin is set high the position and counts pins will be reset the next time the resolver passes through the zero position. At the same time the pin is driven low to indicate to connected modules that the index has been seen, and that the counters have been reset.
- .error (bool, out)
-
Indicates an error in the particular channel. If this value is "True" then the reported position and velocity are invalid.
Parameters:
- .scale (real, rw)
-
Масштаб позиции, в единицах станка на электрический оборот резольвера.
- .velocity-scale (real, rw)
-
Коэффициент преобразования между скоростью вращения резольвера и скоростью станка. Значение 1 обычно дает скорость двигателя в об/сек, значение 0,01666667 дает (приблизительное) число об/мин.
- .index-divisor (default 1) (uint, rw)
-
The resolver component emulates an index at a fixed point in the sin/cos cycle. Some resolvers have multiple cycles per rev (often related to the number of pole-pairs on the attached motor). LinuxCNC requires an index once per revolution for proper threading etc. This parameter should be set to the number of cycles per rev of the resolver. CAUTION: Which pseudo-index is used will not necessarily be consistent between LinuxCNC runs. Do not expect to re-start a thread after restarting LinuxCNC. It is not appropriate to use this parameter for index-homing of axis drives.
- .excitation-khz (real, rw)
-
This pin sets the excitation frequency for the resolver. This pin is module-level rather than instance-level as all resolvers share the same excitation frequency. Valid values are 10 (ca. 10 kHz), 5 (ca. 5 kHz) and 2.5 (ca. 2.5 kHz). The actual frequency depends on the FPGA frequency, and they correspond to CLOCK_LOW/5000, CLOCK_LOW/10000 and CLOCK_LOW/20000 respectively. The parameter will be set to the closest available of the three frequencies. A value of -1 (the default) indicates that the current setting should be retained.
- .use-position-file (bool, rw)
-
In conjunction with joint-pos-fb (qv) emulate absolute encoders.
pwmgen
pwmgens have names like hm2_<BoardType>.<BoardNum>.pwmgen.<Instance>. <Instance> is a two-digit number that corresponds to the HostMot2 pwmgen instance number. There are "num_pwmgens"-many instances, starting with 00.
Так, например, контакт HAL, который разрешает вывод четвертого pwmgen первой платы 7I43: hm2_7i43.0.pwmgen.03.enable (при этом предполагается, что прошивка на этой плате настроена так, что этот объект HAL доступен) .
В HM2 каждый pwmgen использует три выходных контакта ввода-вывода: Not-Enable, Out0 и Out1. Функция контактов ввода-вывода Out0 и Out1 зависит от параметра типа выхода (см. ниже).
Представление hm2 pwmgen аналогично программному компоненту pwmgen. Каждый экземпляр pwmgen имеет следующие контакты и параметры:
Pins:
- .enable (bool, in)
-
If True, the pwmgen will set its Not-Enable pin False and output its pulses. If "enable" is False, pwmgen will set its Not-Enable pin True and not output any signals.
- .value (real, in)
-
The current pwmgen command value, in arbitrary units.
Parameters:
- .scale (real, rw)
-
Scaling factor to convert "value" from arbitrary units to duty cycle: dc = value / scale. Duty cycle has an effective range of -1.0 to +1.0 inclusive, anything outside that range gets clipped. The default scale is 1.0.
- .output-type (sint, rw)
-
This emulates the output_type load-time argument to the software pwmgen component. This parameter may be changed at runtime, but most of the time you probably want to set it at startup and then leave it alone. Accepted values are 1 (PWM on Out0 and Direction on Out1), 2 (Up on Out0 and Down on Out1), 3 (PDM mode, PDM on Out0 and Dir on Out1), and 4 (Direction on Out0 and PWM on Out1, "for locked antiphase").
- .offset-mode (bool, rw)
-
When True, offset-mode modifies the PWM behavior so that a PWM value of 0 results in a 50% duty cycle PWM output, a -1 value results in a 0% duty cycle and +1 results in a 100% duty cycle (with default scaling). This mode is used by some PWM motor drives and PWM to analog converters. Typically the direction signal is not used in this mode.
- .dither (bool, rw)
-
When True, dither causes the PWM output to dither between two adjacent PWM register values at the PWM frequency. This increases the PWM resolution when used for analog output purposes, increasing the maximum resolution from 12 to 16 bits. Dither is only supported with PWMGen firmware version 1 or greater and only affects PWM outputs, not PDM outputs.
В дополнение к параметрам HAL для каждого экземпляра, перечисленным выше, существует несколько параметров HAL, которые влияют на все экземпляры pwmgen:
- .pwm_frequency (uint, rw)
-
This specifies the PWM frequency, in Hz, of all the pwmgen instances running in the PWM modes (modes 1 and 2). This is the frequency of the variable-duty-cycle wave. Its effective range is from 1 Hz up to 386 kHz. Note that the max frequency is determined by the ClockHigh frequency of the Anything IO board; the 5I25 and 7I92 both have a 200 MHz clock, resulting in a 386 kHz max PWM frequency. Other boards may have different clocks, resulting in different max PWM frequencies. If the user attempts to set the frequency too high, it will be clipped to the max supported frequency of the board. Frequencies below about 5 Hz are not terribly accurate, but above 5 Hz they’re pretty close. The default pwm_frequency is 20,000 Hz (20 kHz).
- .pdm_frequency (uint, rw)
-
This specifies the PDM frequency, in Hz, of all the pwmgen instances running in PDM mode (mode 3). This is the "pulse slot frequency"; the frequency at which the pdm generator in the AnyIO board chooses whether to emit a pulse or a space. Each pulse (and space) in the PDM pulse train has a duration of 1/pdm_frequency seconds. For example, setting the pdm_frequency to 2e6 (2 MHz) and the duty cycle to 50% results in a 1 MHz square wave, identical to a 1 MHz PWM signal with 50% duty cycle. The effective range of this parameter is from about 1525 Hz up to just under 200 MHz. Note that the max frequency is determined by the ClockHigh frequency of the Anything IO board; the 5I25 and 7I92 both have a 100 MHz clock, resulting in a 100 MHz max PDM frequency. Other boards may have different clocks, resulting in different max PDM frequencies. If the user attempts to set the frequency too high, it will be clipped to the max supported frequency of the board. The default pdm_frequency is 20,000 Hz (20 kHz).
3ppwmgen
Three-Phase PWM generators (3pwmgens) are intended for controlling the high-side and low-side gates in a 3-phase motor driver. The function is included to support the Mesa motor controller daughter-cards but can be used to control an IGBT or similar driver directly. 3pwmgens have names like hm2_<BoardType>.<BoardNum>.3pwmgen.<Instance> where <Instance> is a 2-digit number. There will be num_3pwmgens instances, starting at 00. Each instance allocates 7 output and one input pins on the Mesa card connectors. Outputs are: PWM A, PWM B, PWM C, /PWM A, /PWM B, /PWM C, Enable. The first three pins are the high side drivers, the second three are their complementary low-side drivers. The enable bit is intended to control the servo amplifier. The input bit is a fault bit, typically wired to over-current detection. When set, the PWM generator is disabled. The three phase duty-cycles are individually controllable from -Scale to +Scale. Note that 0 corresponds to a 50% duty cycle and this is the initialization value.
Pins:
- .A-value, .B-value, .C-value (real, in)
-
The PWM command value for each phase, limited to +/- "scale". Defaults to zero which is 50% duty cycle on high-side and low-sidepins (but see the "deadtime" parameter).
- .enable (bool, in)
-
When high the PWM is enabled as long as the fault bit is not set by the external fault input pin. When low the PWM is disabled, with both high- side and low-side drivers low. This is not the same as 0 output (50% duty cycle on both sets of pins) or negative full scale (where the low side drivers are "on" 100% of the time).
- .fault (bool, out)
-
Indicates the status of the fault bit. This output latches high once set by the physical fault pin until the "enable" pin is set to high.
Parameters:
- .deadtime (uint, rw)
-
Sets the dead-time between the high-side driver turning off and the low-side driver turning on and vice-versa. Deadtime is subtracted from on time and added to off time symmetrically. For example with 20 kHz PWM (50 µs period), 50% duty cycle and zero dead time, the PWM and NPWM outputs would be square waves (NPWM being inverted from PWM) with high times of 25 µs. With the same settings but 1 µs of deadtime, the PWM and NPWM outputs would both have high times of 23 µs (25 - (2X 1 µs), 1 µs per edge). The value is specified in nanoseconds (ns) and defaults to a rather conservative 5000 ns. Setting this parameter to too low a value could be both expensive and dangerous as if both gates are open at the same time there is effectively a short circuit across the supply.
- .scale (real, rw)
-
Sets the half-scale of the specified 3-phase PWM generator. PWM values from -scale to +scale are valid. Default is +/- 1.0
- .fault-invert (bool, rw)
-
Sets the polarity of the fault input pin. A value of 1 means that a fault is triggered with the pin high, and 0 means that a fault it triggered when the pin is pulled low. Default 0, fault = low so that the PWM works with the fault pin unconnected.
- .sample-time (real, rw)
-
Sets the time during the cycle when an ADC pulse is generated. 0 = start of PWM cycle and 1 = end. Not currently useful to LinuxCNC. Default is 0.5.
В дополнение к параметрам для каждого экземпляра, указанным выше, есть следующий параметр, который влияет на все экземпляры:
- .frequency (uint, rw)
-
Устанавливает основную частоту ШИМ. Максимум составляет около 48 кГц, минимум — 1 кГц. По умолчанию 20 кГц.
oneshot
The oneshot is a hardware one-shot device suitable for various timing, delay, signal conditioning, PWM generation, and watchdog functions. The oneshot module includes 2 timers to allow variable pulse delays for applications like phase control. Trigger sources can be software, external inputs, the DPLL timer, a built in rate generator or the other timer. Oneshots have names like hm2_<BoardType>.<BoardNum>.oneshot.<Instance> where <Instance> is a 2-digit number. There will be num_oneshots instances, starting at 00. Each instance allocates up to two input and two output pins.
Pins:
- .width1 (real, in)
-
Sets the pulse width of timer1 in ms. Default is 1 ms (1/1000 s).
- .width2 (real, in)
-
Sets the pulse width of timer2 in ms. Default is 1 ms (1/1000 s).
- .filter1 (real, in)
-
Sets digital filter time constant for timer1’s external trigger input Filter time is in ms. Default filter time constant time is 0.1 ms. External trigger response will be delayed by the filter time setting.
- .filter2 (real, in)
-
Sets digital filter time constant for timer2’s external trigger input Filter time is in ms. Default filter time constant time is 0.1 ms. External trigger response will be delayed by the filter time setting.
- .rate (real, in)
-
Sets the frequency of the built in rate generator (in Hz)
- .trigger_select1, .trigger_select2 (uint, in)
-
Sets the trigger source for timer1,timer2 respectively. Trigger sources are:
0 Триггер отключен 1 Программный триггер: срабатывает, когда на контакте hal swtrigger1 установлено значение true 2 Внешнее оборудование: триггер 3 Триггер DPLL: запускается выбранным таймером DPLL 4 Триггер скорости: запускается встроенным генератором скорости. 5 Триггер timer1: запускается выходом timer1 6 Триггер timer2: запускается выходом timer2
- .trigger_on_rise1, .trigger_on_rise2 (bool, in)
-
When true, triggers timer1, timer2 respectively on the rising edge of the trigger source.
- .trigger_on_fall1, .trigger_on_fall2 (bool, in)
-
When true, triggers timer1, timer2 respectively on the falling edge of the trigger source.
- .retriggerable1, .retriggerable2 (bool, in)
-
When true, the associated timer is retriggerable, meaning the timer will reset to full time on a trigger event even during the output pulse period. When false the timer is not retriggerable, meaning it will ignore trigger events during the output pulse period.
- .enable1, .enable2 (bool, in)
-
Trigger enable for timer1 and timer2 respectively True to enable.
- .reset1, .reset2 (bool, in)
-
If true, resets timer1 and timer2 respectively, aborting any pulse in progress.
- .out1, .out2 (bool, out)
-
Pulse output status bits for timer1 and timer2.
- .exttrigger1, .exttrigger2 (bool, out)
-
External trigger input status bits for timer1 and timer2. These monitor the filtered inputs.
- .swtrigger1, .swtrigger2 (bool, in)
-
Software trigger inputs to trigger timer1 and timer2.
periodm
Periodm — это модуль измерения периода/ширины/скважности. Он может измерять период, частоту, ширину импульса и скважность. Он также может усреднять показания для фильтрации шума.
Pins:
- .period_us (real, out)
-
Input period in microseconds.
- .width_us (real, out)
-
Input pulse width in microseconds.
- .duty_cycle (real, out)
-
Input duty cycle (width/period) scaling and offset are changeable.
- .duty_cycle_scale (real, in)
-
Sets the scale of the duty cycle value, default is 100.
- .duty_cycle_offset (real, in)
-
Sets an offset to the duty cycle value, added after scaling. Default is 0.
- .averages (uint, io)
-
Количество periods/widths для усреднения. От 1 до 4095. Скорость обновления period, width, duty cycle, и frequency будет являться входной частотой/усреднения.
- .frequency (real, out)
-
Входная частота в Гц.
- .minimum_frequency (real, in)
-
Minimum input frequency in Hz, if input frequency is lower than this threshold, the valid bit will be cleared. .filtertc_us (real, in):: The periodm input in conditioned with a digital filter for noise rejection. The time constant of this filter is settable via this pin in units of microseconds. Pulses shorter than this time constant will not be recognized. .valid (bool, out):: The valid output bit is true when the input signal is present and the input frequency exceeds the minimum frequency setting. .invert (bool, io):: The invert bit sets the input polarity, when false, the input is direct which means the input high time determines the width. When set true, the input is inverted so the input low time determines the width. .input_status (bool, out):: The input_status bit reads the real time filtered input status (affected by invert pin).
rcpwmgen
The rcpwmgen is a simple PWM generator optimized for use with standard RC servos that use pulse width to determine position. rcpwmgens have names like hm2_<BoardType>.<BoardNum>.rcpwmgen.<Instance> where <Instance> is a 2-digit number. There will be num_rcpwmgens-many instances, starting at 00. Each instance allocates a single output pin. Unlike the standard PWM generator, the rcpwmgen output is specified in width rather than duty cycle so the pulse width is independent of the operating frequency. Resolution is approximately 1/2000 for standard 1 to 2 ms range RC servos.
Pins:
- .rate (real, in)
-
Устанавливает частоту ШИМ ведущего RC. Максимум — 1 кГц, минимум — 0.01 Гц. По умолчанию 50 Гц.
- .width (real, in)
-
Устанавливает ширину импульса для каждого канала в (ms/scale).
- .offset (real, in)
-
Устанавливает смещение ширины импульса для каждого канала в мс. Это значение будет установлено на 1,5 мс для сервоприводов 1-2 мс для 0 центрального положения.
- .scale (real, in)
-
Устанавливает масштабирование ширины импульса для каждого канала. Например, установка масштаба на 90 и смещения на 1,5 мс приведет к диапазону положения +-45 градусов и масштабу в градусах для сервоприводов 1-2 мс с полным диапазоном движения 90 градусов.
stepgen
stepgens have names like hm2_<BoardType>.<BoardNum>.stepgen.<Instance>. <Instance> is a two-digit number that corresponds to the HostMot2 stepgen instance number. There are "num_stepgens"-many instances, starting with 00.
Так, например, контакт HAL, который имеет обратную связь о текущем положении от первого шага второй платы 5I22: hm2_5i22.1.stepgen.00.position-fb (при этом предполагается, что прошивка на этой плате настроена так, что этот объект HAL доступен ).
Каждый stepgen использует от 2 до 8 контактов ввода-вывода. Сигналы на этих выводах зависят от параметра Step_type (описанного ниже).
Представление Stepgen смоделировано на основе программного компонента Stepgen. Каждый экземпляр Stepgen имеет следующие контакты и параметры:
Pins:
- .position-cmd (real, in)
-
Target position of stepper motion, in arbitrary position units. This pin is only used when the stepgen is in position control mode (control-type=0). .velocity-cmd (real, in):: Target velocity of stepper motion, in arbitrary position units per second. This pin is only used when the stepgen is in velocity control mode (control-type=1).
- .counts (sint, out)
-
Положение обратной связи в отсчетах (количество шагов).
- .position-fb (real, out)
-
Положение обратной связи в масштабированных единицах положения. Это похоже на «counts/position_scale», но имеет более точное разрешение, чем шаг.
- .position-latch (real, out)
-
latched-position в масштабированных единицах положения. Это похоже на «counts/position_scale», но имеет более точное разрешение, чем шаг.
- .velocity-fb (real, out)
-
Скорость обратной связи в произвольных единицах положения в секунду.
- .enable (bool, in)
-
Этот контакт включает экземпляр генератора шагов. Если установлено значение True, экземпляр Stepgen работает должным образом. Если установлено значение False, шаги не генерируются, а velocity-fb немедленно переходит в 0. Если stepgen движется, когда enable переходит в false, он немедленно останавливается, не соблюдая предел maxaccel .
- .position-reset (bool, in)
-
Resets position to 0 when True. Useful for step/dir controlled spindles when switching between spindle and joint modes. .control-type (bool, in):: Switches between position control mode (0) and velocity control mode (1). Defaults to position control (0). .index-enable (bool, io):: When this pin is set to True, the step count (and therefore also position) are reset to zero on the next stepgen index pulse. At the same time, index-enable is reset to zero to indicate that the pulse has occurred. .index-invert (bool, in):: If set to True, the rising edge of the index input pin triggers the position clear event (if index-enable is True). If set to False, the falling edge triggers. .probe-enable (bool, io):: When this pin is set to True, the step count (and therefore also position) are latched on the the next stepgen probe active edge. At the same time, probe-enable is reset to zero to indicate that a latch event has occurred. .probe-invert (bool, in):: If set to True, the rising edge of the probe input pin triggers the latch event (if probe-enable is True). If set to False, the falling edge triggers.
Parameters:
- .position-scale (real, rw)
-
Converts from counts to position units. position = counts / position_scale
- .maxvel (real, rw)
-
Maximum speed, in position units per second. If set to 0, the driver will always use the maximum possible velocity based on the current step timings and position-scale. The max velocity will change if the step timings or position-scale changes. Defaults to 0.
- .maxaccel (real, rw)
-
Maximum acceleration, in position units per second per second. Defaults to 1.0. If set to 0, the driver will not limit its acceleration at all. This requires that the position-cmd or velocity-cmd pin is driven in a way that does not exceed the machine’s capabilities. This is probably what you want if you are going to be using the LinuxCNC trajectory planner to jog or run G-code.
- .steplen (uint, rw)
-
Duration of the step signal, in nanoseconds.
- .stepspace (uint, rw)
-
Minimum interval between step signals, in nanoseconds.
- .dirsetup (uint, rw)
-
Minimum duration of stable Direction signal before a step begins, in nanoseconds.
- .dirhold (uint, rw)
-
Minimum duration of stable Direction signal after a step ends, in nanoseconds.
- .step_type (uint, rw)
-
Output format, like the step_type modparam to the software stepgen(9) component: 0 = Step/Dir, 1 = Up/Down, 2 = Quadrature, 3+ = table-lookup mode. In this mode the step_type parameter determines how long the step sequence is. Additionally the stepgen_width parameter in the loadrt config string must be set to suit the number of pins per stepgen required. Any stepgen pins above this number will be available for GPIO. This mask defaults to 2. The maximum length is 16. Note that Table mode is not enabled in all firmwares but if you see GPIO pins between the stepgen instances in the dmesg/log hardware pin list then the option may be available.
В квадратурном режиме (step_type=2) stepgen выдает один полный цикл Грея (00 → 01 → 11 → 10 → 00) для каждого принимаемого им импульса «шага», поэтому масштаб необходимо разделить на 4 относительно стандартного step/dir. В табличном режиме индивидуально управляются до 6 контактов ввода-вывода в произвольной последовательности длиной до 16 фаз.
- .swap_step_dir (bool, rw)
-
This swaps the step and direction outputs on the selected stepgen. This parameter is only available if the firmware supports this option.
- .table-data-N (uint, rw)
-
There are 4 table-data-N parameters, table-data-0 to table-data-3. These each contain 4 bytes corresponding to 4 stages in the step sequence. For example table-data-0 = 0x00000001 would set stepgen pin 0 (always called "Step" in the dmesg output) on the first phase of the step sequence, and table-data-4 = 0x20000000 would set stepgen pin 6 ("Table5Pin" in the dmesg output) on the 16th stage of the step sequence.
- .timer-number (default: -1) (sint, in)
-
Sets the hm2dpll timer instance to be used to latch stepgen counts. This pin is global to the stepgen module and has no instance number in the name. A setting of -1 does not latch stepgen counts. A setting of 0 latches at the same time as the main hostmot2 read. A setting of 1..4 uses a time offset from the main hostmot2 read according to the dpll’s timer-us setting.
Обычно timer-us должно быть отрицательным числом с величиной, большей, чем наибольшая задержка (например, -100 для системы со средней задержкой, -50 для системы с хорошей задержкой). Отрицательное число указывает фиксацию указанного времени до номинального времени чтения Hostmot2.
Если в прошивке FPGA отсутствует модуль DPLL или модуль Stepgen не поддерживает DPLL, то этот контакт не создается.
Если эта функция доступна, ее обычно следует включить. Это обычно уменьшает количество последующих ошибок.
Smart Serial Interface
Smart Serial Interface позволяет подключать к одной карте FPGA до 32х различных устройств, таких как трехфазный привод Mesa 8i20 мощностью 2,2 кВт или 48-контактные карты ввода-вывода 7I64. Драйвер автоматически определяет подключенный порт оборудования, канал и тип устройства. Устройства можно подключать в любом порядке к любому активному каналу активного порта (см. определение config modparam выше).
For full details of the smart-serial devices see sserial(9).
BSPI
Драйвер BSPI (Buffered SPI) необычен тем, что не создает никаких контактов HAL. Вместо этого драйвер экспортирует набор функций, которые могут использоваться субдрайвером для подключенного оборудования. Обычно они пишутся в "comp".
Язык предварительной обработки: см. https://linuxcnc.org/docs/html/hal/comp.html или man halcompile для получения дополнительной информации. См. mesa_7i65(9) и исходный код mesa_7i65.comp для получения подробной информации о типовом субдрайвере. См. hm2_bspi_setup_chan(3), hm2_bspi_write_chan(3), hm2_tram_add_bspi_frame(3), hm2_allocate_bspi_tram(3), hm2_bspi_set_read_function(3) и hm2_bspi_set_write_function(3) для получения информации об экспортированных функциях.
Имена доступных каналов выводятся на стандартный вывод во время загрузки драйвера и имеют вид hm2_<имя платы>.<индекс платы>.bspi.<индекс>, например, hm2_5i23.0.bspi.0.
UART
Драйвер UART также не создает никаких контактов HAL, вместо этого он объявляет две простые функции чтения/записи и функцию настройки, которые будут использоваться написанным пользователем кодом. Обычно это записывается на языке предварительной обработки «comp»: дополнительную информацию см. в https://linuxcnc.org/docs/html/hal/comp.html или man halcompile. См. mesa_uart(9) и исходный код mesa_uart.comp для получения подробной информации о типичном субдрайвере. См. hm2_uart_setup_chan(3), hm2_uart_send(3), hm2_uart_read(3) и hm2_uart_setup(3).
Имена доступных каналов UART выводятся на стандартный вывод во время загрузки драйвера и имеют вид hm2_<board name>.<board index>.uart.<index>, e.g., hm2_5i23.0.uart.0.
Ввод/вывод общего назначения
Контакты ввода-вывода на плате, которые не используются экземпляром модуля, экспортируются в HAL как «полные» контакты GPIO. Полные контакты GPIO могут быть настроены во время выполнения как входы, выходы или открытые стоки и иметь интерфейс HAL, обеспечивающий такую гибкость. Контакты ввода-вывода, принадлежащие экземпляру активного модуля, ограничены требованиями модуля-владельца и имеют ограниченный интерфейс HAL.
GPIOs have names like hm2_<BoardType>.<BoardNum>.gpio.<IONum>. <IONum> is a three-digit number. The mapping from <IONum> to connector and pin-on-that-connector is written to the syslog when the driver loads, and it is documented in Mesa’s manual for the Anything I/O boards.
So, for example, the HAL pin that has the current inverted input value read from GPIO 012 of the second 7I43 board is: hm2_7i43.1.gpio.012.in_not (this assumes that the firmware in that board is configured so that this HAL object is available).
Параметр HAL, который определяет, является ли последний GPIO первой 5I22 входом или выходом: hm2_5i22.0.gpio.095.is_output (при этом предполагается, что встроенное ПО этой платы настроено так, что этот объект HAL доступен).
Представление hm2 GPIO смоделировано по образцу цифровых входов и цифровых выходов, описанных в интерфейсе устройств Canonical (часть документа HAL Общая Справка). Каждый GPIO может иметь следующие контакты HAL:
- .in, .in_not (bool, out)
-
State (normal and inverted) of the hardware input pin. Both full GPIO pins and I/O pins used as inputs by active module instances have these pins.
- .out (bool, in)
-
Value to be written (possibly inverted) to the hardware output pin. Only full GPIO pins have this pin.
Каждый GPIO может иметь следующие параметры:
- .is_output (bool, rw)
-
If set to 0, the GPIO is an input. The I/O pin is put in a high-impedance state (weakly pulled high), to be driven by other devices. The logic value on the I/O pin is available in the "in" and "in_not" HAL pins. Writes to the "out" HAL pin have no effect. If this parameter is set to 1, the GPIO is an output; its behavior then depends on the "is_opendrain" parameter. Only full GPIO pins have this parameter.
- .is_opendrain (bool, rw)
-
This parameter only has an effect if the "is_output" parameter is True. If this parameter is False, the GPIO behaves as a normal output pin: The I/O pin on the connector is driven to the value specified by the "out" HAL pin (possibly inverted), and the value of the "in" and "in_not" HAL pins is undefined. If this parameter is True, the GPIO behaves as an open-drain pin. Writing 0 to the "out" HAL pin drives the I/O pin low, writing 1 to the "out" HAL pin puts the I/O pin in a high-impedance state. In this high-impedance state the I/O pin floats (weakly pulled high), and other devices can drive the value; the resulting value on the I/O pin is available on the "in" and "in_not" pins. Only full GPIO pins and I/O pins used as outputs by active module instances have this parameter.
- .invert_output (bool, rw)
-
This parameter only has an effect if the "is_output" parameter is True. If this parameter is True, the output value of the GPIO will be the inverse of the value on the "out" HAL pin. Only full GPIO pins and I/O pins used as outputs by active module instances have this parameter.
Когда физический вывод ввода/вывода используется специальной функцией, соответствующие параметры HAL is_output и is_opendrain присваиваются специальной функции. Например, если gpio 1 занят первым выходом pwmgen 0, то будут автоматически созданы такие псевдонимы, как hm2_7i92.0.pwmgen.00.out0.invert_output (относящиеся к hm2_7i92.0.gpio.001.invert_output). Когда к одной и той же специальной функции подключено более одного GPIO, вставляется дополнительный .#., чтобы настройки для каждого связанного GPIO можно было задать отдельно. Например, для прошивки SV12IM_2X7I48_72 создаются оба псевдонима hm2_5i20.0.pwmgen.00.0.enable.invert_output (относящийся к hm2_5i20.0.gpio.000.invert_output) и hm2_5i20.0.pwmgen.00.1.enable.invert_output (относящийся к hm2_5i20.0.gpio.023.invert_output).
inm и inmux
inm/inmuxs are input debouncing modules that support hardware digital filtering of input pins. In addition to the input filtering function, the inm/inmux modules support up to 4 simple quadrature counters for MPG use. The quadrature inputs for MPG encoders 0 through 3 are inm/inmux pins 0 through 7. MPG A,B inputs use the filter time constants programmed for inputs 0..7. Each inm/inmux input pin can have a slow or fast filter constant. Filter time constants are specified in units of scan times. inms have names like hm2_<BoardType>.<BoardNum>.inm.<Instance>. inmuxes have names like hm2_<BoardType>.<BoardNum>.inmux.<Instance>. "Instance" is a two-digit number that corresponds to the HostMot2 inm or inmux instance number. There are "num_inms" or numx_inmuxs" instances, starting with 00.
Каждый экземпляр считывает от 8 до 32 входных контактов. inm и inmux идентичны, за исключением названий контактов и физического интерфейса.
Pins:
- .input-MM (bool, out)
-
Filtered input state.
- .input-MM-not (bool, out)
-
Inverted filtered input state.
- .raw-input-MM (bool, out)
-
Unfiltered input state.
- .raw-input-MM-not (bool, out)
-
Inverted unfiltered input state. .input-MM-slow (bool, in):: If True, selects the long time constant filter for the corresponding input, if False the short time constant is used.
- .enc0-count, .enc1-count, .enc2-count, .enc3-count (sint, out)
-
MPG counters 0 through 3. .enc0-reset, .enc1-reset, .enc2-reset, .enc3-reset (bool, in):: Reset for MPG counters 0 through 3, count is forced to 0 if true.
Parameters:
- .scan_rate (uint, rw)
-
This sets the input scan rate in Hz. Default scan rate is 20 kHz (50 µs scan period).
- .fast_scans (uint, rw)
-
This sets the fast time constant for all input pins. This is the time constant used when the .input-MM-slow pin for the corresponding input is False. The range is 0 to 63 scan periods and the default value is 5 = 250 µs at the default 20 kHz scan_rate.
- .slow_scans (uint, rw)
-
This sets the slow time constant for all input pins. This is the time constant used when the .input-MM-slow pin for the corresponding input is True. The range is 0 to 1023 scan periods and the default value is 500 = 25 ms at the default 20 kHz scan_rate.
- .enc0_4xmode, .enc1_4xmode, .enc2_4xmode, and .enc3_4xmode (bool, rw)
-
These set the MPG encoder operating modes to 4X when True and 1X when False.
- .scan_width (uint, ro)
-
This read only parameter specifies the number of inputs scanned by the module.
СИД (led)
Создает контакты HAL для светодиодов на плате FPGA.
Pins:
- .CR<NN> (bool, in)
-
The pins are numbered from CR01 upwards with the name corresponding to the PCB silkscreen. Setting the bit to "True" or 1 lights the LED.
Твердотельное реле (Solid State Relay)
SSRs have names like hm2_<BoardType>.<BoardNum>.ssr.<Instance>. Instance is a two-digit number that corresponds to the HostMot2 SSR instance number. There are num_ssrs instances, starting with 00.
Каждый экземпляр имеет контакт управления скоростью и от 1 до 32 выходных контактов.
Pins:
- .rate (uint, in)
-
Set the internal frequency of the SSR instance, in Hz (approximate). The valid range is 25 kHz to 25 MHz. Values below the minimum will use the minimum, and values above the max will use the max. 1 MHz is a typical value, and appropriate for all Mesa cards, and is the default. Set to 0 to disable this SSR instance.
- .out-NN (bool, in)
-
The state of this SSR instance’s NNth output. Set to 0 to make the output pins act like an open switch (no connection), set to 1 to make them act like a closed switch.
- .invert-NN (bool, in)
-
Inverts the state of this SSR instance’s NNth output, defaults to 0. When invert-NN is set to 1, SSR output NN is closed when the out-NN pin is 0 and open when the out-NN pin is 1.
OutM Простой модуль вывода
OutMs have names like hm2_<BoardType>.<BoardNum>.outm.<Instance>. Instance is a two-digit number that corresponds to the HostMot2 OutM instance number. There are num_outms instances, starting with 00.
Каждый экземпляр имеет от 1 до 32 выходных контактов.
Pins:
- .out-NN (bool, in)
-
The sets the state of this OutM instance’s NNth output. Normally the output pin follows the state of this pin but may be inverted by the invert-nn HAL pin.
- .invert-NN (bool, in)
-
Inverts the state of the this OutM instance’s NNth output, defaults to 0. When invert-NN is set to 1, OutM output NN is high when the out-NN pin is 0 and low when the out-NN pin is 1.
xy2mod
The xy2mod is a xy2-100 galvanometer interface. It supports 16 and 18 bit data modes and includes parabolic interpolation to provide position updates between servo thread invocations. xy2mod pins use the prefix hm2_<BoardType>.<BoardNum>.xy2mod.<Instance>.
Pins:
- .posx-cmd, .posy-cmd (real, in)
-
X and Y position commands. Full scale is +-posn_scale default full scale (set by posx-scale and posy-scale) is +- 1
- .posx-fb, .posy-fb (real, out)
-
Обратная связь по положению X и Y. Полная шкала +-posN_scale по умолчанию полная шкала +- 1. Это обратная связь от интерполятора, а не от гальванометра.
- .velx-cmd, .vely-cmd (real, in)
-
Команды скорости X и Y в единицах fullscale_position/second
- .velx-fb, .vely-fb (real, out)
-
Обратная связь по скорости X и Y в единицах fullscale_position/second
- .accx-cmd, .accy-cmd (real, in)
-
Команды ускорения X и Y в единицах fullscale_position/second2
- .posx-scale, .posy-scale (real, in)
-
This sets the full scale range of the position command and feedback, default is +- 1.0. .enable (bool, in):: When False, output data is 0, all interpolator values are set to 0 and overflow flags are cleared. Must be True for normal operation.
- .controlx, .controly (uint, in)
-
These set the galvanometer control bits. There 3 bits per channel in 16 bit mode but just 1 control bit in 18 bit mode, so values from 0..7 are valid in 16 bit mode but only 0 and 4 are valid in 18 bit mode. .commandx, .commandy (uint, in):: These set the raw 16 bit data sent to the galvanometer in command mode. .commandmodex, .commandmodey (bool, in):: When set, these enable the command mode where 16 bit command data is sent to the galvanometer. .18bitmodex, .18bitmodey (bool, in):: When True, these enable the 18 bit data mode for the respective channel. .posx-overflow, .posy-overflow (bool, out):: When true, these indicate an attempted position move beyond the full scale value. .velx-overflow, .vely-overflow (bool, out):: When True, these indicate an attempted velocity update move beyond the full scale value.
- .status (uint, out)
-
Необработанный 16-битный статус возврата от гальванометра.
- .read-timer-number (sint, in)
-
Selects the DPLL timer number for pre-read sampling of the position and velocity registers. If set to -1, pre-read sampling is disabled. .write-timer-number (sint, in):: Selects the DPLL timer number for post write update of the position and velocity registers. If set to -1, post write update is disabled.
Сторожевой таймер
The HostMot2 firmware may include a watchdog Module; if it does, the hostmot2 driver will use it. The HAL representation of the watchdog is named hm2_<BoardType>.<BoardNum>.watchdog.
Сторожевой таймер запускается спящим и неактивен. Как только вы первый раз получите доступ к плате, запустив функцию HAL hm2 write() (см. ниже), сторожевой таймер просыпается. Из нее его нужно периодически гладить, иначе он укусит. Погладьте сторожевой таймер, запустив функцию HAL hm2 write().
Когда сторожевой таймер кусает, все контакты ввода-вывода платы отключаются от своих экземпляров модуля и становятся входами с высоким импедансом (подтянуты к высокому уровню), и вся связь с платой прекращается. Состояние модулей прошивки HostMot2 не нарушено (кроме конфигурации выводов IO). Экземпляры энкодеров продолжают считать квадратурные импульсы, а ШИМ- и шаговые генераторы продолжают генерировать сигналы (которые не передаются на двигатели, поскольку контакты ввода-вывода стали входами).
Сброс сторожевого таймера (путем сброса контакта has_bit, см. ниже) возобновляет связь и сбрасывает контакты ввода-вывода в конфигурацию, выбранную во время загрузки.
Если прошивка включает сторожевой таймер, будут экспортированы следующие объекты HAL:
Pins:
- .has_bit (bool, io)
-
True if the watchdog has bit, False if the watchdog has not bit. If the watchdog has bit and the has_bit bit is True, the user can reset it to False to resume operation.
Parameters:
- .timeout_ns (uint, rw)
-
Watchdog timeout, in nanoseconds. This is initialized to 5,000,000 (5 milliseconds) at module load time. If more than this amount of time passes between calls to the hm2 write() function, the watchdog will bite.
Необработанный режим (Raw Mode)
If the "enable_raw" config keyword is specified, some extra debugging pins are made available in HAL. The raw mode HAL pin names begin with hm2_<BoardType>.<BoardNum>.raw.
При включенном режиме Raw пользователь может просматривать и скачивать прошивку из HAL, а также может выгружать внутреннее состояние драйвера hostmot2 в системный журнал.
Pins:
- .read_address (uint, in)
-
The bottom 16 bits of this is used as the address to read from.
- .read_data (uint, out)
-
Each time the hm2_read() function is called, this pin is updated with the value at .read_address.
- .write_address (uint, in)
-
The bottom 16 bits of this is used as the address to write to.
- .write_data (uint, in)
-
This is the value to write to .write_address.
- .write_strobe (bool, in)
-
Each time the hm2_write() function is called, this pin is examined. If it is True, then value in .write_data is written to the address in .write_address, and .write_strobe is set back to False.
- .dump_state (bool, io)
-
Обычно этот контакт имеет значение False. Если для него установлено значение True, драйвер hostmot2 запишет свое представление о внутреннем состоянии платы в системный журнал и снова установит для вывода значение False.
Настройка устройств Smart Serial
См. setserial(9) для текущего способа установки параметров eeprom smart-serial.
FUNCTIONS
- hm2_<BoardType>.<BoardNum>.read-request
-
На платах с длительным временем ожидания чтения (на момент написания это относится только к платам Ethernet) эта функция отправляет запрос на чтение. При использовании нескольких плат это может сократить время выполнения servo thread. В этом случае соответствующий порядок потоков будет таким
addf hm2_7i80.0.read-request addf hm2_7i80.1.read-request addf hm2_7i80.0.read addf hm2_7i80.1.read
что приводит к отправке запроса на чтение на плату 1 перед ожиданием прибытия ответа на запрос на чтение от платы 0.
- hm2_<BoardType>.<BoardNum>.read
-
Это считывают счетчики энкодера, сигналы обратной связи stepgen и входные контакты GPIO из FPGA.
- hm2_<BoardType>.<BoardNum>.write
-
Это обновляет скважности ШИМ, частоты генерации импульсов шага и выходы GPIO на FPGA. Эта функция также влияет на любые изменения в контактах конфигурации, такие как синхронизация шагового генератора, инверсия GPIO и т. д.
- hm2_<BoardType>.<BoardNum>.read_gpio
-
Считывает входные контакты GPIO. Обратите внимание, что эффект этой функции является подмножеством эффекта функции .read(), описанной выше. Обычно используется только .read(). Единственная причина вызова этой функции — если вы хотите выполнять действия GPIO в потоке, более быстром, чем сервопривод. (Эта функция недоступна на 7I43 из-за ограничений шины EPP.)
- hm2_<BoardType>.<BoardNum>.write_gpio
-
Запишите регистры управления GPIO и выходные контакты. Обратите внимание, что эффект этой функции является подмножеством эффекта функции .write(), описанной выше. Обычно используется только .write(). Единственная причина вызова этой функции — если вы хотите выполнять действия GPIO в потоке, более быстром, чем сервопривод. (Эта функция недоступна на 7I43 из-за ограничений шины EPP.)
- hm2_<BoardType>.<BoardNum>.trigger-encoders
-
Эта функция появится только в том случае, если прошивка содержит модуль BiSS, Fanuc или SSI энкодера и если прошивка не содержит модуль hm2dpll (qv), или если параметр modparam содержит num_dplls=0. Эту функцию следует вставить первой в поток, чтобы данные энкодера были готовы когда запустится функция hm2_*XXXX.NN.read*. Если чтение энкодера не завершится вовремя, будет выведено сообщение об ошибке. Этого можно избежать, увеличив скорость передачи данных. Если проблема не устранена и если "устаревшие" данные приемлемы, функцию можно поместить в поток позже, что позволит выполнить полный сервоцикл передачи данных с устройств. Если таковая имеется, лучше использовать синхронную функцию запуска hm2dpll.
СМОТРИТЕ ТАКЖЕ
Документация Mesa для плат Anything I/O доступна по адресу https://www.mesanet.com.
LICENSE
GPL