Подключение устройства ethernet labview
В данный момент большинство систем управления и сбора данных создаются по принципу деления систем на отдельные функциональные узлы, которые исполняют автономные алгоритмы обработки данных и обмен данными между собой при помощи универсальных программных интерфейсов. Наиболее универсальным способом взаимодействия программных алгоритмов является сеть.
Компьютерные сети позволяют совершать не только взаимодействие разных частей одной и той же системы между собой, а также обеспечивать обмен данными между абсолютно разнородными дополнениями, которые работают на разных платформах. Именно потому компьютерные сети считаются одним из наиболее универсальных средств обмена данными.
Наибольшего распространения приобрели сети с предварительной установкой соединений, в которых используется стек протоколов TCP/IP, хотя в многих случаях успешно применяются простые протоколы сетевого обмена без установки соединения, например UDP.
Вы можете использовать LabVIEW для взаимодействия с низкоуровневыми протоколами, это лучший путь изучения сетевых протоколов «с середины». Применяйте функции TCP/IP, например, для связи с любым другим компьютером, устройством или программой, которые также поддерживают TCP/IP.
LabVIEW поддерживает и TCP/IP,и UDP-протоколы, доступ к которым совершается через палитру Data Communication » Protocols. В LabVIEW также реализованы высокоуровневые функции потоковой передачи данных, их вы найдете в палитре Data Communication » Network Streams.
TCP/IP (Протокол управления передачей данных / протокол Интернета) является основным протоколом для работы в сети Интернет и большинства внутренних сетей.
В данном случае TCP – сокращено от Transmission Control Protocol (Протокол управления передачей данных), a IP — аббревиатура для Internet Protocol (Протокол Интернета). Протокол Интернета разделяет ваши данные на управляемые пакеты, которые называются датаграмами, и решает, каким образом передать их с А в В.
Проблема полагает в том, что протокол Интернета не является «вежливым» и не будет сотрудничать с удалённым компьютером, который может создать проблемы. И как в случае с большим объёмом почты в почтовой службе, протокол Интернета не гарантирует доставку датаграм. Поэтому к протоколу Интернет добавлен протокол управления передачей, который обеспечивает взаимодействие с другими компьютерами и гарантирует доставку датаграм в установленном порядке (что больше похоже на частного экспресс-курьера).
TCP является протоколом с установлением соединения. Это означает, что перед передачей данных вы должны установить связь, используя определённый протокол. При подключении к сайту следует задать его IP-адрес и порт с этим адресом. ІР-адресом является 32-битовое число, которое часто представляется в виде ряда из четырёх чисел, разделённых точками, например, 128.25.0.112. Портом служит число в диапазоне от 0 до 65535. Одновременно вы можете иметь много активных соединений. Если вы уже знакомы с UNIX или использовали программы, которые работают с Интернетом, сказанное не будет новостью.
Developing Communication Applications
1 = acquire data and confirm
2 = send data
3 = get status
4 = close connection
The following image* shows how the server receives these commands. Notice that the same basic TCP functions are included, but surrounding code allows for more complex connections and robust communication.
- A While Loop surrounds the rest of the VI. This allows the VI to handle multiple sequential connections without having to restart after each connection closes. The VI cannot handle multiple simultaneous connections.
- The outer Case structure determines whether a valid connection occurred.
- If a valid connection is not established, nothing happens.
- If a valid connection occurs, the VI enters a While Loop that reads one byte from the TCP/IP port. This byte holds commands 1 through 4 from the client.
- If the connection is valid but no command is received within the read timeout period, the default case of the inner Case structure sends a TRUE value to the continuation terminal of the inner While Loop to keep the connection active.
The following block diagram* shows the other four cases of the inner case statement. Each case handles a specific command that the server can send. Each case sends information to the continuation terminal, which determines whether to continue the loop. In particular, the Quit case always returns a value of FALSE. After leaving the loop, the server closes the connection with the client.
This type of server architecture allows you to develop flexible servers for the more complex network communication procedures. The protocols you develop might be more complex than the preceding example.
* Note that these images are from a previous version of LabVIEW. The colors of data wires and function icons may not match your version. The structure of the code is still applicable.
Internet Protocol (IP), User Datagram Protocol (UDP), and Transmission Control Protocol (TCP) are the basic tools for network communication. The name TCP/IP comes from two of the best-known protocols of the internet protocol suite, the Transmission Control Protocol and the Internet Protocol. With TCP/IP you can communicate over single networks or interconnected networks (Internet).
TCP/IP communication provides a simple user interface that conceals the complexities of ensuring reliable network communications. Refer to the Using LabVIEW with TCP/IP and UDP from LabVIEW Help for more information about how TCP/IP communication works.
Use the TCP/IP functions located on the Functions»Data Communication»Protocols»TCP palette for TCP communication in LabVIEW. As with DAQ, instrument, and File I/O communication, the process involves opening the connection, reading and writing the information, and closing the connection.
With most I/O communication, the processor is always the client that initiates a connection to the disk drive server, the external instrument server, or the DAQ board server. With TCP/IP connections, a computer can function either as the client or the server. The following block diagram represents a client application that initiates a connection to a remote server with TCP Open Connection. The server, or daemon, listens for remote connections and responds appropriately.
LabVIEW users can develop custom applications for TCP/IP communication. The programmer is responsible for developing both the client and the server.
Because anyone can initiate a connection to a server, you might want server access control. The following block diagram shows how the server uses the remote address output value of the TCP Listen VI to determine whether a remote client has permission to access the server.
Configure Ethernet Instrument in MAX
Use Measurement and Automation Explorer (MAX) to create and configure the VISA TCP/IP Resource used to communicate with your instrument.
Open MAX from the Start menu.
Right-click on Devices and Interfaces and select Create New…
In the Create New… window, select VISA TCP/IP Resource. Click Next.
- Select the type of TCP/IP resource to add.
- Auto-detect of LAN Instrument – This option provides a list of LAN instruments found on the local subnet.
- Manual Entry of LAN instrument - Add the IP address and LAN device name for your instrument manually.
- Validate and finish the configuration. There should now be a new VISA TCP/IP Resource under Devices and Interfaces >> Network Devices in MAX in one of the following formats:
- LAN Instrument - TCPIP[board]::host address[::LAN device name][::INSTR]
- Raw Socket Instrument - TCPIP[board]::host address::port::SOCKET
Test Network Communication
Ping your device to make sure you can communicate with your instrument over the network.
Open the Command Prompt from the Start menu.
Type in the following command:
Ping xxx.xxx.xxx.xxx:yyyy
Where xxx.xxx.xxx.xxx is the IP address of the instrument and yyyy is the port. Depending on the instrument, you may not need to specify the port. Press Enter.
If you get a reply response back, you are able to communicate with the instrument and are ready to configure it in Measurement & Automation Explorer (MAX).
Управление прибором через Ethernet
Наверное лучше для ваших целей использовать вот этот интерфейс, так как:
а) Он для этого и предназначен
б) Это сделать намного проще
Перечень дальнейших действий таков:
Установите драйвера на девайс и GPIB адаптер, изучите мануал, найдите систему команд для прибора, посмотрите нет ли готовых примеров для LabVIEW на диске с драйверами (если есть - попробуйте с ними поработать), если нет то см. примеры на слово GPIB в Example Finder. Из примеров попытайтесь получить отклик на команды, если не получается - то из MAX попытайтесь получить отклик на команды.
A Ethernet на этом приборе скорее всего для объединения его с компьютером в локальную сеть, для доступа к носителю информации, а вовсе не для управления им по этому протоколу.
Вот как то так.
п.с. Кстати если вы занимаетесь исследованием проводных коммуникаций, то мы с вами в некотором роде коллеги. Могу посоветовать так же вот этот прибор, возможно он вас заинтересует.
Я подозреваю что Ethernet был выбран автором из-за желания очень удалённо управлять. Например прибор и комп находятся в разных концах здания. Хотя, возможно, я ошибаюсь.
Думаю что Indey прав и для управления он не предназначен.
Indey писал(а): A Ethernet на этом приборе скорее всего для объединения его с компьютером в локальную сеть, для доступа к носителю информации, а вовсе не для управления им по этому протоколу.
Вот как то так.
Как вариант можно купить преобразователь GPIB-LAN National Instruments ENET 100. Подключить прибор по GPIB к преобразователю, а команды уже посылать по локалке. В таком случае всё прекрасно находится в максе.
Наверное лучше для ваших целей использовать вот этот интерфейс, так как:
а) Он для этого и предназначен
б) Это сделать намного проще
Перечень дальнейших действий таков:
Установите драйвера на девайс и GPIB адаптер, изучите мануал, найдите систему команд для прибора, посмотрите нет ли готовых примеров для LabVIEW на диске с драйверами (если есть - попробуйте с ними поработать), если нет то см. примеры на слово GPIB в Example Finder. Из примеров попытайтесь получить отклик на команды, если не получается - то из MAX попытайтесь получить отклик на команды.
A Ethernet на этом приборе скорее всего для объединения его с компьютером в локальную сеть, для доступа к носителю информации, а вовсе не для управления им по этому протоколу.
Вот как то так.
п.с. Кстати если вы занимаетесь исследованием проводных коммуникаций, то мы с вами в некотором роде коллеги. Могу посоветовать так же вот этот прибор, возможно он вас заинтересует.
Большое спасибо за совет Сомневаюсь что мы коллеги. Я студент факультета информационной безопасности. По поводу рекомендуемого вами прибора скажу, что недавнее использование портативного измерителя частоты и мощности заставляет меня немного усомниться в качестве продукции этой фирмы. GPIB адаптер, конечно, хорошо было бы попробовать, но его на кафедре нет((((((((
Software
Connect Instrument to Network
Directly connect the instrument’s Ethernet port to the Ethernet port on the target machine via an Ethernet cable. Refer to your instrument’s user manual for more information.
Driver
This tutorial shows you how to set up NI hardware and software to communicate with an Ethernet/LAN instrument in LabVIEW. Consult the documentation for your Ethernet instrument and make sure you have the correct cable to connect the instrument to the network.
Developing Communication Applications
1 = acquire data and confirm
2 = send data
3 = get status
4 = close connection
The following image* shows how the server receives these commands. Notice that the same basic TCP functions are included, but surrounding code allows for more complex connections and robust communication.
- A While Loop surrounds the rest of the VI. This allows the VI to handle multiple sequential connections without having to restart after each connection closes. The VI cannot handle multiple simultaneous connections.
- The outer Case structure determines whether a valid connection occurred.
- If a valid connection is not established, nothing happens.
- If a valid connection occurs, the VI enters a While Loop that reads one byte from the TCP/IP port. This byte holds commands 1 through 4 from the client.
- If the connection is valid but no command is received within the read timeout period, the default case of the inner Case structure sends a TRUE value to the continuation terminal of the inner While Loop to keep the connection active.
The following block diagram* shows the other four cases of the inner case statement. Each case handles a specific command that the server can send. Each case sends information to the continuation terminal, which determines whether to continue the loop. In particular, the Quit case always returns a value of FALSE. After leaving the loop, the server closes the connection with the client.
This type of server architecture allows you to develop flexible servers for the more complex network communication procedures. The protocols you develop might be more complex than the preceding example.
* Note that these images are from a previous version of LabVIEW. The colors of data wires and function icons may not match your version. The structure of the code is still applicable.
Environment shows products that are verified to work for the solution described in this article. This solution might also apply to other similar products or applications.
Install Instrument Driver
After completing your configuration and verifying communication with the instrument, you can easily transition from interactive mode to programming mode by using an instrument driver.
Refer to Choosing the Right Interface to Control Instruments in LabVIEW to determine which instrument driver type is best for your application. Follow the links in the document to install and use the instrument driver.
Test Communication in VISA Test Panels
After set up and configuration, use VISA Test Panels to verify communication with the instrument and test different instrument commands.
In MAX, select the Tools tab >> NI-VISA >> VISA Interactive Control.
Select the VISA TCP/IP resource of your instrument.
In the Test Panel windows, select the Input/Output tab.
In the Basic I/O tab, input a supported command and select Query. Refer to manufacturer documentation for a valid list of commands to use with your instrument.
The display window will outline the write and read operations.
Install NI Software and Drivers
Install the latest compatible version of LabVIEW and the NI-VISA driver. Refer to the following for compatibility information.
Run an Example
The instrument driver and NI-VISA driver will install examples and the API required to communicate with your instrument. Use these examples as programming references and an easy way to start using your instrument.
Note: Close MAX before you start running a LabVIEW example. Having MAX Test Panels open and running a LabVIEW example simultaneously will result in an access resource error.
Instrument Driver Examples
If you installed an instrument driver, refer to the following examples:
NI-VISA Driver Example
If you are using NI-VISA, refer to the following LabVIEW snippet. This example opens a session to the Ethernet instrument, performs a write of *IDN?\n, reads the specified number of bytes back from the instrument, closes the session, and handles any errors.
Drag the snippet directly onto an empty LabVIEW block diagram.
On the front panel, configure the VISA resource name to be the VISA TCP/IP resource of your instrument previously configured in this tutorial.
For more information on VISA functions, refer to LabVIEW Help: VISA VIs and Functions.
Виртуальные приборы LabVIEW
LabVIEW имеет набор виртуальных приборов, которые находятся в подпалитре TCP палитры Коммуникация. Они позволяют исполнять операции, связанные с ТCP, такие как открытие связи по заданному IP-адресу, перебор текущих TCP-подключений, считывание и запись данных и т.д. Они легкие в использовании, при условии, что ваша сеть настроена правильно (Рис. 1).
Рис. 1. Палитра TCP/IP
Хорошим началом работы по созданию сетевого виртуального устройств с приборами, которые имеются в полной версии LabVIEW: Simple Data Client.vi і Simple Data Server.vi. Их диаграммы показаны на Рис. 2 і 3.
Рис. 2. Блок-диаграмма Simple Data Client.vi
Рис. 3. Блок-диаграмма Simple Data Server.vi Немного познакомится с программой клиент/сервер можно, изучая эти диаграммы. Процесс создания виртуального прибора клиента в основном состоит из трех этапов:
- запрос TCP-соединение. Вы можете установить время ожидания (timeout),чтоб избежать «зависания» программы, если сервер не отвечает;
- считывание (или запись) данных. Данные всегда передаются в виде ряда;
- закрытие ТСР-соединение.
Процесс создания программы сервера также состоит из трех этапов:
- ожидание соединения;
- запись (или считывание) данных. Данные всегда передаются в виде рада;
- закрытие ТСР-соединения.
Hardware
Взаимодействие с сетевым протоколом TCP/IP
Поскольку все данные в сети TCP/IP должны передаваться в виде ряда, возникает необходимость в перевоплощении ваших данных в строковый тип LabVIEW. Самым легким способом для этого является использование функций Приведение типа (Type Cast). Убедитесь только в том, что и клиент, и сервер знают точно, какой тип данных они передают. Если, например, сервер переводит число повышенной точности с плавающей комой в ряд, а клиент пытается преобразовать ряд в число удвоенной точности, то результат будет неправильный.
Если вам нужен общий метод передачи данных, попробуйте воспользоваться изменённым типом данных, преобразованным в ряд. В результате вы будете точно знать, какой тип данных преобразованный (variant). После обратного перевоплощения вы можете проанализировать variant средствами.
Управление распределённой системой сети
Сетевые дополнения очень удобны в таких случаях, когда необходимо написать программу для управления большой распределённой системой.
В дополнение для всех отличных особенностей среды разработки LabVIEW стоит вспомнить то, что они прозрачно работают в сети. Сетевая прозрачность указывает на возможность совершать операции с виртуальными приборами или средой разработки на удаленном устройстве через локальную сеть или Интернет таким же образом, как и на локальном клиентском компьютере. В таком случае необходимо организовать введение /выведение сигналов на удаленном компьютере, в то же время как компьютер на рабочем месте будет анализировать собранную информацию без необходимости разработки любых специальных сетевых программ и описания сложных функций протоколу TCP/IP.
Так, на рис. 4 и 5 показано насколько просто запустить использование программы на удаленном компьютере. Данные функции уже реализованы и входят в палитру Application Control.
Рис. 4. Реализация программы foo.vi на локальном компьютере
Возможности сервера виртуальных приборов исполняются в окружении LabVIEW путем вызова функций блок-диаграммы, подобных наведённым на рисунках выше. Однако сервер тоже предоставляет доступ к собственным функциям с внешних дополнений, будь это алгоритмы Visual Basic или макросы, используя клиент автоматизации ActiveX и с удаленной программы LabVIEW через протокол TCP/IP.
Рис. 6. Архитектура взаимодействия с сервером
Схема на рис. 6 иллюстрирует такую архитектуру. Как можно заметить, согласно этой диаграммы функции сервера виртуальных приборов доступны через функции на блок-диаграммы, внешние ActiveX программы или через удаленный виртуальный прибор с использованием протокола TCP/IP.
Используйте современные решения для профессионально-технических учебных учреждений:
LabVIEW – это передовое окружение разработки и платформ для выполнения программ настоящих ученых и инженеров. Овладевайте серьёзную профессию с школы – изучая конструирование и робототехнику с Lego вы можете и в профессии использовать полученные знания.
Internet Protocol (IP), User Datagram Protocol (UDP), and Transmission Control Protocol (TCP) are the basic tools for network communication. The name TCP/IP comes from two of the best-known protocols of the internet protocol suite, the Transmission Control Protocol and the Internet Protocol. With TCP/IP you can communicate over single networks or interconnected networks (Internet).
TCP/IP communication provides a simple user interface that conceals the complexities of ensuring reliable network communications. Refer to the Using LabVIEW with TCP/IP and UDP from LabVIEW Help for more information about how TCP/IP communication works.
Use the TCP/IP functions located on the Functions»Data Communication»Protocols»TCP palette for TCP communication in LabVIEW. As with DAQ, instrument, and File I/O communication, the process involves opening the connection, reading and writing the information, and closing the connection.
With most I/O communication, the processor is always the client that initiates a connection to the disk drive server, the external instrument server, or the DAQ board server. With TCP/IP connections, a computer can function either as the client or the server. The following block diagram represents a client application that initiates a connection to a remote server with TCP Open Connection. The server, or daemon, listens for remote connections and responds appropriately.
LabVIEW users can develop custom applications for TCP/IP communication. The programmer is responsible for developing both the client and the server.
Because anyone can initiate a connection to a server, you might want server access control. The following block diagram shows how the server uses the remote address output value of the TCP Listen VI to determine whether a remote client has permission to access the server.
Читайте также: