LabVIEW serial acquisition block diagram overview, LabVIEW serial reader, NI-VISA, COM port data

Get Continuous Data From COM Port in LabView

1.7M Views
40
700
60
25
60
PCBWay

Hello friends! Today, we will receive continuous data from a COM port in LabVIEW and display both the incoming text and its individual values. This is a useful first step when connecting a microcontroller, measurement instrument or serial sensor to a computer.

Our original example receives comma-separated values and places them in a one-dimensional array. We will keep that flow, but also explain how the program knows where one complete record ends. Without that step, a serial reader can appear to work during a short demonstration and then occasionally display incomplete or mixed measurements.

We will start with the software and serial settings, build the front panel and block diagram, then discuss parsing, timeouts and stopping the reader cleanly. The original VI remains available near the end for reference. Its screenshots show an older LabVIEW interface, so menu locations may differ in your installed version.

LabVIEW serial acquisition block diagram overview, LabVIEW serial reader, NI-VISA, COM port data
Figure: LabVIEW serial acquisition block diagram overview.

What Does Continuous Serial Data Look Like?

A serial port transports bytes in order. It does not inherently know that three numbers belong to one measurement or that a comma separates two channels. Those rules come from the sending device's protocol. Before placing a VISA Read block, write down the exact format your device sends.

For this tutorial, assume the sender transmits three decimal numbers separated by commas, with a line-feed character after each record. A displayed example is 120,221,312. On the wire, the final byte is LF, hexadecimal 0A. Some senders use carriage return followed by line feed; our parser can remove the optional carriage return after receiving a complete line.

Protocol itemExample choiceReason to define it
FieldsThree numeric valuesThe receiver knows the expected array length
Field separatorCommaThe parser can separate values
Record terminatorLFThe receiver can identify complete records
Decimal separatorPeriodDecimal numbers remain distinct from field separators
Maximum record length64 bytes for this exampleThe reader has a defined bound for malformed input
Nominal record interval100 ms for a demonstrationTimeout and display behavior can be chosen sensibly

These values are an example protocol, not a requirement imposed by LabVIEW. If your instrument sends binary packets, fixed-length records or responses only after a command, adapt the reader to that protocol. A comma-based text parser is not suitable for arbitrary binary data.

Install LabVIEW and Compatible Serial Support

Install the LabVIEW edition and license appropriate to your work, then install a compatible NI-VISA package with LabVIEW development support. Check NI's compatibility information for your operating system and software combination. The old article's specific trial duration and 2014 driver download are historical details, not current installation requirements.

NI-VISA provides the serial communication interface used by the VI. The USB-to-serial device may also need its own operating-system driver. These are different layers: first the computer must recognize the device and expose a port, then the application can open that resource through VISA.

  1. Connect the serial device or its USB adapter.
  2. Confirm that the operating system shows the intended COM port.
  3. Install the compatible NI-VISA development support if the VISA blocks are missing.
  4. Close any terminal or Serial Monitor that already has the port open.
  5. Record the sender's baud rate, data bits, parity, stop bits and flow-control requirements.

A USB-to-UART adapter and an RS-232 adapter are not electrically equivalent. Use an adapter matching the device's signal levels. LabVIEW's COM-port settings cannot correct a hardware voltage mismatch.

Create a Blank VI

Open LabVIEW and create a blank VI. The front panel contains the controls and indicators that the user sees. The block diagram contains the functions and wires that implement the program. The following images preserve the original project-creation steps.

LabVIEW start screen for creating a serial project, LabVIEW serial reader, NI-VISA, COM port data
Figure: LabVIEW start screen for creating a serial project.

Creating a blank LabVIEW VI, LabVIEW serial reader, NI-VISA, COM port data
Figure: Creating a blank LabVIEW VI.

Give the VI a meaningful name and save it in a project folder before making substantial changes. Keep the sender's protocol description beside it. A VI file alone cannot tell a future reader what a third-party device was configured to transmit.

Build the Front Panel

Add a VISA resource-name control for selecting the port, numeric controls for baud rate and timeout, and a Stop button. Add a Start Reading control if you want the same interaction as the original example. For output, create a string indicator named Response and a numeric array indicator named Data 1D.

Also add a small status indicator and counters for valid and rejected records. These make failures visible without forcing you to inspect every wire during execution. A stopped sender should not look identical to a sender repeatedly reporting the same valid measurement.

Front-panel itemRole
VISA resource nameSelects the actual COM port
Baud rate and serial settingsMatch the sending device
Start ReadingEnables the acquisition behavior you define
ResponseShows a complete received text record
Data 1DShows validated numeric fields
Valid and rejected countsExpose data quality during operation
Stop and statusEnd the session and explain its current state

Configure VISA Once Before the Read Loop

Place VISA Configure Serial Port before a While Loop and wire its VISA session and error output into the loop. Set the baud rate and frame settings explicitly to match the device. Do not repeatedly configure the port on every iteration; configuration belongs to the start of the acquisition session.

For the LF-terminated example, enable the termination character and set it to hexadecimal 0A. Choose a finite timeout, such as 500 ms for a sender normally producing a record every 100 ms. That is an example starting value; startup delays and device behavior may justify a different setting. The VISA Configure Serial Port reference documents these inputs.

Wire the session reference and error cluster through the read operation and onward to cleanup after the loop. Dataflow wiring establishes the order of dependent operations. Merely placing a configuration block visually to the left of a read block does not create an execution dependency.

Read Complete Records

Inside the While Loop, use VISA Read with a byte count large enough for the maximum legal record, for example 128 bytes for our 64-byte record limit. With termination enabled, a shorter complete line can return before that byte count is reached. NI explains the interaction of termination, byte count and timeout in its NI-VISA termination-character guide.

The original block diagram is retained below. Treat its serial reading and comma splitting as the starting idea, then incorporate the record checks described here when rebuilding the VI.

Original VISA serial reading and comma-separated data block diagram, LabVIEW serial reader, NI-VISA, COM port data
Figure: Original VISA serial reading and comma-separated data block diagram.

Do not use Bytes at Port as if it reports the size of a complete message. It reports the amount currently buffered. One check might find the first half of a line, and another might find several complete lines. A message boundary must come from a terminator, fixed length, length field or another documented protocol rule.

Handle Partial Reads Explicitly

A read can return partial data when it reaches a limit or times out. Keep a pending string in a shift register if you need to preserve that partial input. Append new bytes, extract complete LF-terminated records, and retain the unfinished tail for the next iteration. Process every complete record found in the accumulated input.

Apply a maximum pending-buffer length. If a sender stops providing terminators, blindly appending data forever creates a memory problem. Mark the malformed record, discard through the next known boundary and resume with a clearly defined resynchronization rule. Do not silently splice the tail of one oversized record onto the start of another.

Read bytes from VISA
Append bytes to pending text
While pending text contains LF:
    Remove one complete line
    Remove its line ending
    Validate its fields
    Publish a valid record or count a rejected record
Keep only the unfinished tail
Enforce the maximum pending-record length

In a simple terminated-read design, most calls will return one complete line. The accumulation rule still explains what to do when a timeout occurs halfway through a record. If you choose instead to discard partial records, document that choice and discard through the next boundary before accepting another measurement.

Convert the Comma-Separated Text into Numbers

After isolating a complete line, remove its LF and optional CR, then split the fields at commas. Require exactly three nonempty fields for this example. Convert each field using a numeric parser appropriate to your format, checking its error result and that the complete field was consumed.

LabVIEW's string and numeric conversion functions can help with this step, but a conversion result alone is not a complete validity check. For example, 12abc, an empty field and a legitimate zero must not all become an apparently valid zero-valued measurement. Define what the sender is allowed to transmit and reject anything outside that format.

Once all three fields are valid, build or populate a one-dimensional numeric array. With the example record 120,221,312, index 0 contains 120, index 1 contains 221 and index 2 contains 312. LabVIEW arrays use zero-based indices, so the third value is not at index 3.

If using a spreadsheet-string conversion function, configure the delimiter and numeric representation deliberately, and supplement it with field-count and syntax checks. Use a consistent decimal-point convention at both ends. A locale that writes decimal commas conflicts with a protocol that also uses commas to separate fields.

Run the Reader from the Front Panel

The original front panel shows the port selector, Response indicator and Data 1D output. Your version can keep those familiar controls while adding the status and validation indicators.

Front panel controls for continuous COM port reading, LabVIEW serial reader, NI-VISA, COM port data
Figure: Front panel controls for continuous COM port reading.

  1. Select the COM port belonging to the intended device.
  2. Set the serial parameters to the sender's configuration.
  3. Start the VI and enable reading if that control is present.
  4. Confirm that Response contains complete lines.
  5. Check the three parsed values against one known test record.
  6. Observe the valid-record counter and rejected-record counter.
  7. Use Stop to leave the loop and close the VISA session.

Received serial text and separated values on the LabVIEW front panel, LabVIEW serial reader, NI-VISA, COM port data
Figure: Received serial text and separated values on the LabVIEW front panel.

The screenshot uses COM5, but that is only the port assigned on the original computer. Select your own resource. If the device is unplugged and reconnected through another adapter or USB arrangement, its port assignment may change.

Decide what Start Reading actually means. If it prevents reading while the sender continues transmitting, the operating-system buffer can accumulate old data. An alternative is to keep receiving and validating while pausing only the visible updates. Label the control accordingly so a paused display is not confused with paused acquisition.

Calculate Whether the Serial Link Is Fast Enough

For an 8N1 UART frame, each byte uses ten transmitted bits. A 30-byte record at 9600 baud therefore occupies approximately 30 × 10 / 9600 = 0.03125 seconds. Ignoring other delays, that corresponds to an upper limit of about 32 such records per second.

If the sender attempts 100 records per second at that record length, the requested payload exceeds the link capacity. No LabVIEW loop setting can recover data that the sender cannot transmit at the required rate. Reduce the record size, lower the sampling output rate or choose a mutually supported higher baud rate.

Leave margin rather than designing exactly at the arithmetic limit. Additional status messages, longer negative values and extra decimal places can increase the record length. Measure the longest valid record you intend to support, including separators and line endings.

Timeouts, Errors and Clean Shutdown

A timeout may mean that no new record arrived during the chosen interval. It may also mean that bytes arrived without the expected terminator. Inspect the returned data and the exact error before deciding whether to continue. Do not clear every VISA error indiscriminately; a disconnected resource requires different handling from an expected idle interval.

Keep Stop responsive by using a finite read timeout. The loop normally cannot respond to the button until a blocking read finishes. If a half-second delay is too long for your application, design a shorter bounded read or a separate acquisition loop with an explicit stop mechanism.

After the loop, close the VISA session and report the acquisition error. Ensure the cleanup path still runs when acquisition fails, preserving the original error for display. Use the front-panel Stop behavior for normal operation rather than the toolbar Abort button, which can bypass your intended cleanup logic.

Troubleshooting Checklist

SymptomCheck first
COM port is missingDevice driver, cable and operating-system detection
Port cannot be openedAnother program may own it
Unreadable textBaud, frame settings and electrical interface
Regular read timeoutsSender activity and actual line-ending bytes
Occasionally shifted valuesPartial records or missing field-count validation
Display is increasingly delayedBacklog, excessive UI work or insufficient processing rate
Stop appears slowRead timeout and other blocking operations

Use known test records before trusting measurements. Try a normal line, a negative value, a line with one missing field and a line split across two transmissions. The first two should be accepted if allowed by your protocol; malformed data should be counted and explained rather than silently plotted as a real value.

Keep a Small Diagnostic Log

During development, save a bounded sample of raw complete records alongside their receive timestamps and validation result. When a value looks wrong, that record lets you distinguish a sender problem from a parser problem. If the raw text says 120 but the display says 12, investigate conversion and formatting. If the raw text already says 12, the receiver should not invent the missing zero.

Do not grow a front-panel string indefinitely as a substitute for logging. At ten records per second, even a modest demonstration produces 36,000 records in one hour. Rebuilding and displaying that expanding string on every iteration creates unnecessary work. Show the latest record or a limited recent history, and use a file or separate logging process when a longer record is required.

If the sender can be changed, adding a sequence number is helpful. A jump from record 104 to record 106 reveals a missing record, while two instances of 104 reveal duplication. Define wraparound and device-reset behavior before treating every decrease as corruption. A sequence number identifies ordering; it does not replace a checksum or establish when the sensor physically sampled the signal.

Download and Review the Original VI

Download Labview Simulation

This is the original project archive, retained for learning and comparison. It has not been rebuilt into a new downloadable VI as part of this written refresh. Review its blocks against the framing, validation and cleanup guidance above, and check compatibility with your installed LabVIEW version before using it as the basis of a new application.

The central idea is simple: receive complete records, validate their meaning and then update the display. Once that path works, continue with displaying serial data on a real-time graph in LabVIEW.

Frequently Asked Questions

Does one VISA Read always equal one measurement?

No. The relationship depends on the protocol and read configuration. Use explicit record boundaries and handle partial input rather than assuming every returned string is a complete measurement.

Should I disable termination characters to remove timeouts?

Only when the protocol requires another framing method. If the sender uses line endings, configure the correct one. Disabling termination without replacing the framing logic can hide the symptom while making records harder to separate.

Can I read more than three values?

Yes. Update the protocol, field-count check and array handling together. Keep channel order and units documented so the fourth field is not accidentally interpreted as an older channel.

Why does Data 1D stay unchanged after a bad line?

A sensible reader preserves the last valid value while displaying an invalid or stale status. It should not replace a valid measurement with an invented zero. Show the time of the last valid record so the retained value is not mistaken for fresh data.


Comments

29

Join the conversation

3 replies
1 reply
1 reply
Reply2.1
Replying to emadfadaee

hello sir.
thank you for this good explaination.
i have a question.
when i run the labview program it runs correctly,but when i wanna change some values from the coms,there is no response and give me error............so if i want to insert a new values,i must stop the run simulation and the program does not work online.
hope you help me

Reply4

Hi reader!
I have a question. In labview ,we get the datain form of string.In my application, I need to send an array of 6000 double data type numbers and receive this array in LabVIEW.can you modify the above code according to my needs.Thankyou

1 reply
1 reply
Reply6

Hi sir
i am a labview new user and i want to make this serial communication between arduino and labview but actually cant make such a code
can you upload the labview file please

1 reply
1 reply
Reply10

Sir,
Content is good.I am using the same procedure to analyse the output of the microcontroller PIC 16F628A by feeding the output signals Rx & Tx from microcontroller directly to the pins 2 & 3 of Max-232 and then into the read buffer, now its not showing any error but meanwhile i am not able to view the result (as indicated in the attachment).So,please suggest me accordingly.

1 reply
Reply11

Hi Mate,

I downloaded your VI and it's quite nice. However, i'm trying to read on 3 sets from the index, but the vi read only from index 0, I was wondering why there's noting on the other indexes 1 and 2.

I'm reading from COM3, also my code it good, and i'm trying to read a force of my hand ,then I want to do some extra calculation to read it in different measurement. I noticed that i may need to do extra steps to read my calculations.

any idea will be helpful.

Cheers,
Anthony

Reply13

HELLO,+I+got+the+output+sir.+Thank+you+for+your+tutorial,+i+need+to+add+the+date+and+time+to+the+output+which+is+continuously+running+can+u+help+me+out.

Reply14

Hey Nasir, There's some problem with the link for the VI as well as the one for the next tutorial.. It says service unavailable .. Could you please fix this ? Or maybe send me the VI via email ?

Reply15

Hey Nasir, Love the tutorial. Can you please fix the link to download the VI ? It takes me to the homepage and does nothing. Or if possible, can you email it to me ?

Reply16

Hey Nasir, Can you please fix the link to download the VI ? It takes me to the homepage and does nothing. Or if possible, can you email it to me ? my mail id rbajajece@gmail.com

Reply19

Hello! This is very useful, but can you upload images of the false portion of the loop as well as have all of the components be viewed as icons? I had a little trouble following the tutorial since I am new to LabVIEW and am not as familiar as to what should go in each spot intuitively.
Also could you update download link again? It seems to be broken.

Thank you so much!