Подключение usb устройства к labview

Обновлено: 04.07.2024

How do I access any USB device in LabVIEW?

‎04-10-2012 04:58 AM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

I have Labview 8.5.It has some blocks to directly control the serial port , but I see NOTHING to let me control devices connected to USB ports. While using VISA functions the USB port is not available in the list at VISA Resource Name Control. I have a device with USB port. I would like to transfer data to/from the device through USB port using LabVIEW.Does someone have some suggestions for how I can gain access to the USB port in a way that will allow LabVIEW to directly communicate with the device connected to the USB port?

‎04-10-2012 05:13 AM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

Did you search about USB communication through labview?

You have to first configure your VISA to recognise the USB

Here is a starting point..

‎04-10-2012 05:16 AM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

Also follow this thread and see the links given in the thread

‎04-10-2012 05:20 AM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

Some devices that connect via USB are visable to the OS as virtual serial ports. In this case you would use VISA to open a serial session and communicate.

There are several threads on the forums dealing with performing RAW communications over USB. The series of 'nuggets' by Intaris are excellent, but be aware that you need some experience with LabVIEW in general before diving in.

Without some basic information about the device (mfgr & model), it will be difficult to help.

Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
If you don't hate time zones, you're not a real programmer.
"You are what you don't automate" Inplaceness is synonymous with insidiousness
  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

As per following the procedure mentioned in the tutorial, the device I connected through USB is not visible in the list of devices in MAX.

‎04-19-2012 09:46 AM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

Before you went and created the VISA driver, did you check in windows device manager to see if a driver wasa already installed?

‎04-19-2012 11:15 PM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

Yes i have checked it. It shows the device in Human Interface Devices list. After installing the VISA driver by following steps as per tutorial, It is listed in Universal Serial Bus controllers list.

‎05-29-2019 09:49 AM - edited ‎05-29-2019 10:07 AM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

Nothing like responding to a 7 year old post but just in case anyone runs across this with the same problem -- You need to set up a virtual com port for your USB device. Go to the device manager and locate your device under "universal serial bus controllers", then right click and select "properties", select the "advanced" tab, check the "load VCP" box (VCP stands for virtual com port). Then check "Ports (COM & LPT) under device manager. There should be a new (virtual) com port associated with your device. Communicate with it using normal VISA serial commands.

------------------------------
All statements are my opinion and worth every cent you paid for them.
Tom Whitaker, CLD
- - - - - - - - - - - - - - - - - - - -
"Give every man thy ear but few thy voice."
Polonius in Hamlet.
rolfk

‎05-30-2019 07:00 AM

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Email to a Friend

Except that the USB VCP (Virtual Com Port) is not an option for most devices that are recognized as USB HID (Human Inderface Device). USB is for the most part an electrical standard (with some basic communication infrastructure standardized too). But a USB Video Camera has VERY different requirements in data transfer than an USB Keyboard or Mouse and again different from a USB serial communication link.

That is why USB defines many different device profiles and each of them uses one or more endpoints (data ports) and for each endpoint one of the protocol methods (bulk, interrupt, and isochronous). A USB VCP driver will never attempt to connect to a USB HID device. Theoretically a device can support multiple USB device profiles in parallel as USB allows discovery of devices and their device profile but that is not done very often.

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

Также среда разработки LabVIEW очень удобна для радиоинженеров и научных работников, потому что имеет в своем составе множество готовых инструментов (для создания ПИД-регуляторов, обработки звука, изображений и множества других приложений), да и в целом работа в LabVIEW для людей, не посвящённых в тонкости программирования, намного проще, чем в том же Delphi или Visual Studio.

Изучая управление микроконтроллерами по шине USB на основе библиотек V-USB и LibUSB, у меня возник вопрос – как управлять разрабатываемым USB-устройством из LabVIEW, и возможно ли это вообще?

Выяснилось, что в LabVIEW можно просмотреть все доступные функции libusb0.dll (основная DLL библиотеки LibUSB). Чтобы начать использовать функции библиотеки libusb, нужно научиться работать с типом данных handle в LabVIEW. Довольно простое решение нашлось на одном англоязычном форуме – оно заключалось в преобразовании handle в числовой тип, см. [1]. Читая статью [2] об управлении макетной платой из программы на Delphi, я подумал, что наверно можно сделать такую dll-ку в Delphi, которую потом использовать в LabVIEW для управления устройством USB. Эта DLL (назовем её V-USB-LabVIEW.dll) будет обращаться к libusb0.dll и управлять микроконтроллером ATmega32 по протоколу USB. Все манипуляции с handl-ами, PID, VID, адресами, байтами и т. д. будут происходить внутри V-USB-LabVIEW.dll. Получается следующая схема взаимодействия:


За основу для создания V-USB-LabVIEW.dll взял почти без изменений пример программы useport от Vanoid-а [2], и готовую прошивку для контроллера от Сергея Кухтецкого [3]. Скомпилированную DLL, её исходный код и пример программы LabVIEW можно скачать по ссылке [4]. Теперь коротко о содержимом исходного кода DLL. Работу программ испытывал на макетной плате AVR-USB-MEGA16, на которой установлен микроконтроллер ATmega32A (в память микроконтроллера через USB-бутлоадер была залита прошивка Сергея Кухтецкого).

В начале кода V-USB-LabVIEW.dll объявлены используемые константы, функции и процедуры из проекта useport: usbGetStringAscii, usbOpenDevice, SendUSBControlMessage. Они нужны, чтобы обратиться к нужному устройству USB. В процедуре SendUSBControlMessage объявлены также PID и VID устройства USB в виде строковых констант. Я добавил функцию PortX_Write, которая будет вызываться в LabVIEW. На примере обращения к порту PB0, к которому подключен светодиод на макетной плате AVR-USB-MEGA16, эта дополнительная функция в проекте DLL на Delphi выглядит так:

function PortX_Write (Address:integer;on_off:integer): integer; stdcall;
var data: array [0..2] of char ; //AVR отправляет обратно max 3 байта
bit: byte ;
begin
// Порт PB0 со светодиодом
if Address = 0 then
begin
// Читаем состояние ножек порта В
SendUSBControlMessage(USB2PC,RQ_IO_READ, 0, aPORTB, 0, data);
bit := bit0;
if on_off = 1 then
data[0]:= char ( byte (data[0]) or bit)
else
data[0]:= char ( byte (data[0]) and ($FF-bit));
SendUSBControlMessage(PC2USB, RQ_IO_WRITE,
byte (data[0]), aPORTB, 0, data);
end;
result := 1;
end;

// Далее идет экспорт функций dll для последующего
// использования в LabVIEW
exports PortX_Write;

Функция PortX_Write имеет два аргумента: первый Address – определяет порт, которым нужно управлять. Светодиод на макетной плате подключен к порту PB0, и для него используется адрес 0. Для всех остальных портов P1..P22 макетной платы (которые подключены к разрядам портов A, B, C, D микроконтроллера ATmega32) используются значения от 1 до 22 соответствуют портам макетки P1..P22). Второй аргумент on_off – состояние, в которое порт нужно перевести. Например, чтобы подать питание на светодиод (зажечь его), в параметре on_off нужно передать 1, и чтобы погасить светодиод, надо передать 0. В параметре Address соответственно должен быть 0 (адрес порта светодиода).

А кто-нибудь пользовалься инструментами на закладке VISA USB?

Как с ними, в принципе, работать? Годятся ли они для любого устройства, подключенного к USB-порту, или только для определённых продуктов National Instruments? Существуют ли примеры их использования и русско-язычное описание (можно и англоязычное, но понятное, а не ограничивающееся отговорками "VISA Resourse Name - имя ресурса VISA")?

Я читал документацию отсюда (Using NI-VISA 3_0 to Control Your USB Device) и даже проделывал все действия по конфигурации, там описанные, но после создания файла *.inf не удалось инсталлировать его в системе (ошибка). Соответственно, LV не видело моё устройство ни в MAX-е, ни программным поиском доступных VISA-устройств.

Пока продолжаю биться над этим и с радостью выслушаю ваши советы и рекомендации!

К сожалению, здесь все не так уж просто. С помощью процедуры, описанной в Using NI-VISA 3_0 to Control Your USB Device, вы можете написать inf-файл, с помощью которого можно будет установить драйвер LabVIEW для USB устройства. Но! Это Вы сделать не сможете, если у Вас уже установлены драйвера устройства в ОС или, в особенности, если это устройство стандартного класса, например, мышь - они имеют системные драйвера с более высоким приоритетом.

Но даже если Вам
1. удалось удалить старые драйвера
2. создать inf-файл и установить стандартный драйвер LV
3. увидеть в Measurement & Automation Explorer Ваше USB-устройство,
то Вам необходимо знание протокола обмена данных между USB-устройством и компьютером по USB-шине для дальнейшего программирования. Это не последовательный порт!

Могу пожелать успехов, если намерены разобраться. У меня руки до этого не доходили, но могу подтвердить, что сие реально. Тому есть замечательный пример - управление контроллером шагового двигателя средствами VISA-USB. Там есть ссылка на LV софт в виде VI.

А нужен ли вообще USB порт?!
Если у Вас устройство, которое подключаете к USB порту, является нестандартным (не имеет драйвера), то без драйвера не удастся определить устройство и работать с ним. Для этого как минимум придется написать собственный драйвер. А это не так уж просто и займет некоторое время.
В принципе, есть техническое решение данной проблемы:
могу предложить попробовать подключить USB - RS232 адаптер, а там уже получать доступ к ресурсам устройства через обычный COM порт.

Один из примеров USB RS-232 Serial Adapter или USB Serial Adaptor Converter можно найти здесь .

Привет! Мы работаем с USB устройствами и без проблем подключаем передаём данные в LabView. Опишите подробнее в чем у вас проблема, может смогу помочь. функции в закладке VISA USB используются для управления связью по USB, тоесть передают на ваше устройства команты управления (какой протокол используется, позволяют получить имя устройства, производителя и т.п.), для передачи данных используются другие функции.

Павел, я не согласен с тем что вы написали. По крайней мере, я подключая устройство, сначало ставлю драйвер устройства для ОС. после того как Windows нормально определит устройство. Запускаю VISA иделаю нужные установки там, и автоматически создается нужный inf-файл. и далее устройство будет видеться уже как NI device, и с ним нормально можно работать из LabView. И данные передаются не сложнее, чем через последовательный порт.

__________________
Ты знаешь все, что надо знать,
Мы знаем чуть больше, чем надо.

УГТУ-УПИ Радиофак,
Уральский региональный центр технологий NI
г.Екатеринбург, ул. Мира 32, оф.428

Последний раз редактировалось Rover, 18.01.2006 в 14:36 . To OLEG.Интереса ради, какое устройство подключаете? Для связи по USB используем микросхемку FT8U245AM, драйвер используем который предлагает производитель (FTDI). А вообще все устройство в целом, должно обеспечивать беспроводную связь ZigBee.

__________________
Ты знаешь все, что надо знать,
Мы знаем чуть больше, чем надо.

УГТУ-УПИ Радиофак,
Уральский региональный центр технологий NI
г.Екатеринбург, ул. Мира 32, оф.428

поробовал подключить USB мышку. подключилась. правда курсор перестала двигать, но это естественно. данные не получилось от неё принять, как будет время попробую ради интереса с ней поработать из LabView

__________________
Ты знаешь все, что надо знать,
Мы знаем чуть больше, чем надо.

УГТУ-УПИ Радиофак,
Уральский региональный центр технологий NI
г.Екатеринбург, ул. Мира 32, оф.428

Как вы могли дагадаться, данная тема связана с темой Как из LV вызвать функции WinAPI. Эта связь выражается не только их автором, но и задачей, требующей решения.
Просто соседняя тема была альтернативным вариантом решения (способ № 1), когда мой "напарник" написал драйвер для USB-устройства, а я из LabVIEW считывал данные через этот драйвер при помощи функций WinAPI.
Каких-то результатов мы добились, но работы ещё предстоит много.

В текущей теме я поднял вопрос использования NI-VISA USB (способ № 2), чтобы уяснить для себя, какой способ решения лучше и проще?

Итак, возвращаюсь к постановке задачи.
Имеется цепочка "АЦП / USB-микропроцессор / компьютер".
USB используется для обеспечения большой скорости передачи (до 250 кГц).
Используются четыре конечные точки:
0. - управляющая (control in/out) - 32 байт максимальный размер пакета;
1. - текущего состояния устройства (bulk in) - 8 байт размер пакета;
2. - конфигурирующая (bulk out) - 8 байт размер пакета;
6. - данные (isochronous in) - 500 байт максимальный размер пакета.

СПОСОБ № 1.
Был взят стандартный USB-микропроцессор AT89C5131 фирмы ATMEL.
В принципе, для него есть и подробное описание (в книге Павла Агурова "Интерфейс USB, практика использования и программирования"), и драйвер ATDriver.sys, разработанный автором книги.
Но для нашей задачи было решено, что этот драйвер не подходит, и назрела необходимость написания собственного драйвера, чем мой коллега и занимался (до сих пор драйвер не доведён "до ума").
Про работу с ним через функции API я уже рассказывал.

СПОСОБ № 2.
Я же со своей стороны, попробовал докопаться до USB-устройства через LV & VISA.
С помощью программы VISA Driver Development Wizard я создал файл AT89_WDM.inf, поместил его в папку C:\WINDOWS\INF.
Произвёл действие Install, которое неизбежно выдало ошибку (см. рис.1), но в результате создало файл AT89_WDM.PNF.
Параллельно я обнаружил, что эти файлы связаны с файлом С:\WINDOWS\system32\drivers\NiViUsbK.sys.
Помучавшись с Диспетчером устройств Windows (разные варианты установки драйвера), попробовав втыкать кабель в разные USB-порты и несколько раз перезагрузившись, я обнаружил, что сэмулированный "Визардом" драйвер всё же установился и моё устройство стало видно и в Диспетчере Windows (см. рис.2), и (о, чудо. ) в MAX-е (см. рис.3).
Таким образом, я получил VISA Resource Name для своего устройства: USB0::0x03EB::0x5803::0.0.0::RAW

Теперь устройство можно найти программно из LV (Visa Find Resources), и посмотреть некоторые его свойства (Property Node).
Эти "проперти ноды" я пока не умею нормально настраивать.
Но главное, я по-прежднему в тупике по поводу решения вышеописанной задачи способом № 2.
Может, Олег (Rover) чем-нибудь поможет (советы по функциям для передачи данных, настройке их параметров и т.п.).

PS: Стану ли я компьютерным "гуру", если прочитаю все 553 страницы книжки по USB.

The National Instruments USB-8451 is an interface for connecting to and communicating with I2C, SMBus, and SPI devices. With plug-and-play USB connectivity, the NI USB-8451 is a portable solution to communicate with consumer electronics and integrated circuits. It also includes eight general-purpose digital I/O lines for a variety of applications, such as configuring the address of I2C devices or toggling LEDs.

The USB-8451 can be physically located more closely to I2C/SPI devices than PCI interfaces, reducing I2C bus length and minimizing noise problems. Additionally, the interface provides +5 V and GND to power circuits up to 230 mA with no external power supply.

Device Addressing

A control byte is the first byte received following the Start condition from the master device. The control byte consists of a 4-bit control code, typically set as ‘1010’ binary for read and write operations. The next three bits of the control byte are the Chip Select bits (A2, A1 and A0).

The Chip Select bits allow the use of up to eight devices on the same bus and are used to select which device is accessed. The Chip Select bits in the control byte must correspond to the logic levels on the corresponding A2, A1 and A0 pins for the device to respond. These bits are in effect the three Most Significant bits of the word address.

The last bit of the control byte defines the operation to be performed. When set to a one a read operation is selected and when set to a zero a write operation is selected.

Example of the control byte format

Basic LabVIEW API for Device Addressing
Use the property node to define the device address. If only one slave is connected to CS 0 the address is typically h50 (1010000- see control byte format above). The configuration output goes then to the high level Write, Read or Write/ Read VIs.

Property Node for 845x Basic API

Advanced LabVIEW API for Device Addressing
Use the Script Address + Write or + Read Functions after a Script Issue Start function to program the device address.

Write Operation

Byte Write
Following the Start condition from the master, the control code (four bits), the Chip Select (three bits) and the R/W bit (which is logic low for write operations) are clocked onto the bus by the master transmitter. This indicates to the addressed slave receiver that the address byte (for single address byte) or bytes (for two address bytes) will follow after it has generated an ACK bit during the ninth clock cycle.

Therefore, the next byte transmitted by the master is the high byte of the word address and will be written into the Address Pointer. The next byte is the Low Address Byte. After receiving another ACK, the master device will transmit the data word to be written into the addressed memory location. The slave ACKs again and the master generates a Stop condition. This initiates the internal write cycle (from the buffer to the memory) and during this time, the Slave will not generate ACK signals.

Example of a Byte Write

Page Write
The write control byte, word address and the first data byte are transmitted to the slave receiver in the same way as in a Byte Write. But instead of generating a Stop condition, the master transmits up to 127 additional bytes, which are temporarily stored in the on-chip page buffer and will be written into memory after the master has transmitted a Stop condition. After receipt of each word, the seven lower Address Pointer bits are internally incremented by one. If the master should transmit more than 128 bytes prior to generating the Stop condition, the address counter will roll over and the previously received data will be overwritten. As with the Byte Write operation, once the Stop condition is received, the internal write cycle will begin (from the page buffer to the memory). Refer to Figure 8 for an example of a Page Write.

Example of a Page Write

Note: You need to look at the page size of your chip!

Page Write operations are limited to writing bytes within a single physical page, regardless of the number of bytes actually being written. Physical page boundaries start at addresses that are integer multiples of the page buffer size (or ‘page size’) and end at addresses that are integer multiples of [page size – 1].

If a Page Write command attempts to write across a physical page boundary, the result is that the data wraps around to the beginning of the current page (overwriting data previously stored there), instead of being written to the next page as might be expected. It is therefore necessary for the application software to prevent page write operations that would attempt to cross a page boundary.

Basic LabVIEW API for Write Operations
The basic write operation takes the device descriptor, the configuration reference (including the device address) and uses a data byte array to write the data bytes to the address specified in the first two bytes.

The write functions acts like it is described above. To write to single byte addresses use a U8 integer instead of the U16 for the first data byte.

Example of 845x Basic API Write Operation

Advanced LabVIEW API for Write Operations
Use the Script write function twice to write the EEPROM Start address and the data bytes, followed by the Issue Stop function to have the same result as using the basic function.

Example of 845x Advanced API Write Functions

Read Operation

Read operations are initiated in the same way as write operations with the exception that the R/W bit of the control byte is set to ‘1’. There are three basic types of read operations: current address read, random read, and sequential read.

Example of Current Address Read Operation

Random Read
Random Read operations allow the USB-8451 to access any memory location in a random manner. To perform this type of read operation, first the word address must be set. This is done by sending the word address to the slave as part of a write operation (R/W bit set to ‘0’). After the word address is sent, the master generates a Start condition following the ACK. This terminates the write operation, but not before the internal Address Pointer is set. Then, the master issues the control byte again but with the R/W bit set to a one.

Example of Random Read

To provide Sequential Reads, a slave normally contains an internal Address Pointer which is incremented by one at the completion of each operation. This Address Pointer allows the entire memory contents to be serially read during one operation. The internal Address Pointer will automatically roll over from address FFFF to address 0000 if the master ACKs the byte received from the array address FFFF.

Example of Sequential Read

Basic API for Read Operations
For the Basic API, we have two different VIs to reflect two different ways to read data. The easiest way is to read the current address as described in the Read Operations section. Therefore you need to use the Read VI and the Read process starts at memory address ‘0’ and the next time behind the last address you read. This is because you do not specify which start address to use and the slave uses his address counter that maintains the address of the last word accessed.

Example of 845x Basic API Read for Current Address

The second way to read data using I2C is using the Write/Read Function. For the Random and Sequentially Read this function performs a Write to specify the Start address to read from and a Read to read the data from this address. The Random Read reads only a single byte on a random position specified by the start address. The Sequentially Read reads as much data as specified with Number of Bytes to Read.

Example of 845x Basic API Read Write for Random and Sequentially Read Address

Advanced API for Read Operations
The 845x Advanced API allows you to script individual functions. For the Current Read, you have to write the address together with the read bit ‘1’, before you can read from the current address. For the Random and Sequentially Read you have to write the address and the write command bit ‘0’ before you can write the Start address. Then you have to write the address again together with the read bit ‘1’ to read any data. Both operations are separated by the Issue Start command.

Example of 845x Advanced API for Current Read

Example of 845x Advanced API for Random or Sequentially Read

Finding Examples

Where to find examples on a Windows XP system:

Open LabVIEW » Help » Find Examples . » Hardware Input and Output » I2C and SPI

C:\Program Files\National Instruments\CVIXX\samples\ni845x

Microsoft Visual C/C++ 6.0

C:\Program Files\National Instruments\NI-845x\MS Visual C\Examples

Note: To find the shipping examples on your computer, you will need to download the NI-845x Driver which can be found in the Related Links section.

SPI Bus

The SPI bus is a four-wire, full-duplex serial interface. Three of the wires, SCK, MOSI, and MISO, are shared along with a fourth wire, known as the chip select, which is a direction connection between the master and a single slave.

Communication across SPI uses a system known as data exchange. Whenever a bit is written to an SPI device across the MOSI lines, the SPI device concurrently returns a bit on the MISO line. Because data is transferred in both directions, it is up to the receiving device to know whether the received by is meaningful or not. For example, to receive data from an EEPROM, the master must configure the EEPROM to send n bytes of data and then must send n bytes to be exchanged for valid data. These bytes can usually be any value, and writing them serves only to clock the data out of the receiving device.

Читайте также: