СИНТАКСИС
Дивіться розділ config modparam нижче для налаштування карти Mesa. Зазвичай hostmot2 завантажується без параметрів, якщо не потрібне налагодження.
loadrt hostmot2 [ debug_idrom=N ] [ debug_module_descriptors=N ] [ debug_pin_descriptors=N ] [ debug_modules=N ]
- debug_idrom [за замовчуванням: 0]
-
Тільки для розробників/налагодження! Увімкнути ведення журналу налагодження заголовка HostMot2 IDROM.
- debug_module_descriptors [за замовчуванням: 0]
-
Тільки для розробників/налагодження! Вмикає ведення журналу налагодження дескрипторів модуля HostMot2.
- debug_pin_descriptors [за замовчуванням: 0]
-
Тільки для розробників/налагодження! Вмикає ведення журналу налагодження дескрипторів контактів HostMot2.
- debug_modules [за замовчуванням: 0]
-
Тільки для розробників/налагодження! Вмикає ведення журналу налагодження використовуваних модулів HostMot2.
- use_serial_numbers [за замовчуванням: 0]
-
При створенні HAL-контактів для інтелектуальних послідовних пристроїв називайте контакти за серійним номером плати, а не за тим, до якої плати і порту вони підключені. Якщо для цього параметра встановлено значення 1, контакти матимуть такі імена, як «hm2_8i20.1234.current», а не «hm2_5i23.0.8i20.0.1.current». Ідентифікатор складається з останніх 4 цифр серійного номера плати, який зазвичай вказано на наклейці на платі. Це зробить конфігурації менш портативними, але означає, що плати можна підключати знову, не дотримуючись таких ретельних вимог.
ОПИС
hostmot2 — це драйвер пристрою, який забезпечує взаємодію прошивки Mesa або litehm2 HostMot2 з LinuxCNC HAL. Сам по собі цей драйвер нічого не робить, для роботи прошивки необхідні власні драйвери. Наразі доступні драйвери для карт з інтерфейсами PCI, Ethernet, SPI та EPP.
Прошивка HostMot2 надає такі модулі, як кодери, генератори PWM, генератори кроку/напрямку та універсальні виводи вводу/виводу (GPIO). Ці елементи називаються «модулями». Прошивка налаштовується під час компіляції прошивки для надання нульової або більшої кількості екземплярів кожного з цих модулів.
Контакти вводу/виводу плати
Прошивка HostMot2 працює на платі FPGA. Плата взаємодіє з комп’ютером через PCI, Ethernet, SPI або EPP, а також взаємодіє з апаратним забезпеченням управління рухом, таким як сервоприводи та крокові двигуни, через виводи вводу-виводу на платі.
Кожен вивід вводу/виводу може бути налаштований під час завантаження драйвера плати для виконання однієї з двох функцій: як конкретний вивід вводу/виводу конкретного екземпляра модуля (енкодер, pwmgen, stepgen тощо) або як цифровий вивід вводу/виводу загального призначення. За замовчуванням усі екземпляри модулів увімкнені, і всі виводи плати використовуються екземплярами модулів.
Користувач може вимкнути екземпляри модулів під час завантаження драйвера плати, вказавши конфігураційний рядок modparam hostmot2. Всі контакти, що належать до вимкнених екземплярів модулів, автоматично стають GPIO.
Всі виводи вводу-виводу мають певну присутність HAL, незалежно від того, чи належать вони до активного екземпляра модуля, чи є повними GPIO. GPIO можна змінювати (під час виконання) між входами, звичайними виходами та відкритими стоками, і вони мають гнучкий інтерфейс HAL. Виводи вводу-виводу, що належать до активних екземплярів модуля, обмежені вимогами модуля-власника і мають більш обмежений інтерфейс в HAL. Це описано в розділі «Вводу-виводу загального призначення» нижче.
параметр модифікації конфігурації
Всі модулі драйверів плат (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 [optional]
-
Завантажте прошивку, вказану в F, у FPGA на цій платі. Якщо рядок «firmware=F» не вказано, FPGA не буде перепрограмовано, але може продовжувати працювати з раніше завантаженою прошивкою.
Запитане мікропрограмне забезпечення F отримується за допомогою udev, яке шукає мікропрограмне забезпечення в системному шляху пошуку мікропрограмного забезпечення, зазвичай /lib/firmware. F зазвичай має вигляд «hm2/<BoardType>/file.bit»; типовим значенням для F може бути «hm2/5i20/SVST8_4.BIT». Файли прошивки hostmot2 надаються пакетами hostmot2-firmware, доступними на 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 [необов’язково, за замовчуванням: ""]
-
Вказує, як буде інтерпретуватися потік бітів від пристрою з синхронним послідовним інтерфейсом. Для кожного підключеного пристрою має бути створено запис. Будуть увімкнені лише канали з визначником формату (оскільки програмне забезпечення не може вгадати швидкість передачі даних та довжину бітів).
- 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 перевищує кількість pwmgens, доступних у прошивці, плата не зможе зареєструватися.
- num_3pwmgens [необов’язково, за замовчуванням: -1]
-
Увімкніть тільки перші N трифазних pwmgens. Якщо N дорівнює -1, увімкнені всі 3 pwmgens. Якщо N дорівнює 0, жоден pwmgen не увімкнений. Якщо N перевищує кількість pwmgens, доступних у прошивці, плата не зможе зареєструватися.
- num_rcpwmgens [необов’язково, за замовчуванням: -1]
-
Увімкніть тільки перші N RC pwmgens. Якщо N дорівнює -1, увімкнені всі rcpwmgens. Якщо N дорівнює 0, жодні rcpwmgens не увімкнені. Якщо N перевищує кількість rcpwmgens, доступних у прошивці, плата не зможе зареєструватися.
- num_stepgens [необов’язково, за замовчуванням: -1]
-
Увімкніть тільки перші N степгенів. Якщо N дорівнює -1, увімкнені всі степгени. Якщо N дорівнює 0, степгени не увімкнені. Якщо N перевищує кількість степгенів, доступних у прошивці, плата не зможе зареєструватися.
- num_xy2mods [необов’язково, за замовчуванням: -1]
-
Увімкніть тільки перші N xy2mods. Якщо N дорівнює -1, увімкнені всі xy2mods. Якщо N дорівнює 0, xy2mods не увімкнені. Якщо N перевищує кількість xy2mods, доступних у прошивці, плата не зможе зареєструватися.
- 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 [optional]
-
Якщо вказано, це вмикає режим необробленого доступу, за допомогою якого користувач може переглядати та завантажувати прошивку з HAL. Див. Режим необробленого доступу нижче.
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 General Reference), та на компонент програмного кодера. Кожен екземпляр кодера має такі контакти та параметри:
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.
Синхронний послідовний інтерфейс (SSI)
(Не плутати з інтелектуальним послідовним інтерфейсом)
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: (Прокладка)
-
Не створює жодних виводів, використовується для ігнорування непотрібних ділянок бітового потоку.
- b: (Булеве значення).
-
(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: (Без підпису)
-
(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: (Підписано)
-
(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: (бітФілд)
-
(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: (Енкодер)
-
(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: (Розділений кодер, старші біти)
-
Деякі енкодери (включаючи Fanuc) розміщують підрахунки частин обертів енкодера та підрахунки повних обертів в окремих, несуміжних полях. Цей тег визначає старші біти такого модуля енкодера. На кожен канал може бути тільки один тег h та один тег l, поведінка з декількома такими каналами буде невизначеною.
- l: (Розділений кодер, молодші біти)
-
Молодші біти (див. "h")
- g: (Грей-код)
-
Це модифікатор, який вказує, що наступний рядок формату закодовано за кодом Грея. Це дійсне лише для типів даних кодувальників (e, h l) та беззнакового (u).
- m: (Багатооборотний)
-
Це модифікатор, який вказує, що наступний форматний рядок є багатооборотним енкодером. Це дійсно тільки для енкодерів (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: (Прокладка)
-
Без параметрів.
- b: (Булеве значення)
-
Без параметрів.
- u: (Без підпису)
-
(real, rw) .<name>-scalemax. The scaling factor for the channel.
- s: (Підписано)
-
(real, rw) .<name>-scalemax. The scaling factor for the channel.
- f: (бітФілд)
-
Без параметрів.
- e: (Енкодер)
-
(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. Наразі драйвер LinuxCNC підтримує пакети даних розміром до 96 біт, хоча модуль Mesa Hostmot2 може обробляти пакети розміром 512 біт. За необхідності можна розширити кількість пакетів, що підтримуються драйвером.
Енкодер Fanuc
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)
-
вказує стан батареї
- .batt_fail-not (bool, out)
-
перевернута версія вищезазначеного
- .comm (uint, out)
-
Абсолютний вихід 0-1023 для комутації двигуна
- .crc (uint, out)
-
Контрольна сума CRC. Наразі HAL не має можливості її використовувати
- .encoder.count (sint, out)
-
Кількість кодерів
- .encoder.index-enable (bool, io)
-
Імітований індекс. Встановлюється параметром кількості обертів
- .encoder.position (real, out)
-
Кількість, масштабована параметром …scale
- .encoder.rawcounts (sint, out)
-
Необроблені підрахунки, на які не впливає скидання або індексація
- .encoder.reset (bool, io)
-
Якщо високе/Істина, то рахунок рахується, а позиція = 0
- .pos_invalid (bool, out)
-
Indicates that the absolute position is not valid
- .pos_invalid-not (bool, out)
-
Перевернута версія
вирішити
Резолвери мають такі імена: hm2_<BoardType>.<BoardNum>.resolver.<Instance>. <Instance> — це 2-значне число, яке для плати 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 зазвичай дає швидкість двигуна в обертах за хвилину (RPS), значення 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 кГц.
один постріл
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 pin swtrigger1 має значення true 2 Зовнішнє апаратне забезпечення: тригер 3 Тригер DPLL: спрацьовує за допомогою вибраного таймера DPLL 4 Тригер частоти: спрацьовує за допомогою вбудованого генератора частоти. 5 Тригер Timer1: спрацьовує за допомогою виходу таймера 1 6 Тригер Timer2: спрацьовує за допомогою виходу таймера 2
- .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 — це модуль вимірювання періоду/ширини/коефіцієнта заповненості. Він може вимірювати період, частоту, ширину імпульсу та коефіцієнт заповненості. Він також може усереднювати показники для фільтрації шуму.
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)
-
Кількість періодів/ширини для усереднення. Від 1 до 4095. Частота оновлення періоду, ширини, шпаруватості та частоти будуть введеними значеннями частоти/усереднення.
- .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)
-
Встановлює частоту PWM головного RC-перетворювача. Максимальна — 1 кГц, мінімальна — 0,01 Гц. За замовчуванням — 50 Гц.
- .width (real, in)
-
Встановлює ширину імпульсу для кожного каналу в (мс/шкала).
- .offset (real, in)
-
Встановлює зміщення ширини імпульсу для кожного каналу в мс. Для сервоприводів з часом імпульсу 1-2 мс для центрального положення 0 це значення має бути встановлено на 1,5 мс.
- .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, який має зворотний зв’язок про поточне положення від першого stepgen другої плати 5I22, має вигляд: hm2_5i22.1.stepgen.00.position-fb (це припускає, що прошивка на цій платі налаштована таким чином, що цей об’єкт HAL доступний).
Кожен степген використовує від 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)
-
фіксована позиція в масштабованих одиницях позиції. Це схоже на "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) генератор кроків видає один повний цикл Грея (00 → 01 → 11 → 10 → 00) для кожного «кроку», який він робить, тому шкала повинна бути розділена на 4 відносно стандартного кроку/напрямку. У табличному режимі до 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, то цей висновок не створюється.
Якщо ця функція доступна, її зазвичай слід увімкнути. Це, як правило, зменшує кількість наступних помилок.
Інтелектуальний послідовний інтерфейс
Інтелектуальний послідовний інтерфейс дозволяє підключити до однієї плати FPGA до 32 різних пристроїв, таких як 3-фазний привід Mesa 8i20 потужністю 2,2 кВт або 48-канальні плати вводу-виводу 7I64. Драйвер автоматично визначає підключений апаратний порт, канал і тип пристрою. Пристрої можна підключати в будь-якому порядку до будь-якого активного каналу активного порту (див. визначення конфігурації 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_<board name>.<board index>.bspi.<index>, e.g., 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 є доступним).
Представлення GPIO hm2 моделюється на основі цифрових входів і цифрових виходів, описаних у Canonical Device Interface (частина документа HAL General Reference). Кожен 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.
Твердотільне реле
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/секунда
- .velx-fb, .vely-fb (real, out)
-
Зворотний зв’язок щодо швидкості X та Y в одиницях повної шкали_позиції/секунда
- .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 не порушується (за винятком конфігурації виводів вводу/виводу). Інстанції енкодера продовжують рахувати квадратурні імпульси, а генератори pwm і step продовжують генерувати сигнали (які не передаються на двигуни, оскільки виводи вводу/виводу стали входами).
Скидання сторожового таймера (шляхом очищення виводу 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
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
Дивіться setsserial(9) для ознайомлення з поточним способом встановлення параметрів smart-serial eeprom.
ФУНКЦІЇ
- hm2_<BoardType>.<BoardNum>.read-request
-
На платах з тривалим часом обробки запитів на читання (на момент написання статті це стосується тільки плат Ethernet) ця функція надсилає запит на читання. При використанні декількох плат це може скоротити час виконання сервопотоку. У цьому випадку відповідним порядком потоків буде
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
-
Це зчитує лічильники енкодера, зворотні зв’язки ступінчастого генератора та вхідні контакти 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 доступна за адресою https://www.mesanet.com.
ЛІЦЕНЗІЯ
GPL