Measurement Studio Analog Input: Acquiring and Logging Data in Visual Basic

Publish Date: Aug 14, 2012 | 22 Ratings | 3.32 out of 5 |  PDF

Overview

This application note explains how you can acquire and log data using your National Instruments data acquisition (DAQ) hardware and Microsoft Visual Basic. You can control DAQ devices with Visual Basic by using Measurement Studio ActiveX controls. Each Measurement Studio control adds a specific function to your program; you can use the control to set properties -- such as the device, scan rate, and channel strings for DAQ devices -- interactively through a set of property pages or programmatically in your Visual Basic code.

You can use this application note to create a simple data logger, a program that acquires analog signals with the Measurement Studio Analog Input (CWAI) control. The data will be displayed on a graph and logged to an ASCII file that can be viewed with any text editor. Data loggers are useful for monitoring low frequency signals, such as temperature. As you work with the data logger example, you will learn about scan rates, channel strings, named channels, and multiple channel objects and how to set these parameters programmatically. You also will learn how to visualize data in Visual Basic using the Measurement Studio Graph control and log data to a file using Visual Basic code.

Note: Measurement Studio includes tools to build measurement applications in ANSI C, Visual C++, and Visual Basic. The Measurement Studio Visual Basic tools were formerly known as ComponentWorks.

Note: You can also download the Measurement Studio Analog Input: Acquiring and Logging Data in Visual Basic example by using the link below.


Table of Contents

  1. Installing the Tools
  2. Opening a New Project and Loading ActiveX Controls
  3. Configuring Your Device
  4. Creating the User Interface
  5. Manipulating Controls Programmatically
  6. Adding Multiple Channels
  7. Adding Logging Functionality
  8. Conclusion

1. Installing the Tools


You need the following tools to develop the data logger:

  1. Launch Visual Basic from the Windows Start menu.
  2. Open a new Standard EXE project.
  3. Right click on the Visual Basic Toolbox and select Components.
  4. Select National Instruments CW DAQ and National Instruments CW UI. You will use the graph and numeric edit box from the UI group and the analog input control from the DAQ group.
  5. Click OK.

    Back to Top

    3. Configuring Your Device


Before you can communicate with a data acquisition device, you have to configure the device and specify channels and acquisition settings. You can specify the device and set up channels quickly and interactively through the Measurement Studio custom property pages.

1. Place a CWAI control on the form. Right-click on the control and select Properties to set your acquisition channel and parameters interactively, as shown in Figure 1.

Tip: You can customize any control through its custom property pages. Right click on the control and select Properties to open the custom property pages.

Figure 1. Selecting Devices and Channels Interactively

2. On the Channels page, select your data acquisition device from the drop-down list. To acquire data from that device, you have to add a new channel and configure the acquisition settings.

3. Click the New button. Notice that the new channel is added to the device hierarchy and that you can specify the channels you want to read and the parameters for the channels. The channel and all of its settings are referred to as a Channel object.

Every Channel object contains information about one or more channels, and you can specify that information in the property pages or set it programmatically. You can create multiple Channel objects for the same device. All of the Channel objects for a device are referred to as a Channels collection. Use the New or Del buttons to add or remove Channel objects from the Channels collection on this property page. Later in this example, you will learnhow to set these parameters programmatically, so you can add, remove, or modify Channel objects during run time.

4. Type 1 or the channel you want to read in Channels. A channel string is one or more channels on which to acquire data. If you are using hardware-specific channel strings, you can specify a range of channels, a reverse range of channels, or multiple non-consecutive channels with the following notations:
  • "0:2" acquires data from channels 0, 1, and 2.
  • "6:3" samples data from channel 6 down to channel 3.
  • "1,3,5" acquires data from channels 1, 3, and 5.
You also can specify named channels that you configure with National Instruments Measurement & Automation Explorer. Named channels are useful for customization. For example, if you are reading temperature data, you can customize scaling on the channel to read as degrees Celsius rather than volts.

Note: You cannot specify both named channels and hardware-specific channels in the same channel string or in the same Channels collection. All named channels in a Channels collection must refer to channels configured for the same device. Named channels can be specified in any order in the Channels collection, although some DAQ devices require you to specify channels in descending order, ending with channel 0.

5. On the Buffer page, change the Number of scans to acquire to 1000. Number of scans to acquire specifies the number of samples of a signal to acquire, which, along with the scan rate, determines the amount of time the entire acquisition takes. For a continuous acquisition, the number of scans specifies the number of acquired scans to return on each AcquiredData event.

6. On the Clocks page, change the Scans/second (scan rate) to 1000. One of the most important parameters of an analog input system is the rate at which the DAQ board samples an incoming signal, known as the scan rate. To determine an appropriate scan rate, you need to consider factors such as the maximum frequency of the input signal, the accuracy you require for your data, the noise that affects the signal, and the capabilities of your DAQ board. A fast sampling rate acquires more points in a given period of time and can form a better representation of the signal. A slow sampling rate might cause an alias or a poorly represented signal. You can find more information about aliasing and other DAQ fundamentals in the Data Acquisition (DAQ) Fundamentals application note.

7. On the Conditions page, make sure that the Stop condition is chosen and select Continuous from the drop-down list. The CWAI control enables you to perform acquisitions on multiple channels, either continuously or in one shot. One-shot acquisition stops after the specified number of scans are acquired. Because a data logger application is commonly used to acquire large amounts of data, choose continuous acquisition for this example.

8. Click OK to close the property pages.
See Also:
Data Acquisition Fundamentals

Back to Top

4. Creating the User Interface


Now that you have configured your DAQ device and defined your channel, build a user interface that will enable you to control the data acquisition. Figure 2 shows one way to design your display.


Figure 2. Developing the Data Logger Display


1.
Place a CommandButton on the control form. Change Name to cmdStart and Caption to Start.

2.
Place another CommandButton on the form. Change Name to cmdStop and Caption to Stop.

3.
Place a CWGraph control on the form. Right click on the graph and select Properties to customize the graph in the custom property pages. Set the following options on the Ticks page and click OK when you are finished:

a. Choose YAxis-1.
b. Type in Channel A for Axis caption.
c. Use the color palette to change the axis caption color to bright green to match the plot.

4.
Add Visual Basic Code to make the application respond to interactions from users and events generated by the program.

a. Users will press the Start button to configure their device with the properties set either in the property pages or programmatically and start the acquisition. Double click on the Start button and add the following code:

Private Sub cmdStart_Click()
 CWAI1.Configure
 CWAI1.Start
End Sub


Tip: If you are going to run the same acquisition multiple times, you can restart the acquisition without reconfiguring the device. You might want to develop a separate configure subprogram to avoid unnecessary configuration.

b. Users press the Stop button to stop the data acquisition. Double click on the Stop button and add the following code:

Private Sub cmdStop_Click()
 CWAI1.Stop
End Sub

c. When you are running a continuous acquisition, the AcquiredData event fires each time the specified number of scans is acquired. If you select a non-continuous acquisition, then the event will fire once after the acquisition is complete. Double click on the CWAI control and add the following code to display data on the graph when the event fires:

Private Sub CWAI1_AcquiredData(ScaledData As Variant, BinaryCodes As Variant)
 CWGraph1.ChartY ScaledData
End Sub

5.
Save the project and form as Data Logger.

6.
Connect a signal to the input channel that you selected. You can generate analog output data through Measurement & Automation Explorer if you do not have an external signal source such as a function generator.

7.
Select Run»Start to run your program.

8.
Press the Start button to configure your device and begin acquiring data. Notice that a plot with the value of the channel you selected appears on the graph and is continually updated. Press the Stop button to stop the acquisition.

Back to Top

5. Manipulating Controls Programmatically


The custom property pages enable you to quickly select a device and easily set parameters to acquire data from channels on that device, but you cannot access the property pages during run time. However, if you set the parameters programmatically, you can alter them from the user interface while the example is running. Figure 3 shows the Data Logger with the device and channel parameters on the user interface.


Figure 3. Setting Devices and Channels from the User Interface

1.
Place a CWNumEdit on the form. Change Name to numDevice and Value to 1. Add a label next to the control and change Caption to Device.

2.
Place a second CWNumEdit on the form. Change Name to numScans and Value to 1000. Add a label next to the control and change Caption to # of Scans.

3.
Place a third CWNumEdit on the form. Right click on the control and select Properties. On the Numeric page, check the Do range checking box and set the Minimum and Maximum to 0 and 2000 respectively. Enabling range checking prevents users from setting a rate that is too high for the data logger. Change Name to numScanRate and Value to 1000. Add a label next to the control and change Caption to Scan Rate.

4.
Place a TextBox on the form. Change Name to txtChannelA and Text to 1 or the channel you are using. Add a label above the control and change Caption to Channel A.

5.
Place another TextBox on the form. Change Name to txtUpperLimitA and delete the default text. Add a label next to the control and change Caption to Upper Limit.

6.
Place a third TextBox on the form. Change Name to txtLowerLimitA and delete the default text. Add a label next to the control and change Caption to Lower Limit.

7.
To configure the device using the parameters set in the user interface during run time and start the data acquisition, add the bolded code to the existing cmdStart_Click event procedure:

Private Sub cmdStart_Click()
Dim Chan As CWAIChannel
CWAI1.Device = numDevice
'Remove channels already configured in property pages CWAI1.Channels.RemoveAll
'Add a Channel object to the collection
Set Chan = CWAI1.Channels.Add(txtChannelA.Text)
'Set upper and lower limits, if specified
If (txtUpperLimitA.Text <> "") Then
  Chan.UpperLimit = txtUpperLimitA.Text
End If
If (txtLowerLimitA.Text <> "") Then
  Chan.LowerLimit = txtLowerLimitA.Text
End If
'Set number of scans to acquire before firing
'AcquiredData event
CWAI1.NScans = numScans.Value
'Set scan rate
CWAI1.ScanClock.Frequency = numScanRate.Value
'Set to continuous acquisition
CWAI1.StopCondition.Type = cwaiContinuous
CWAI1.Configure
CWAI1.Start
End Sub

8.
Save the project and form.

9.
Select Run»Start to run your program. Input the values for the channel, lower and upper limits (default values for the upper and lower limits for most MIO boards are -10 and +10 V for bipolar devices and 0 to 10 V for unipolar devices), device number, number of scans, and scan rate and press the Start button. The plot with a value of the channel appears again.

Note: Setting appropriate input limits allows the CWAI control to apply a gain setting on the DAQ device so you get the most accurate measurement. Adjust your limits if your input values are less than the default values. You can change the values of the lower and upper limits, but if you leave the values blank, the CWAI control configures with the default values. Use Measurement & Automation Explorer to find the default limits for your board.

Back to Top

6. Adding Multiple Channels



If you want to acquire data from more than one channel, you can create a new Channel object. The benefit of adding this extra Channel object is that you can set different parameters for different channels. You can add an additional Channel object in the following way:

1.
Add another channel (Channel B) to your program by adding the appropriate code and controls on the user interface, similar to what you did for Channel A. See Figure 4 for an example interface for Channel B.

2.
Add another plot to display Channel B. Right click on the graph and select Properties.

3.
On the Axes page, click Add to add an axis (YAxis-2) and select Auto scale.

4.
On the Plots page, click Add to add a Plot (Plot-2). Choose magenta from the color palette next to the Line style choices so that this plot will be a different color than the first one. Choose YAxis-2 from the Y-axis list so the plot will have its own y-axis.

5.
On the Ticks page, choose YAxis-2. Type Channel B for Axis caption. Choose magenta for the axis caption color to match the new plot. Choose Right for Labels (unselect Left). Choose Right for Tick marks (unselect Left).
6.
Click OK to close the property pages.

7.
Save the project and form.

8.
Select Run»Start to run your program. Enter the parameters in the user interface and press the Start button to begin acquiring data. Two plots appear with the values of the signals from the two selected channels.

Back to Top

7. Adding Logging Functionality



Now that you are acquiring data, you can add an actual file input/output (I/O) feature to complete the data logger. Figure 4 shows the final data logger during run time.

Note: Although file I/O is not a feature of Measurement Studio, this section shows you how to log data to a file using Visual Basic.


Figure 4. Running the Data Logger


1.
Add the controls as shown in Figure 4.

a.
Place a TextBox on the form. Change the Name property to txtFilename and Text to log.txt. Add a Visual Basic label to identify this control as the log file name. Data will be logged to that file in the same directory as the project.

b.
Place a CWButton on the form to allow users to append or overwrite the file, depending on the position of the button. The button looks like a toggle switch by default, but the CWButton offers many styles such as LEDs, switches, or pushbuttons. Right click on the CWButton and select Properties. Change the button style to Horizontal 3D Slide. Click OK. Change Name to Overwrite. Add Visual Basic labels to both sides of the button. Change Caption of the left label to Append and the right label to Overwrite.

c.
Place a CommandButton on the form. Change Name to cmdViewFile and Caption to View Log File.

2.
When users click on the View Log File button, Notepad will open and display the acquired data. Double click on the View Log File button and add the following code:

Private Sub cmdViewFile_Click()
Shell "notepad.exe" & " " & txtFilename.Text, vbNormalFocus
End Sub

3.
To log the data to a file, create a stand-alone subroutine, LogData, that other event procedures can call:

Tip: You can optimize the data logging routine to use a binary format that requires less storage space and processor time. Binary formats are ideal for the large amounts of data acquired from higher frequency signals.

Sub LogData(ScaledData As Variant)
'Log the data to a file
Dim FileNumber As Integer
Dim iChannel As Integer
Dim Chan As CWAIChannel
Dim iScans As Integer
Dim sData As String

'Open the file
FileNumber = FreeFile
If Overwrite Then

   Open txtFilename.Text For Output As #FileNumber
Else
  Open txtFilename.Text For Append As #FileNumber
End If

'Print the title of each column
For Each Chan In CWAI1.Channels
  Print #FileNumber, vbTab & "Ch " & _
  RTrim(Chan.ChannelString);
Next Print #FileNumber, 'carriage return/line feed

'The data is in a two dimensional array because
'this example performs a multichannel
'acquisition. Therefore, you need two loops to
'log the data to the file. The outer loop goes
'through the set number of scans, and the inner
'loop writes the data for each of the two
'channels to a file.

For iScans = LBound(ScaledData, 2) To _
UBound(ScaledData, 2)
  For iChannel = LBound(ScaledData) To _
   UBound(ScaledData)
     sData = Format(ScaledData(iChannel, _

       iScans), ".###0")
     'the semi-colon after a Print command means
     'that a CR is not placed at the end of

      'the line
     Print #FileNumber, vbTab & sData;
  Next iChannel
Print #FileNumber,
Next iScans

'Close the file
Close #FileNumber
End Sub

4.
To call the LogData subprogram, add the bolded line to the existing AcquiredData event procedure:
Private Sub CWAI1_AcquiredData(ScaledData As _
Variant, BinaryCodes As Variant)
CWGraph1.ChartY ScaledData
LogData ScaledData
End Sub

5.
Save the project and form.

6.
Run your program. Enter the necessary values, type log.txt for the log file name, and select Append. To begin the data acquisition, press the Start button. Two plots appear with the values of the signal on Channel A and Channel B. When you are done acquiring data, press the Stop button (you cannot view the file until you have pressed the Stop button). To see the log file, press the View Log File button. Notepad opens and displays the acquired data in two columns.

Back to Top

8. Conclusion



The DAQ concepts presented in this application note -- scan rates, channel strings, named channels, and multiple channel objects -- create a foundation on which you can build custom DAQ programs using Measurement Studio. As ActiveX controls, Measurement Studio offers you more versatility than any laboratory instrument:

  • Develop your programs in any ActiveX container, including Visual Basic, Visual C++, Borland Delphi, or Microsoft Excel.
  • Use the Measurement Studio property pages to quickly configure the controls to look and behave as you need them to. For example, you quickly added another Channel object to the Data Logger and a new plot to the graph.
  • Continue using your own software to analyze the data and generate reports. For example, you can import the data into Microsoft Excel or National Instruments HiQ and analyze it there. You also can display your data on the Internet using National Instruments DataSocket. See Application Note 127, Building an Interactive Web Page with DataSocket, for information about setting up a live display of data.

With the power of Measurement Studio and your computer, you can create versatile programs that you can easily and fully integrate into your project.

See Also:
Building an Interactive Web Page with DataSocket


Back to Top

Bookmark & Share


Ratings

Rate this document

Answered Your Question?
Yes No

Submit