Labview 2020 v20.0.1 на русском

Содержание

Введение

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

Основное отличие от имеющихся учебных материалов будет заключаться в том, что мы будем изучать этот язык с точки зрения средства разработки «общего назначения». В процессе изложения я буду пытаться также проводить параллели с текстовыми языками чтобы показать некоторые отличия от «традиционных» средств разработки. Для иллюстрации я буду использовать C# (в минимальном варианте, доступном и тем, кто понимает базовый синтаксис языка С). Изложение будет настолько подробным, насколько возможно, по мере углубления в дебри LabVIEW степень «подробности» основ будет уменьшаться. Также потребуется минимальное знание английского — русской локализации LabVIEW пока нет.

Итак, LabVIEW программа собирается из отдельных «кирпичиков», которые называются «Виртуальные Инструменты» («Virtual Instruments») или коротко VI. Первые версии LabVIEW предназначались для превращения ПК в измерительный прибор-инструмент, так что исторически за ними и закрепилось такое вот название. Также как С# программа собирается из отдельных *.cs файлов, также и LabVIEW программа собирается из VI файлов (в классической LabVIEW 2020 у них расширение *.vi, а в NXG — *.gvi). Множественные файлы объединяются в проекты. Единственное отличие — представьте себе, что вы организуете проект таким образом, что в каждом файле лежит только одна функция (ну или метод класса, если будет угодно). В небольшом проекте счёт отдельных виртуальных инструментов может идти на десятки, в проектах средних размеров — на сотни, а в больших проектах — тысячи их (предполагается, что размер кода в каждом отдельном инструменте находится в пределах разумного). Вот сейчас я работаю над проектом, в котором семь с лишним тысяч VI и это довольно большой проект.

При первом запуске LabVIEW NXG покажет нам вот такое окно:

Здесь перечислены шесть основных направлений, в которых применяется LabVIEW. В принципе без разницы, что вы здесь выберете, просто для некоторых направлений разработки или обучения нам рекомендуется «классическая» LabVIEW, а для некоторых — NXG, поскольку функциональность NXG пока проигрывает классической LabVIEW, но команда NI работает в этом направлении, а нам для изучения и NXG хватит с лихвой.

На этот вопрос нужно ответить всего один раз, после этого NXG будет запускаться вот так:

Uninstalling LabVIEW (All Platforms)

When troubleshooting a persistent installation issue, you might choose to uninstall LabVIEW and other NI software to retry installation on a clean machine.

(Windows)

  1. Create a system configuration report in Measurement & Automation Explorer (MAX), which is a hardware configuration program that is installed when you install LabVIEW. The system configuration report records the state of your system before you erase all information about your NI software installations. If you eventually need to file a service request at ni.com/ask, the support engineer who addresses your request may need this information.
    1. Open MAX.
    2. Select File»Export and create a report for your entire system.
    3. Refer to the KnowledgeBase at ni.com for more detailed instructions about creating MAX system configuration reports.
  2. Save the system configuration report and all VIs to an external location, such as a USB or network drive.
  3. Turn off the computer and remove or unplug all NI hardware.
  4. Uninstall LabVIEW 2018 by navigating to the Programs applet in the Control Panel and selecting National Instruments Software. Select and uninstall LabVIEW, modules, toolkits, and device drivers.
  5. Restart the computer.

(macOS)

  1. Save any files that you modified or added to the LabVIEW 2018 directory in another location.
  2. Uninstall LabVIEW 2018 by double-clicking the Uninstall.command shell script file located in the LabVIEW 2018 directory or on the installation media.
Note  If you moved the LabVIEW 2018 directory after installing LabVIEW, LabVIEW does not uninstall and remove the LabVIEW 2018 directory unless you move the directory back to the default location.

(Linux)

Run the UNINSTALL script from the mounted installation media. This script is available only on the installation media.

Project Sublibraries

Project sublibraries are project libraries that another project library owns. The settings in the owning project library do not affect access settings and editing permission for items within the project sublibrary. You can set the access of a project sublibrary file (.lvlib) as private within the owning project library, but when you edit the project sublibrary itself, items the sublibrary owns retain public or private access settings.

Project sublibraries are useful if you want to create a project library that includes separate areas of functionality. For example, if you are creating a project library of graphics tools, you might divide the two-dimensional and three-dimensional drawing tools into separate sublibraries.

Про именование ВП

Ни для кого не секрет, что в классическом программировании всем пользовательским объектам и функциям нужно давать осмысленные имена, то же можно сказать и о LabVIEW, особенно, если в роли объектов выступает SubVI. Я привык имена файлам ВП давать на основе их места в иерархии разрабатываемого ПО. В текущем приложении можно выделить четыре уровня абстракции:

  • Самый низкий уровень — это ВП, выполняющие непосредственное взаимодействие с FTDI, в большинстве своем они сводятся к вызову соответствующей функции из API D2XX. В своем проекте имена ВП этого уровня я начинал с префикса «FT», например FT_Close.vi или FT_Read.vi.
  • Второй уровень — это взаимодействие с процессором MPSSE. Имена ВП этого уровня начинаются с префикса «MPSSE». Пример: MPSSE_open.vi, MPSSE_Set_LByte.vi, MPSSE_Get_LByte.vi.
  • Третий уровень — это реализация протокола «Passive Serial» поверх MPSSE. Все файлы имеют префикс «SР». Например, SP_FT_MPSSE_FPGA.vi (жуткое имя, состоящее из аббревиатур) и SP_LBYTE_BITS.ctl.
  • Уровень приложения. ВП верхнего уровня. Имя может быть произвольным, человекоориентированным.

Если проект достаточно большой (десятки ВП), то для каждого уровня файлы лучше хранить в отдельных директориях с соответствующим названием. В нашем проекте все ВП разместились в одной папке subVI.

LabVIEW NXG 5.0 — Основы и Блок-Диаграмма +10

  • 11.05.20 14:44


AndreyDmitriev

#501406

Хабрахабр


Tutorial

1500

LabVIEW

Это первая статья из небольшого цикла о графическом языке программирования G, который используется в LabVIEW. Язык этот пока не очень популярен — по индексу TIOBE на май 2020 года LabVIEW находится на сороковом месте аккурат между Julia и Haskell. Выпуск LabVIEW Community Edition даёт возможность значительно расширить аудиторию пользователей (раньше можно было пользоваться только триальной версией, а по истечении 45-и дней учиться «вприглядку»).

Что ж, как говорили великие Керниган и Ритчи — «единственный способ научиться новому языку программирования — это начать на нём программировать». Этим и займёмся.

В первой части мы разберём основные элементы среды разработки, и нарисуем на блок-диаграмме наш первый «Hello, World!»

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

Locating Missing SubVIs, Palettes, and Property Nodes (macOS)

LabVIEW may not be able to locate certain subVIs, palettes, or Property Nodes for the following reasons:

  • You did not install the LabVIEW 2018 versions of the drivers used by your VIs. To communicate with hardware devices, LabVIEW 2018 requires that the LabVIEW 2018 versions of the related device drivers be installed. If you do not update your drivers to run with LabVIEW 2018, the associated driver VIs, palettes, and Property Nodes are not available, making it impossible for LabVIEW to communicate with the device. To correct this problem, reinstall the related drivers from one of the following sources:
    • For the latest version of the driver for any NI device—Download the latest version of the driver from ni.com/drivers.
    • For NI-DAQmx Base—Download the NI-DAQmx Base Software at ni.com.
    • For third-party devices—Search for and download drivers for third-party instruments on the Instrument Driver Network at ni.com.
  • Your VIs require files from the user.lib directory of a previous version of LabVIEW. If you created custom VIs in a previous version of LabVIEW, you must copy those VIs to the user.lib directory of LabVIEW 2018 to continue using them as subVIs.

Locating Missing SubVIs, Palettes, and Property Nodes (Windows)

LabVIEW may not be able to locate certain subVIs, palettes, or Property Nodes for the following reasons:

  • You did not install the LabVIEW 2018 versions of the drivers used by your VIs. To communicate with hardware devices, LabVIEW 2018 requires that the LabVIEW 2018 versions of the related device drivers be installed. If you do not update your drivers to run with LabVIEW 2018, the associated driver VIs, palettes, and Property Nodes are not available, making it impossible for LabVIEW to communicate with the device. To correct this problem, reinstall the related drivers from one of the following sources:
    • For most NI devices—Use the NI Device Drivers media packaged with the LabVIEW Platform media.
    • For NI devices not included on the NI Device Drivers media—Use the driver media packaged with the device or download the latest version of the driver from ni.com/drivers.
    • For third-party devices—Search for and download drivers for third-party instruments on the Instrument Driver Network at ni.com.
  • You installed a module or toolkit after you installed the drivers used by your VIs. If you install an add-on, such as LabVIEW FPGA or the LabVIEW Real-Time Module, after installing device drivers, you must modify the device drivers in order for the module to recognize them and their associated VIs. Complete the following steps to modify device drivers:
    1. Navigate to the Programs applet in the Control Panel.
    2. Select National Instruments Software from the list of programs.
    3. Select each device driver and click Modify.
  • Your VIs require files from the user.lib directory of a previous version of LabVIEW. If you created custom VIs in a previous version of LabVIEW, you must copy those VIs to the user.lib directory of LabVIEW 2018 to continue using them as subVIs.

Locating Missing SubVIs, Palettes, and Property Nodes (Linux)

LabVIEW may not be able to locate certain subVIs, palettes, or Property Nodes for the following reasons:

  • You did not install the LabVIEW 2018 versions of the drivers. In order to communicate with hardware devices, LabVIEW 2018 requires that the LabVIEW 2018 versions of the related device drivers be installed. If you do not update your drivers to run with LabVIEW 2018, the associated driver VIs, palettes, and Property Nodes are not available, making it impossible for LabVIEW to communicate with the device. To correct this problem, reinstall the related drivers from one of the following sources:
    • For NI-VISA drivers—Download the latest version of the driver from ni.com/linuxdrivers.
    • For other NI devices—Use the driver media packaged with the device or download the latest version of the driver from ni.com/drivers.
    • For NI-DAQmx Base—Download the NI-DAQmx Base Software at ni.com.
    • For third-party devices—Search for and download drivers for third-party instruments on the Instrument Driver Network at ni.com.
  • Your VIs require files from the user.lib directory of a previous version of LabVIEW. If you created custom VIs in a previous version of LabVIEW, you must copy those VIs to the user.lib directory of LabVIEW 2018 to continue using them as subVIs.

Осваиваем GPIO

После того, как MPSSE активирован, работа с ним осуществляется через так называемые «op-code», а из функций API D2XX используется только , и (чтобы узнать статус буфера приемника). По наторенной дорожке создаем соответствующие VI: FT_Write.vi, FT_Read.vi, FT_Queue.vi.

Теперь из этих трех кирпичиков выкладываем ВП для чтения параллельного порта и записи в него. Значение удобно представить в виде массива булевых переменных.

Как говорилось в самой первой статье протокол загрузки ПЛИС «Passive Serial» есть ничто иное как SPI с дополнительной манипуляцией флагами. Всего используется пять ножек: линии DCLK, DATA, nCONFIG должны быть сконфигурированы как выхода, линии nSTATUS, CONF_DONE — как входы.

Нам понадобится ВП, который сможет менять значение на выбранной ножке не затрагивая все остальные. Первым делом создаем с порядковыми номерами ножек в порту, сохраняем в виде «Strict Type Def» в файл SP_LBYTE_BITS.ctl. Создаем новый ВП, добавляем привычные терминалы потока ошибок. Считываем текущее значение параллельного порта с помощью MPSSE_Get_LByte.vi, с помощью функции модифицируем нужный бит и записываем значение обратно в порт (MPSSE_Set_LByte.vi).

Для начала конфигурации контроллер MPSSE должен генерировать переход из низкого уровня в высокий на линии nCONFIG. Как только ПЛИС будет готова к приему данных, она сформирует высокий уровень на линии nSTATUS. На данном этапе у нас все готово для эксперимента в железе. На блок-диаграмму SP_FT_MPSSE_FPGA.v добавляем управление линией nCONFIG — после инициализации MPSSE подаем низкий уровень, а затем высокий. После каждой операции (для отладки) считываем состояние ножек порта.

В целом, во время запуска VI видно, что ПЛИС реагирует на переход на линии nCONFIG — на ножке nSTATUS устанавливается ноль, а затем единица. Но не будет лишним проконтролировать это с помощью осциллографа. Годится почти любой двуканальный осциллограф с возможностью запуска по триггеру (ждущий режим). Канал А (синий трек) я ставлю в контрольную точку цепи nCONFIG, канал B (красный трек) — цепь nSTATUS. Триггер настроен на спадающий фронт канала A.

Картинка кликабельна. С подробностями!

OS Support

LabVIEW is supported and G source code development can be accomplished on Windows 9x/2000/NT/XP/Vista/7/8/10, Apple Macintosh (including X), PowerMax OS, Solaris, HP-Unix, Sun, Linux, the Pharlap RTOS, and VxWorks RTOS (Real-Time Operating Systems, found on National Instruments embedded controllers). Executables can be compiled under their respective development systems to run on these platforms. Code developed under one platform can be ported to any of the others, recompiled and run*. LabVIEW PDA can run on handheld devices, such as Microsoft Windows Mobile for Pocket PC devices.

*There are of course exceptions to every rule. In this case platform specific sections of the LabVIEW development system will not be transferable. For example, ActiveX or .NET integration which is Windows specific. Furthermore, certain third party device drivers or LabVIEW toolkits installed under one system may not necessarily be available, run, or be recompiled on a different operating system.

Locating Missing Module or Toolkit Functionality (All Platforms)

To use a module or toolkit with LabVIEW 2018, you must install a version of the module or toolkit that is compatible with LabVIEW 2018. Otherwise, the VIs, project items, dialog boxes, and other features associated with the module or toolkit do not appear in LabVIEW.

Complete the following steps to locate and install missing modules and toolkits:

(Windows)

  1. Locate and install the module or toolkit.
    • Modules and toolkits that ship on the LabVIEW Platform media—Insert the LabVIEW Platform media and enter the serial number of the module or toolkit. To determine if a module or toolkit , refer to the LabVIEW Platform Readme.
    • All other LabVIEW modules and toolkits—Follow the .
    • Third-party add-ons—From the Getting Started window of LabVIEW, select Find Drivers and Add-ons»Find LabVIEW Add-ons to access the latest versions of third-party add-ons.
  2. Modify the device drivers. If you install LabVIEW or an add-on after installing device drivers, LabVIEW cannot recognize the device drivers.

(macOS and Linux)

Install a version of the module or toolkit that is compatible with LabVIEW 2018. You can obtain a compatible version of the module or toolkit from the following locations:

  • For NI add-ons—Download the latest version of the add-on from ni.com/downloads.
  • For third-party add-ons—Download the latest version of the add-on from the LabVIEW Tools Network at ni.com.

For installation instructions, refer to the readme file on the installation media of the module or toolkit.

Versions

There are many versions of LabVIEW still in use, although the earlier versions are constrained to hard core dedicated enthusiasts. We have heard whispered mention of the use of Version 3 and there are many active Version 4’s in circulation. More recent additions to the legacy software bin are versions 5.0, 5.1, LabVIEW 6i and 6.1, while the current version as of May 2018 is LabVIEW 2018. In addition there are demo versions available from National Instruments. Starting in 2017 National Instruments announced the creation of the next generation of LabVIEW, called LabVIEW NXG. Currently, LabVIEW NXG has had two releases in 2017 and 2018 which comprises LabVIEW NXG 1.0 and 2.0, respectively.

From version 6.0 onwards NI released the product formerly known as BridgeVIEW as a LabVIEW plugin module called the Data Supervisory and Control module (DSC) and with the advent of real time boards and the release of the Fieldpoint real-time network module, there is also a module that allows writing of code for embedded processors referred to as the Real Time module (RT). Lastly, there are version available for PDA module (for writing code for PocketPC and PalmOS) and the FPGA module for writing code for Field Programmable Gate Arrays (LabVIEW on a chip!). These modules now keep track with the current LabVIEW version.

See more on all of the LabVIEW Versions.

Виртуальный инструмент

Создадим наш первый инструмент, выбрав в меню File->New VI…:

После этого откроется основное окно — это наше рабочее пространство. При первом запуске нам покажут подсказки (если вы их закроете, то для того, чтобы их вызвать снова, надо нажать вопросик в правом верхнем углу).

Элементы рабочего пространства:

В левой части находится дерево для навигации по файлам проекта (Navigation Pane), в середине — основное пространство для программирования (VI), там же слева палитра инструментов (Palette), а справа — свойства для конфигурирования, вид которых меняется в зависимости от выбранных элементов (Configuration Pane), а снизу будет панель ошибок и предупреждений.

Нас в данный момент интересует средняя панель (VI). Вообще Виртуальный Инструмент VI обычно состоит из двух основных частей — Блок-Диаграммы (Block Diagram) и Передней Панели (Front Panel). Переключатель расположен в верхней части — Panel и Diagram (Icon — это иконка инструмента, мы её разберём попозже).

Installing the NI LabVIEW Application Builder (All Platforms)

The instructions for installing the Application Builder depend on which package of LabVIEW you purchased.

  • LabVIEW Professional Development System—The LabVIEW Professional Development System includes and automatically installs the Application Builder. Therefore, you do not install the Application Builder separately. (Windows) During installation, the serial number for LabVIEW also activates the Application Builder.
  • LabVIEW Full Development System or Base Development System—If you also purchased the Application Builder, you receive a separate package for it.
    • (Windows) Install LabVIEW from the LabVIEW Platform media. During installation, you must enter a serial number for the Application Builder. Locate this serial number on the Certificate of Ownership in the LabVIEW Add-On Software package. If you do not activate the Application Builder during installation, it runs in evaluation mode. You can activate the Application Builder after installing LabVIEW from the License Status window that appears when you launch LabVIEW.
    • (macOS and Linux) After you finish installing LabVIEW, insert the installation media for the Application Builder.

Visualize app in graphical programming approach

LabVIEW is a system-design platform and development environment created by National Instruments Corporation for various engineering applications. It provides a graphical programming approach that allows you to analyze and visualize every aspect of it including hardware configuration, measurement data, and debugging. The visualizations that it offers will make the simplest integration of measurement hardware.

This software solution is offered in paid license, but a free trial is available for you to experience what it can offer. You can get it as long as you have an NI user account created. Furthermore, it has powerful interfaces to MATLAB and Simulink.

What is LabVIEW software used for?

LabVIEW gives you the power to control systems, design industrial-grade circuits, deploy controls, develop engineering instrumentation fields, and program measurement systems. It is designed for students, engineers, electricians, professionals, and even simple enthusiasts. Moreover, it enables you to create engineering applications that can work with any of the hardware or instrument.

Thus, it has the capacity to accommodate all types of engineering programming tasks as well. You can opt to reduce the implementation costs for their systems simply through the work formula. You will be capable to also analyze and share data developed from the software. This system development companion comes with software engineering libraries for convenient referencing.

Is LabVIEW free?

As stated, LabVIEW requires you to purchase any of their subscription plans in order to fully use its features and functions.  The paid licenses are recommended especially for professionals that demand the program’s extensive features to attend to the needs of their engineering applications. By far, it offers three editions — LabVIEW Base, LabVIEW Full, and LabVIEW Professional.

You can get LabVIEW Base if you’re dealing with desktop measurement applications as this particular edition includes device drivers for NI hardware and third-party instruments as well as basic mathematics and signal processing. If you are handling apps that require more advanced versions of the mentioned features, LabVIEW Full will suit you best. On the other hand, LabVIEW Professional is an excellent choice if the application requires code validation.        

Best suite for engineering applications

Whether you are a simple aspirant or professional, LabVIEW can accommodate the various needs of your engineering application. Thanks to the graphical programming approach it provides, it truly helps you to easily and efficiently visualize every aspect of your application regardless if it’s internal or external. This will then also aid you to represent complex logic, develop data analysis algorithms, and design custom engineering user interfaces with ease.   

Работа с файлом

ПЛИС готова принять файл конфигурации. А готовы ли мы передать файл в ПЛИС?

LabVIEW содержит обширный набор инструментов для работы с файлами. Не скажу, что функционала хватает на абсолютно весь спектр задач, однако базовые операции типа чтение и запись выполняются легко и приятно. Основной набор VI для работы с файлами можно найти в палитре «File I/O». Для решаемой задачи требуется открыть файл конфигурации, оценить его размер (нам нужно знать, сколько байт отправлять ПЛИС), прочесть его и закрыть. Все просто и друг за другом. Используем ВП , , , , объединяем их цепочкой потока ошибок и — число, типа файлового дескриптора, создается при открытии файла и должно быть передано на вход другим ВП, работающим с этим файлом.

Пока нам некуда утилизировать считанные данные, но если очень хочется проверить работоспособность цепочки, то можно создать индикатор типа и немножко настроить его. В контекстном меню активируем опцию «Hex Display», включаем вертикальный скроллбар (Visible Items -> Vertical Scrollbar) и после запуска наблюдаем содержимое бинарного файла конфигурации.

На блок-диаграмме ВП образовалось две независимые параллельные линии кода, поэтому для них используются раздельные цепочки ошибок. Для того, чтобы свести параллельные потоки в один терминал , используется функция . Эта функция просматривает ошибки на входе сверху вниз (да, там может более двух входных терминалов, растягивается мышкой) и возвращает первую, которую найдет. Если ошибок нет, то возвращает первое попавшееся предупреждение. Если и предупреждений не обнаружено, то на выходе ошибка отсутствует

Важно отметить, что порядок подключения входов определяет приоритет ошибок, и если ошибка возникнет сразу в двух цепочках, то нижняя ошибка будет проигнорирована. К этому нужно относиться внимательно

Если мы попытаемся в ВП верхнего уровня нажать кнопку «Программировать» не выбрав файл, то на вход SP_FT_MPSSE_FPGA.vi поступит пустой путь, что вызовет ошибку «Error 1430. LabVIEW: (Hex 0x596) The path is empty or relative. You must use an absolute path.» Как говорит мой друг детства: «Пустяки, дело-то житейское!». И ошибка эта — вовсе не ошибка, а так, невнимательность пользователя. Останавливать программу и ругаться на него окном с красным крестиком мы не будем, просто удалим ошибку с этим кодом из потока и в диалоговом окне порекомендуем пользователю определиться с файлом. Для фильтрации ошибки используем ВП «Clear Errors» из палитры «Dialog&User Interface». Для вывода сообщения — «One Button Dialog».