A common design pattern is to communicate over serial using a simple packet protocol of the form:
[packet header (any number of bytes)] [payload length (1 byte)] [payload (payload length bytes)] [checksum (1 byte)]
Here, we share VIs that will automatically write and read packets of this form using NI-VISA.
In VISA Write Simple Packet.vi, a payload and packet information (header and whether or not to include a checksum) are passed in. The VI writes the header, the size of the payload, the payload, and (optionally) a checksum value to the VISA port. NOTE: The [payload length] field is 1 byte long, meaning only payloads of 255 bytes or less may be used.
Figure 1: VISA Write Simple Packet.VI
In VISA Read Simple Packet.vi, the serial port is read until a packet is received (or a timeout occurs). The header, payload size, and checksum are verified, and erroneous content is discarded. This VI is optimal with respect to packet loss; it will align with the serial stream in as few bytes as is possible, and will never discard a good packet. NOTE: This VI must be called at a rate equal to or (preferably) higher than the rate at which packets are transmitted, or the VISA port will overflow.
Figure 2: VISA Read Simple Packet.vi
Typical use is for one device to write and another to read; a simple illustration is to use a desktop computer with two serial ports connected together in a loopback configuration:
Figure 3: Simple read/write example for a desktop computer with two serial ports in a loopback configuration.
2011-11-29: Initial posting.
2011-12-13: Fixed bug where payload size element was not correctly removed from stream. Added indicators for checksum passed, failed, and bytes discarded.