VISA Read on a Serial Device Does not Return the Requested Number of Bytes

Updated Apr 19, 2024

Reported In

Software

  • LabVIEW

Driver

  • NI-VISA

Issue Details

I'm trying to receive some binary data over my serial port using VISA.

For example, I use the VISA Read VI or the viRead() call and request 100 bytes. However, when I look at the data received, I might see that I only get the first 63 bytes. If I do another read, I can get the remaining 37 bytes. I might use the VISA Read VI again, and only receive 54 bytes with the first read, and the remaining 46 bytes on the second read. What's going on?

Solution

VISA Read for serial will return a number of bytes from the serial port buffer to your program. However, the amount of data that it returns depends on 3 important details about your settings and your serial data: your termination character, the amount of data requested, and the timeout period.

Serial VISA Read will stop reading when any of these statements are true:
  1. The number of requested bytes is equal to or less than the number of bytes waiting to be read on the port, OR
  2. The termination character has been received, OR
  3. No more data is available from the serial port and the timeout period has elapsed without any data being received.
For help setting up termination characters in NI-VISA, please see the related links below. 

If you are implementing a standard protocol (like MODBUS) consider using an existing library.

Additional Information

Looking at LabVIEW's serial communication example (NI Example Finder»Hardware Input and Output»Serial»Simple Serial.vi), you will notice that it starts with a VISA Configure Serial Port node. This sets up both the termination character (which defaults to hex 0A ("linefeed")) and the timeout (defaults to 10 seconds).


If you are reading serial data and a byte that matches the set-up termination character, then the VISA Read VI will assume that this must be the end of the requested data and will stop the reading operation. This happens because the second condition above has been satisfied, even though condition 1 has not been satisfied and the VI has not read all of the bytes from the port. 

Using the default termination character usually will not cause issues in normal text communications. However, binary data does not have a special meaning assigned to the 0x0A byte. In the example above this is the reason for the first read operation stop after 63 bytes and leaving the remaining 37 bytes in the software buffer waiting to be read. If you are doing binary data transfers over serial, you will almost always want to disable the termination character on the VISA Configure Serial Port VI. To do so, change the input Enable Termination Char from the VISA Configure Serial Port to False