Academic Company Events NI Developer Zone Support Solutions Products & Services Contact NI MyNI

Document Type: Tutorial
NI Supported: Yes
Publish Date: May 17, 2007


Feedback


Yes No

Related Categories

Related Links - Developer Zone

Related Links - Products and Services

Measurement Studio Analog Output -- Waveform Generation in Visual Basic

19 ratings | 3.32 out of 5
Print

Overview

This application note explains how you can generate waveforms using your National Instruments data acquisition (DAQ) hardware and Microsoft Visual Basic. You can control DAQ devices with Visual Basic programs using Measurement Studio ActiveX controls. Each Measurement Studio control adds a specific functionality to your program and you can set properties -- such as device, channel, and frequency -- interactively through a set of property pages or programmatically in your Visual Basic code.

You can use this application note to create a waveform generator, a program that generates data and writes the waveforms to a specified analog output channel. Using Measurement Studio, you can create a buffer of data points in memory, load the buffer with the data, and send the data to an analog output channel. The example in this application note explains how to build a waveform generator that outputs sine, square, or triangle waveforms and introduces the features of the Measurement Studio Analog Output (CWAO) ActiveX control, including buffered Analog Output (AO) and Progress events.

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 Output: Generating Waveforms in Visual Basic example program.

Installing the Tools


You need the following tools to develop the waveform generator:
  • Visual Basic -- Although this example uses Visual Basic 5 terminology, you can implement the example in Visual Basic 4 or later.
  • Measurement Studio -- Measurement Studio contains ActiveX controls for developing a user interface (such as knobs, slides, and graphs), acquiring data, communicating with instruments, and analyzing data. If you have not purchased a licensed version of Measurement Studio, visit ni.com/mstudio and follow the links to download evaluation software.
  • National Instruments DAQ hardware and NI-DAQ driver software -- To order National Instruments products online, visit ni.com/store
    See Also:
    Measurement Studio Home Page
    National Instruments Online Store

    Opening a New Project and Loading ActiveX Controls


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 the numeric edit box from the UI group and the analog output control from the DAQ group.

5. Click OK.

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 custom property pages.


1.
Place a CWAO control on the form. Right click on the control and select Properties to interactively set your analog output parameters in the custom property pages, as shown in Figure 1.

Figure 1. Selecting Devices and Channels Interactively

2.
On the Channels page, select your data acquisition device from the drop-down list. Click the New button to add the channel object. Specify the channel string for the waveform generation and configure the acquisition settings.

3.
Select the Buffer page.

a.
A data buffer can be output once, several times, or continuously until generation is stopped using the Reset method. To continuously generate waveform data, check Infinite.

b.
The Buffer Settings section allows you to specify the size of the buffer. Set Number of updates to 10000.

c.
Select Progress event. A Progress event can be used to monitor the state of waveform generation. You can control how often the Progress event is fired with the Progress interval option. By default, the Progress interval is one-half of the buffer size. For a buffer of 10000 points, the event is fired after 5000 points have been updated. You can customize the Progress interval to be any value that evenly divides into Number of updates. You might want to set a custom interval if you need the event to fire more often than every half buffer. For instance, if you have a large buffer that takes 10 seconds to output, then the event fires every five seconds. You can set a smaller interval to see more frequent updates.

4.
On the Clocks page, change Updates/second to 10000 to specify the frequency of the update clock of your DAQ device. The update clock controls the rate at which points in the waveform are output on the analog output channels. Because each channel has its own digital-to-analog converter (DAC), there is no delay between updates from different channels, and all channels are updated simultaneously.

The update rate is the frequency at which your data is updated on individual channels. For example, if you add channel 1 and channel 0 and set the update clock to a frequency of 1000 updates per second, the DAQ device updates each DAC every millisecond. This frequency is not the same as the waveform frequency of the output. The actual frequency of the output waveform, the points per cycle, and the update rate are interdependent. In this example, the update rate is a constant 10000 updates/second. The maximum frequency of the waveform is 1000 Hz, giving a minimum of 10 points per cycle. Less than 10 points per cycle will produce an inaccurate waveform.

5.
Click OK to set the parameters and close the property pages.

Creating the User Interface



Now that you have configured your DAQ device and set up the channels, you can build a user interface for controlling data generation. Figure 2 shows the user interface of the waveform generator example, which will generate a sine wave with the frequency specified in the numeric edit control and chart the data on the graph.

Figure 2. Developing the Waveform Generator User Interface

1.
Place a CWGraph control on the form and customize it to behave as a strip chart. Right click on the graph and select Properties.

a.
On the Axes page, uncheck the Auto scale box and change the Minimum and Maximum for the XAxis to 0 and 250, respectively. The graph now displays 250 points at a time.

b.
On the Ticks page, change the Tick spacing to Number of divisions and select 2 for Major and 0 for Minor. The XAxis now displays two major divisions, as shown in Figure 2.

c.
On the Graph page, change Chart history to Fixed at 10000. The chart history specifies the number of points the graph stores before deleting old data. For this example, the chart history will store a full buffer of data before overwriting existing data. Press OK to close the property pages.

2.
Place a CWNumEdit control on the form. Change Name to numFreqVal and Value to 500. Place a Label next to the CWNumEdit control and change Caption to Frequency. Right click on the CWNumEdit control and select Properties.

a.
On the Numeric page, check the Do range checking box and set the Minimum and Maximum to 0 and 1000, respectively. Range checking enforces a minimum and maximum on the values in the numeric edit box.

b.
On the Format page, type .#" Hz" in the Format string box to format and label the value in the numeric edit control. The .# means the numeric edit displays one digit of precision to the right of the decimal, and the " Hz" appends the unit after the value.

c.
Press OK to apply the changes and close the property pages.

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

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

5.
Place a Label on the form. Change Name to Update and delete the default Caption value. This indicator displays the number of updates that have been output to the data acquisition board since the start of the waveform generation. Place another Label next to the control and change Caption to Update Count:.

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

a.
At the top of the code window, you can declare global variables and constants. These variables and constants are accessible from any part of the program. Place the following code in the General Declarations section at the top of the code window:

Option Explicit
'BufferSize is the size of the buffer
Const BufferSize = 10000
Const TwoPi = 6.2832
Dim WholeBuffer

b.
Create a new function that generates the number of updates you specified in the CWAO property pages:

Private Function GeneratePoints(Updates _
As Integer)
  Dim i, PointsPerCycle
  Dim Pattern() As Double
  ReDim Pattern(Updates)
  PointsPerCycle = BufferSize / numFreqVal.Value
  For i = 1 To Updates
     'compute sine wave
     Pattern(i) = Sin(TwoPi * i / PointsPerCycle)
  Next i
  GeneratePoints = Pattern
End Function

c.
When you run the Waveform Generator and press the Start button, data is generated. Before waveform generation can begin, the device needs to be configured, and the AO buffer must already be filled with data so that it is not empty at any point. Double click on the Start button and add the following code:

Private Sub cmdStart_Click()
  WholeBuffer = GeneratePoints(BufferSize)
  CWAO1.Configure
  CWAO1.Write WholeBuffer
  CWAO1.Start
  CWGraph1.ChartY
  WholeBuffer
End Sub

d.
The Progress event fires after 5000 updates on the DAC because the Progress interval defaults to half of the buffer size, which you declared as 10000. When the Progress event fires, the number of updates appears on the user interface. Double click on the CWAO control and add the following code:

Private Sub CWAO1_Progress(UpdateCount _
As Variant)
  Update.Caption = UpdateCount
End Sub

e.
When you press the Stop button, the data generation stops, and the device resets. Double click on the Stop button and add the following code:

Private Sub cmdStop_Click()
  CWAO1.Reset
End Sub

7.
Save the project and form as Waveform Generator.

8.
Select Run»Start to run and test your program.

9.
To begin writing data to the channel, press the Start button. Notice that a sine wave appears on the graph. Watch the update count change. To change the frequency of the wave, press the Stop button, reset the frequency, and restart the generation. You can use an oscilloscope to verify the waveform generation. Alternatively, you can connect the output channel to an input channel and use National Instruments Measurement & Automation Explorer to monitor the input channel. Press the Stop button when you want to stop the data generation and reset the device.

Tip: If you choose to monitor your output, set the scan rate on the analog input to a minimum of double the rate of the analog output to avoid aliasing.

Manipulating Controls Programmatically



With the custom property pages, you can quickly select a device and set parameters to output data to that device, but the property pages are not available during run time. However, you can set the parameters programmatically and alter them from the user interface while the example is running. In this section, you will add controls to the user interface so that you can set the device and channel during run time.

Figure 3. Setting the Devices and Channels from the User Interface

1.
Place the controls on the form as shown in Figure 3 to select the device and channel from the user interface at run time.

Note: The properties set in the property pages are overwritten by those set programmatically.

a.
Place a CWNumEdit control on the form. Change Name to numDevice and Value to 1 or to the device you are using. Place a Label next to the control and change Caption to Device.

b.
Place a CWNumEdit control on the form. Change Name to numChannel and Value to 0 or to the channel you are writing to. Place a Label next to the control and change Caption to Channel.

2.
Modify existing subroutines to use the information specified on the user interface, rather than in the property pages. Add the bolded code to the existing cmdStart_Click event procedure:

Private Sub cmdStart_Click()
WholeBuffer = GeneratePoints(BufferSize)

CWAO1.Device = numDevice
'Remove existing channels
CWAO1.Channels.RemoveAll
'Add channel specified on UI
CWAO1.Channels.Add numChannel


CWAO1.UpdateClock.Frequency = BufferSize
'Set a continuous acquisition
CWAO1.Infinite = True
'Specify the number of points in
'the waveform
CWAO1.NUpdates = BufferSize
'Configure the Progress event to fire
'every half buffer
CWAO1.ProgressEnabled = True
CWAO1.AutoSelectProgressInterval = False
'Progress interval is half of the
'full buffer size
CWAO1.ProgressInterval = BufferSize / 2


CWAO1.Configure

CWAO1.Write WholeBuffer CWAO1.Start

CWGraph1.ChartY WholeBuffer
End Sub

3.
Save the project and form.

4.
Select Run»Start to run your program.

5.
Enter the values for the device, channel, and frequency and press the Start button. The plot of the output appears on the graph, and the Update Count indicator displays the number of updates. Press the Stop button to stop generating data.

Changing Waveform Frequency During Generation



Currently, you can set the frequency of the waveform during run time. Now, you will add code so that you can change the frequency on the fly. When a Progress event is fired, it indicates that the number of updates equal to the Progress interval has been written out from the buffer. At this point, you can write new data to the buffer to replace the data that has been written out. For this part of the example, you will generate new data when the frequency is changed. This new data will then be written to the buffer on each Progress event.

1.
Add a global variable, HalfBuffer, to the declaration section. Declare it as you declared WholeBuffer.
2.
Modify the existing subroutine so that a half buffer will be created when the Start button is pressed. Add the bolded line to the existing procedure:
Private Sub cmdStart_Click()
WholeBuffer = GeneratePoints(BufferSize)

HalfBuffer = GeneratePoints(BufferSize / 2)

CWAO1.Device = numDevice
'Remove existing channels
CWAO1.Channels.RemoveAll
'Add channel specified on UI
CWAO1.Channels.Add numChannel


CWAO1.UpdateClock.Frequency = BufferSize
'Set a continuous acquisition
CWAO1.Infinite = True
'Specify the number of points in the waveform
CWAO1.NUpdates = BufferSize


'Configure the Progress event to fire
'every half buffer
CWAO1.ProgressEnabled = True
CWAO1.AutoSelectProgressInterval = False
'Progress interval is half of the full
'buffer size
CWAO1.ProgressInterval = BufferSize / 2


CWAO1.Configure

CWAO1.Write WholeBuffer CWAO1.Start

CWGraph1.ChartY WholeBuffer
End Sub

3.
To change the frequency on-the-fly, double click on the frequency control and add the following code:

Private Sub numFreqVal_ValueChanged(Value As _
Variant, PreviousValue As Variant, ByVal _
OutOfRange As Boolean)
HalfBuffer = GeneratePoints(BufferSize / 2)
End Sub

4.Add the bolded lines to the existing CWAO1_Progress subroutine so that it updates half of the buffer with the last chosen frequency and charts the points when the event is fired:
Private Sub CWAO1_Progress(UpdateCount As Variant)
Update.Caption = UpdateCount
'Write next half buffer of data
CWAO1.Write HalfBuffer
CWGraph1.ChartY HalfBuffer
End Sub

Note: Notice that each time the frequency changes, half of a buffer is generated. Before you can begin the acquisition, you need to create a full buffer and half buffer of data. If you change the frequency of the waveform before pressing the Start button, you will create HalfBuffer twice.

5.
Save your project.

6.
Select Run»Start to run and test your program.

7.
Press the Start button to begin the data generation. Notice that Update Count changes, as it did before. Change the frequency. Notice that the waveform changes soon after.

Generating Square and Triangle Waves



You can expand this example by generating different waveforms. Figure 4 shows the modified Waveform Generator during run time. The slide functions as a waveform selector with settings to generate sine, square, or triangle waves.

Figure 4. Running the Waveform Generator

1.
Place a CWSlide on the form. Change Name to WaveformType. Right click on the slide and select Properties.

a.
On the Style page, choose Vertical Slide and click the Value pairs only option. A value pair associates a symbolic name with a value and marks a specific point on an axis, which you can specify in the Value Pairs property page.

b.
On the Value Pairs page, delete the last entry (Index 4). Choose Index 1 and change Name to Triangle and Value to 2. For Index 2, change Name to Square and Value to 1. For Index 3, change Name to Sine and leave Value at 0. Each of the values will be used in the program to identify their respective functions in a case statement.

c.
On the Pointer page, choose None for the Fill style. Press OK.

2.
Double click on the slide and add the following code so that when the slide position changes, data is generated for the selected waveform type:

Private Sub WaveformType_PointerValueChanged _
(ByVal Pointer As Long, Value As Variant)
HalfBuffer = GeneratePoints(BufferSize / 2)
End Sub

3.
To implement the new waveform types, add the bolded code to the existing GeneratePoints function:
Private Function GeneratePoints(Updates _
As Integer)
Dim i, PointsPerCycle
Dim j, Mid
Dim Pattern() As Double
ReDim Pattern(Updates)
PointsPerCycle = BufferSize / numFreqVal.Value
Mid = PointsPerCycle / 2
For i = 1 To Updates
    j = i Mod PointsPerCycle
   Select Case WaveformType.Value
       Case 0

            'Compute sine wave
            Pattern(i) = Sin(TwoPi * i _
             / PointsPerCycle)
       
Case 1
           'Compute square wave; the \
          'represents integer division
          Pattern(i) = 1 - 2 * (j \ Mid)
        Case 2        
          'Compute triangle wave
          Pattern(i) = 1 - 2 * (1 - _
            Abs((Mid – j) / Mid))
    End Select
Next i
GeneratePoints = Pattern
End Function

4.
Save the project and form.

5.
Select Run»Start to run your program.

6.
Enter values for the device, channel, and frequency and press the Start button to begin. The plot of the output appears on the graph, and the number of updates appears. Change the slide to output a different waveform. You can see the different waveform appear on the graph. Press the Stop button to stop generating data and reset the device.

Conclusion



The routines outlined in this application note demonstrate the basics of analog output using the CWAO control. You can customize the routines and update the techniques in this example to create a more efficient program that meets your specific needs.

Buffered AO provides a flexible way to continuously generate waveform data and change the data without interrupting the data stream. You can customize your waveform generator in the following ways:
  • Adjust timing parameters -- The ability to manipulate and coordinate various timing parameters is important for any DAQ system. Use the Measurement Studio property pages to quickly configure the controls to behave the way you want. For example, you could use an external timing source rather than the internal clock for your waveform generator. You might want to use an onboard counter to synchronize updates with other timing signals.
  • Use Measurement Studio Digital Signal Processing (DSP) -- The DSP control provides robust and flexible methods for creating complex waveforms. DSP is available in the Measurement Studio Full Development system; built-in functions exist for sine, triangle, square, arbitrary, and sawtooth waveforms, chirps, and Gaussian and white noise. You can use DSP for more complex waveforms in this example. The Waveform Generator presented in this application note does not use the DSP control because it is not available in the Measurement Studio Base package.
  • Broadcast live data -- You can use DataSocket to distribute the generated data from this example over the Internet. With DataSocket, you can distribute interactive data, where users connected to the application receive real data points rather than pictures of the data. See Building an Interactive Web Page with DataSocket for information about setting up a live display of data.
    See Also:
    Building an Interactive Web Page with DataSocket
19 ratings | 3.32 out of 5
Print

Reader Comments | Submit a comment »

Amplitude Setting
This document does not address at all how to set the amplitude of the waveform
- Hoi Young, Motorola. hoi.young@motorola.com - Nov 9, 2004

 

Legal
This tutorial (this "tutorial") was developed by National Instruments ("NI"). Although technical support of this tutorial may be made available by National Instruments, the content in this tutorial may not be completely tested and verified, and NI does not guarantee its quality in any way or that NI will continue to support this content with each new revision of related products and drivers. THIS TUTORIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND AND SUBJECT TO CERTAIN RESTRICTIONS AS MORE SPECIFICALLY SET FORTH IN NI.COM'S TERMS OF USE (http://ni.com/legal/termsofuse/unitedstates/us/).