Daq Ug
Daq Ug
Daq Ug
User's Guide
R2022b
How to Contact MathWorks
Phone: 508-647-7000
v
Hardware and Driver Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
vi Contents
Analog Input and Output
6
Acquire Data in the Foreground . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
vii
Acquire a Single Count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
Acquire a Single Frequency Count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Acquire Counter Input Data in the Foreground . . . . . . . . . . . . . . . . . . . . . 8-4
Digital Operations
9
Digital Channels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Digital Clocked Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Access Digital Subsystem Information . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Acquire Digital Data Using an External Clock via Chassis PFI Terminal
......................................................... 9-11
Generate Digital Output Using Decimal Data Across Multiple Lines . . . 9-14
Multichannel Audio
10
Audio Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Multichannel Audio Scan Rate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Audio Measurement Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Acquire Audio Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
viii Contents
Waveform Function Generation
11
Digilent Analog Discovery Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Synchronization
13
Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2
Shared Triggers and Shared Scan Clocks . . . . . . . . . . . . . . . . . . . . . . . . 13-2
Source and Destination Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-3
Automatic Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Synchronization Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
ix
PCI DSA Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-14
Synchronize DSA PCI Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-14
Handle Filter Delays with DSA Devices . . . . . . . . . . . . . . . . . . . . . . . . . 13-15
Functions
15
Apps
16
Blocks
17
x Contents
Cannot Use PXI 4461 and 4462 Together . . . . . . . . . . . . . . . . . . . . . . . . . A-6
Cannot Get Correct Scan Rate with Digilent Devices . . . . . . . . . . . . . . . . A-7
Cannot Simultaneously Acquire and Generate with myDAQ Devices . . . . . A-7
Simultaneous Analog Input and Output Not Synchronized Correctly . . . . . A-7
Counter Single Scan Returns NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7
External Clock Will Not Trigger Scan . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7
Why Does My S/PDIF Device Time Out? . . . . . . . . . . . . . . . . . . . . . . . . . . A-7
MOTU Device Not Working Correctly . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7
xi
Data Acquisition Toolbox Examples
18
Getting Started with NI Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-3
Acquiring and Generating Data at the Same Time with Digilent Analog
Discovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-73
xii Contents
Acquire Continuous Audio Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-83
Communicate with I2C Devices and Analyze Bus Signals Using Digital IO
....................................................... 18-118
xiii
Write Timetable Data to TDMS-file . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-184
xiv Contents
1
Data Acquisition Toolbox provides apps and functions for configuring data acquisition hardware,
reading data into MATLAB® and Simulink®, and writing data to DAQ analog and digital output
channels. The toolbox supports a variety of DAQ hardware, including USB, PCI, PCI Express®, PXI®,
and PXI-Express devices, from National Instruments™ and other vendors.
The toolbox apps let you interactively set up a data acquisition interface and configure it to your
hardware. You can then generate equivalent MATLAB code to automate your data acquisition.
Toolbox functions give you the flexibility to control the analog input, analog output, counter/timer,
and digital I/O subsystems of a DAQ device. You can access device-specific features and synchronize
data acquired from multiple devices.
You can analyze data as you acquire it or save it for post-processing. You can also automate tests and
make iterative updates to your test setup based on analysis results.
1-2
Product Capabilities
Product Capabilities
In this section...
“Understanding Data Acquisition Toolbox” on page 1-3
“Supported Hardware” on page 1-3
Data Acquisition Toolbox is a collection of functions, blocks, apps, and a MEX-file (shared library)
built on the MATLAB technical computing environment. The toolbox and its support packages also
provide several dynamic link libraries (DLLs) called adaptors, which enable you to interface with
specific hardware. The toolbox provides you with these main features:
• A framework for bringing live, measured data into the MATLAB workspace using PC-compatible,
plug-in data acquisition hardware
• Support for analog input (AI), analog output (AO), and digital I/O (DIO) subsystems, including
simultaneous analog I/O conversions
• Support for these popular hardware vendors/devices:
Supported Hardware
The list of hardware supported by Data Acquisition Toolbox can change in each release.
To see the full list of hardware that the toolbox supports, visit the supported hardware page at
https://www.mathworks.com/hardware-support/data-acquistion-software.html.
1-3
1 Introduction to Data Acquisition
System Setup
The first step in any data acquisition experiment is to install the hardware and software. Hardware
installation consists of plugging a board into your computer or installing modules into an external
chassis. Software installation consists of loading hardware drivers and application software onto your
computer. After the hardware and software are installed, you can attach your sensors.
Calibration
After the hardware and software are installed and the sensors are connected, the data acquisition
hardware should be calibrated. Calibration consists of providing a known input to the system and
recording the output. For many data acquisition devices, calibration can be easily accomplished with
software provided by the vendor.
Trials
After the hardware is set up and calibrated, you can begin to acquire data. You might think that if you
completely understand the characteristics of the signal you are measuring, then you should be able to
configure your data acquisition system and acquire the data.
However, your sensor might be picking up unacceptable noise levels and require shielding, or you
might need to run the device at a higher rate, or perhaps you need to add an antialias filter to remove
unwanted frequency components.
These effects act as obstacles between you and a precise, accurate measurement. To overcome these
obstacles, you need to experiment with different hardware and software configurations. In other
words, you need to perform multiple data acquisition trials.
1-4
Data Acquisition System
Overview
Data Acquisition Toolbox, with the MATLAB technical computing environment, gives you the ability to
generate, measure. and analyze physical phenomena. The purpose of any data acquisition system is
to provide you with the tools and resources to do this.
You can think of a data acquisition system as a collection of software and hardware that connects
your program to the physical world. A typical data acquisition system consists of these components:
Components Description
Data acquisition At the heart of any data acquisition system lies the data acquisition
hardware hardware. The main function of this hardware is to convert analog signals
to digital signals, and to convert digital signals to analog signals.
Sensors and actuators Sensors and actuators are types of transducers. A transducer is a device
(transducers) that converts input energy of one form into output energy of another
form. For example, a microphone is a sensor that converts sound energy
(in the form of pressure) into electrical energy, while a loudspeaker is an
actuator that converts electrical energy into sound energy.
Signal conditioning Sensor signals are often incompatible with data acquisition hardware. To
hardware overcome this incompatibility, the signal must be conditioned. For
example, you might need to condition an input signal by amplifying it or
by removing unwanted frequency components. Output signals might need
conditioning as well.
Computer The computer provides a processor, a system clock, a bus to transfer data,
and memory and disk space to store data.
Software Data acquisition software allows you to exchange information between the
computer and the hardware. For example, typical software allows you to
configure the sampling rate of your board, and acquire a predefined
amount of data.
The following diagram illustrates the data acquisition components, and their relationships to each
other.
1-5
1 Introduction to Data Acquisition
The figure depicts the two important features of a data acquisition system:
• Signals are input to a sensor, conditioned, converted into bits that a computer can read, and
analyzed to extract meaningful information.
For example, sound level data is acquired from a microphone, amplified, digitized by a sound card,
and stored in the MATLAB workspace for subsequent analysis of frequency content.
• Data from a computer is converted into an analog signal and output to an actuator.
For example, a vector of data in the MATLAB workspace is converted to an analog signal by a
sound card and output to a loudspeaker.
At the simplest level, data acquisition hardware is characterized by the subsystems that comprise it.
A subsystem is a component of your data acquisition hardware that performs a specialized task.
Common subsystems include
• Analog input
• Analog output
• Digital input/output
• Counter/timer
Hardware devices that consist of multiple subsystems, such as the one depicted below, are called
multifunction boards.
1-6
Data Acquisition System
Analog input subsystems convert real-world analog input signals from a sensor into bits that can be
read by your computer. Perhaps the most common of all subsystems, they are typically available in
multichannel devices offering 12 or 16 bits of resolution.
Analog input subsystems are also referred to as AI subsystems, A/D converters, or ADCs.
Analog output subsystems convert digital data stored on your computer to a real-world analog signal.
These subsystems perform the inverse conversion of analog input subsystems. Typical acquisition
boards offer two output channels with 12 bits of resolution, with special hardware available to
support multiple channel analog output operations.
Analog output subsystems are also referred to as AO subsystems, D/A converters, or DACs.
Digital input/output (DIO) subsystems are designed to input and output digital values (logic levels) to
and from hardware. These values are typically handled either as single bits or lines, or as a port,
which typically consists of eight lines.
While most popular data acquisition cards include some digital I/O capability, it is usually limited to
simple operations. Special dedicated hardware is often necessary for performing advanced digital I/O
operations.
Counter/Timer Subsystems
Counter/timer (C/T) subsystems are used for event counting, frequency and period measurement, and
pulse train generation.
Sensors
A sensor converts the physical phenomena of interest into signals that are input to your data
acquisition hardware. There are two main types of sensors based on the output they produce: digital
sensors and analog sensors.
Digital sensors produce an output signal that is a digital representation of the input signal, and has
discrete values of magnitude measured at discrete times. A digital sensor must output logic levels
that are compatible with the digital receiver. Some standard logic levels include transistor-transistor
logic (TTL) and emitter-coupled logic (ECL). Examples of digital sensors include switches and position
encoders.
1-7
1 Introduction to Data Acquisition
Analog sensors produce an output signal that is directly proportional to the input signal, and is
continuous in both magnitude and time. Most physical variables such as temperature, pressure, and
acceleration are continuous in nature and are readily measured with an analog sensor. For example,
the temperature of an automobile cooling system and the acceleration produced by a child on a swing
both vary continuously.
The sensor you use depends on the phenomena you are measuring. Some common analog sensors
and the physical variables they measure are listed below.
When choosing the best analog sensor to use, you must match the characteristics of the physical
variable you are measuring with the characteristics of the sensor. The two most important sensor
characteristics are:
Note You can use thermocouples and accelerometers without performing linear conversions.
Sensor Output
The output from a sensor can be an analog signal or a digital signal, and the output variable is usually
a voltage although some sensors output current.
Current Signals
Current is often used to transmit signals in noisy environments because it is much less affected by
environmental noise. The full scale range of the current signal is often either 4-20 mA or 0-20 mA. A
4-20 mA signal has the advantage that even at minimum signal value, there should be a detectable
current flowing. The absence of this indicates a wiring problem.
Voltage Signals
The most commonly interfaced signal is a voltage signal. For example, thermocouples, strain gauges,
and accelerometers all produce voltage signals. There are three major aspects of a voltage signal that
you need to consider:
• Amplitude
If the signal is less than a few millivolts, you might need to amplify it. If it is greater than the
maximum range of your analog input hardware (typically ±10 V), you must divide the signal down
using a resistor network.
1-8
Data Acquisition System
The amplitude is related to the sensitivity (resolution) of your hardware. Refer to Accuracy and
Precision on page 1-22 for more information about hardware sensitivity.
• Frequency
Whenever you acquire data, you should decide the highest frequency you want to measure.
The highest frequency component of the signal determines how often you should sample the input.
If you have more than one input, but only one analog input subsystem, then the overall sampling
rate goes up in proportion to the number of inputs. Higher frequencies might be present as noise,
which you can remove by filtering the signal before it is digitized.
If you sample the input signal at least twice as fast as the highest frequency component, then that
signal will be uniquely characterized. However, this rate might not mimic the waveform very
closely. For a rapidly varying signal, you might need a sampling rate of roughly 10 to 20 times the
highest frequency to get an accurate picture of the waveform. For slowly varying signals, you need
only consider the minimum time for a significant change in the signal.
How long do you want to sample the signal for? If you are storing data to memory or to a disk file,
then the duration determines the storage resources required. The format of the stored data also
affects the amount of storage space required. For example, data stored in ASCII format takes
more space than data stored in binary format.
Sensor Bandwidth
In a real-world data acquisition experiment, the physical phenomena you are measuring have
expected limits. For example, the temperature of your automobile's cooling system varies
continuously between its low limit and high limit. The temperature limits, as well as how rapidly the
temperature varies between the limits, depends on several factors including your driving habits, the
weather, and the condition of the cooling system. The expected limits might be readily approximated,
but there are an infinite number of possible temperatures that you can measure at a given time. As
explained in Quantization on page 1-15, these unlimited possibilities are mapped to a finite set of
values by your data acquisition hardware.
The bandwidth is given by the range of frequencies present in the signal being measured. You can
also think of bandwidth as being related to the rate of change of the signal. A slowly varying signal
has a low bandwidth, while a rapidly varying signal has a high bandwidth. To properly measure the
physical phenomena of interest, the sensor bandwidth must be compatible with the measurement
bandwidth.
You might want to use sensors with the widest possible bandwidth when making any physical
measurement. This is the one way to ensure that the basic measurement system is capable of
responding linearly over the full range of interest. However, the wider the bandwidth of the sensor,
the more you must be concerned with eliminating sensor response to unwanted frequency
components.
Signal Conditioning
Sensor signals are often incompatible with data acquisition hardware. To overcome this
incompatibility, the sensor signal must be conditioned. The type of signal conditioning required
1-9
1 Introduction to Data Acquisition
depends on the sensor you are using. For example, a signal might have a small amplitude and require
amplification, or it might contain unwanted frequency components and require filtering. Common
ways to condition signals include
• Amplification
• Filtering
• Electrical isolation
• Multiplexing
• Excitation source
Amplification
Low-level – less than approximately 100 millivolts – usually need to be amplified. High-level signals
might also require amplification depending on the input range of the analog input subsystem.
For example, the output signal from a thermocouple is small and must be amplified before it is
digitized. Signal amplification allows you to reduce noise and to make use of the full range of your
hardware thereby increasing the resolution of the measurement.
Filtering
Filtering removes unwanted noise from the signal of interest. A noise filter is used on slowly varying
signals such as temperature to attenuate higher frequency signals that can reduce the accuracy of
your measurement.
Rapidly varying signals such as vibration often require a different type of filter known as an
antialiasing filter. An antialiasing filter removes undesirable higher frequencies that might lead to
erroneous measurements.
Electrical Isolation
If the signal of interest contains high-voltage transients that could damage the computer, then the
sensor signals should be electrically isolated from the computer for safety purposes.
You can also use electrical isolation to make sure that the readings from the data acquisition
hardware are not affected by differences in ground potentials. For example, when the hardware
device and the sensor signal are each referenced to separate grounds, problems occur if there is a
potential difference between the two grounds. This difference can lead to a ground loop, which might
cause erroneous measurements. Using electrically isolated signal conditioning modules eliminates
the ground loop and ensures that the signals are accurately represented.
Multiplexing
A common technique for measuring several signals with a single measuring device is multiplexing.
Signal conditioning devices for analog signals often provide multiplexing for use with slowly changing
signals such as temperature. This is in addition to any built-in multiplexing on the DAQ board. The
A/D converter samples one channel, switches to the next channel and samples it, switches to the next
channel, and so on. Because the same A/D converter is sampling many channels, the effective
sampling rate of each individual channel is inversely proportional to the number of channels sampled.
You must take care when using multiplexers so that the switched signal has sufficient time to settle.
Refer to Noise on page 1-25 for more information about settling time.
1-10
Data Acquisition System
Excitation Source
Some sensors require an excitation source to operate. For example, strain gauges and resistive
temperature devices (RTDs) require external voltage or current excitation. Signal conditioning
modules for these sensors usually provide the necessary excitation. RTD measurements are usually
made with a current source that converts the variation in resistance to a measurable voltage.
The Computer
The computer provides a processor, a system clock, a bus to transfer data, and memory and disk
space to store data.
The processor controls how fast data is accepted by the converter. The system clock provides time
information about the acquired data. Knowing that you recorded a sensor reading is generally not
enough. You might also need to know when that measurement occurred.
Data is transferred from the hardware to system memory via dynamic memory access (DMA) or
interrupts. DMA is hardware controlled and therefore extremely fast. Interrupts might be slow
because of the latency time between when a board requests interrupt servicing and when the
computer responds. The maximum acquisition rate is also determined by the computer's bus
architecture. Refer to How Are Acquired Samples Clocked? on page 1-17 for more information about
DMA and interrupts.
Software
Regardless of the hardware you are using, you must send information to the hardware and receive
information from the hardware. You send configuration information to the hardware such as the
sampling rate, and receive information from the hardware such as data, status messages, and error
messages. You might also need to supply the hardware with information so that you can integrate it
with other hardware and with computer resources. This information exchange is accomplished with
software.
• Driver software
• Application software
For example, suppose you are using Data Acquisition Toolbox software with a National Instruments
board and its associated driver. The following diagram shows the relationship between you, the driver
software, and the application software.
1-11
1 Introduction to Data Acquisition
The diagram illustrates that you supply information to the hardware, and you receive information
from the hardware.
Driver Software
For a data acquisition device, there is associated driver software that you must use. Driver software
allows you to access and control your hardware. Among other things, basic driver software allows you
to
Application Software
Application software provides a convenient front end to the driver software. Basic application
software allows you to
MATLAB and Data Acquisition Toolbox software provide you with these capabilities, and provide tools
that let you perform analysis on the data.
1-12
Analog Input Subsystem
The function of the analog input subsystem is to sample and quantize the analog signal using one or
more channels. You can think of a channel as a path through which the sensor signal travels. Typical
analog input subsystems have eight or 16 input channels available to you. After data is sampled and
quantized, it must be transferred to system memory.
Analog signals are continuous in time and in amplitude (within predefined limits). Sampling takes a
“snapshot” of the signal at discrete times, while quantization divides the voltage (or current) value
into discrete amplitudes.
Sampling
Sampling takes a snapshot of the sensor signal at discrete times. For most applications, the time
interval between samples is kept constant (for example, sample every millisecond) unless externally
clocked.
For most digital converters, sampling is performed by a sample and hold (S/H) circuit. An S/H circuit
usually consists of a signal buffer followed by an electronic switch connected to a capacitor. The
operation of an S/H circuit follows these steps:
1 At a given sampling instant, the switch connects the buffer and capacitor to an input.
2 The capacitor is charged to the input voltage.
3 The charge is held until the A/D converter digitizes the signal.
4 For multiple channels connected (multiplexed) to one A/D converter, the previous steps are
repeated for each input channel.
5 The entire process is repeated for the next sampling instant.
A multiplexer, S/H circuit, and A/D converter are illustrated in the next section.
Hardware can be divided into two main categories based on how signals are sampled: scanning
hardware, which samples input signals sequentially, and simultaneous sample and hold (SS/H)
hardware, which samples all signals at the same time. These two types of hardware are discussed
below.
1-13
1 Introduction to Data Acquisition
Scanning Hardware
Scanning hardware samples a single input signal, converts that signal to a digital value, and then
repeats the process for every input channel used. In other words, each input channel is sampled
sequentially. A scan occurs when each input in a group is sampled once.
As shown below, most data acquisition devices have one A/D converter that is multiplexed to multiple
input channels.
Therefore, if you use multiple channels, those channels cannot be sampled simultaneously and a time
gap exists between consecutive sampled channels. This time gap is called the channel skew. You can
think of the channel skew as the time it takes the analog input subsystem to sample a single channel.
Additionally, the maximum sampling rate your hardware is rated at typically applies for one channel.
Therefore, the maximum sampling rate per channel is given by the formula:
maximumboardrate
maximumsamplingrateperchannel =
numberof channelsscanned
Typically, you can achieve this maximum rate only under ideal conditions. In practice, the sampling
rate depends on several characteristics of the analog input subsystem including the settling time and
the gain, as well as the channel skew. The following diagram shows the sample period and channel
skew for a multichannel configuration using scanning hardware.
If you cannot tolerate channel skew in your application, you must use hardware that allows
simultaneous sampling of all channels. Simultaneous sample and hold hardware is discussed in the
next section.
1-14
Analog Input Subsystem
Simultaneous sample and hold (SS/H) hardware samples all input signals at the same time and holds
the values until the A/D converter digitizes all the signals. For high-end systems, there can be a
separate A/D converter for each input channel.
For example, suppose you need to simultaneously measure the acceleration of multiple
accelerometers to determine the vibration of some device under test. To do this, you must use SS/H
hardware because it does not have a channel skew. In general, you might need to use SS/H hardware
if your sensor signal changes significantly in a time that is less than the channel skew, or if you need
to use a transfer function or perform a frequency domain correlation.
The following diagram shows sample period for a multichannel configuration using SS/H hardware.
Note that there is no channel skew.
Quantization
As discussed in the previous section, sampling takes a snapshot of the input signal at an instant of
time. When the snapshot is taken, the sampled analog signal must be converted from a voltage value
to a binary number that the computer can read. The conversion from an infinitely precise amplitude
to a binary number is called quantization.
During quantization, the A/D converter uses a finite number of evenly spaced values to represent the
analog signal. The number of different values is determined by the number of bits used for the
conversion. Most modern converters use 12 or 16 bits. Typically, the converter selects the digital
value that is closest to the actual sampled value.
The figure below shows a 1 Hz sine wave quantized by a 3 bit A/D converter.
1-15
1 Introduction to Data Acquisition
The number of quantized values is given by 23 = 8, the largest representable value is given by 111 =
22 + 21 + 20 = 7.0, and the smallest representable value is given by 000 = 0.0.
Quantization Error
There is always some error associated with the quantization of a continuous signal. Ideally, the
maximum quantization error is ±0.5 least significant bits (LSBs), and over the full input range, the
average quantization error is zero.
As shown below, the quantization error for the previous sine wave is calculated by subtracting the
actual signal from the quantized signal.
The input range of the analog input subsystem is the span of input values for which a conversion is
valid. You can change the input range by selecting a different gain value. For example, National
1-16
Analog Input Subsystem
Instruments' AT-MIO-16E-1 board has eight gain values ranging from 0.5 to 100. Many boards include
a programmable gain amplifier that allows you to change the device gain through software.
When an input signal exceeds the valid input range of the converter, an overrange condition occurs.
In this case, most devices saturate to the largest representable value, and the converted data is
almost definitely incorrect. The gain setting affects the precision of your measurement — the higher
(lower) the gain value, the lower (higher) the precision. Refer to How Are Range, Gain, and
Measurement Precision Related? on page 1-24 for more information about how input range, gain,
and precision are related to each other.
An analog input subsystem can typically convert both unipolar signals and bipolar signals. A unipolar
signal contains only positive values and zero, while a bipolar signal contains positive values, negative
values, and zero.
Unipolar and bipolar signals are depicted below. Refer to the figure in “Quantization” on page 1-15
for an example of a unipolar signal.
In many cases, the signal polarity is a fixed characteristic of the sensor and you must configure the
input range to match this polarity.
As you can see, it is crucial to understand the range of signals expected from your sensor so that you
can configure the input range of the analog input subsystem to maximize resolution and minimize the
chance of an overrange condition.
Samples are acquired from an analog input subsystem at a specific rate by a clock. Like any timing
system, data acquisition clocks are characterized their resolution and accuracy. Timing resolution is
defined as the smallest time interval that you can accurately measure. The timing accuracy is affected
by clock jitter. Jitter arises when a clock produces slightly different values for a given time interval.
For any data acquisition system, there are typically three clock sources that you can use: the onboard
data acquisition clock, the computer clock, or an external clock. Data Acquisition Toolbox software
supports all of these clock sources, depending on the requirements of your hardware.
Onboard Clock
The onboard clock is typically a timer chip on the hardware board that is programmed to generate a
pulse stream at the desired rate. The onboard clock generally has high accuracy and low jitter
compared to the computer clock. You should always use the onboard clock when the sampling rate is
high, and when you require a fixed time interval between samples. The onboard clock is referred to
as the internal clock in this guide.
1-17
1 Introduction to Data Acquisition
Computer Clock
The computer (PC) clock is used for boards that do not possess an onboard clock. The computer clock
is less accurate and has more jitter than the onboard clock, and is generally limited to sampling rates
below 500 Hz. The computer clock is referred to as the software clock in this guide.
External Clock
An external clock is often used when the sampling rate is low and not constant. For example, an
external clock source is often used in automotive applications where samples are acquired as a
function of crank angle.
Channel Configuration
You can configure input channels in one of these two ways:
• Differential
• Single-ended
Your choice of input channel configuration might depend on whether the input signal is floating or
grounded.
A floating signal uses an isolated ground reference and is not connected to the building ground. As a
result, the input signal and hardware device are not connected to a common reference, which can
cause the input signal to exceed the valid range of the hardware device. To circumvent this problem,
you must connect the signal to the onboard ground of the device. Examples of floating signal sources
include ungrounded thermocouples and battery devices.
A grounded signal is connected to the building ground. As a result, the input signal and hardware
device are connected to a common reference. Examples of grounded signal sources include
nonisolated instrument outputs and devices that are connected to the building power system.
Note For more information about channel configuration, refer to your hardware documentation.
Differential Inputs
When you configure your hardware for differential input, there are two signal wires associated with
each input signal — one for the input signal and one for the reference (return) signal. The
measurement is the difference in voltage between the two wires, which helps reduce noise and any
voltage that is common to both wires.
As shown below, the input signal is connected to the positive amplifier socket (labeled +) and the
return signal is connected to the negative amplifier socket (labeled -). The amplifier has a third
connector that allows these signals to be referenced to ground.
1-18
Analog Input Subsystem
National Instruments recommends that you use differential inputs under any of these conditions:
Single-Ended Inputs
When you configure your hardware for single-ended input, there is one signal wire associated with
each input signal, and each input signal is connected to the same ground. Single-ended
measurements are more susceptible to noise than differential measurements because of differences
in the signal paths.
As shown below, the input signal is connected to the positive amplifier socket (labeled +) and the
ground is connected to the negative amplifier socket (labeled -).
National Instruments suggests that you can use single-ended inputs under any of these conditions:
You should use differential input connectors for any input signal that does not meet the preceding
conditions. You can configure many National Instruments boards for two different types of single-
ended connections:
The RSE configuration is used for floating signal sources. In this case, the hardware device itself
provides the reference ground for the input signal.
1-19
1 Introduction to Data Acquisition
The NRSE input configuration is used for grounded signal sources. In this case, the input signal
provides its own reference ground and the hardware device should not supply one.
Refer to your National Instruments hardware documentation for more information about RSE and
NRSE connections.
These steps happen automatically. Typically, all that's required from you is some initial configuration
of the hardware device when it is installed.
FIFO Buffer
The FIFO buffer is used to temporarily store acquired data. The data is temporarily stored until it can
be transferred to system memory. The process of transferring data into and out of an analog input
FIFO buffer is given below:
1 The FIFO buffer stores newly acquired samples at a constant sampling rate.
2 Before the FIFO buffer is filled, the software starts removing the samples. For example, an
interrupt is generated when the FIFO is half full, and signals the software to extract the samples
as quickly as possible.
3 Because servicing interrupts or programming the DMA controller can take up to a few
milliseconds, additional data is stored in the FIFO for future retrieval. For a larger FIFO buffer,
longer latencies can be tolerated.
4 The samples are transferred to system memory via the system bus (for example, PCI bus or AT
bus). After the samples are transferred, the software is free to perform other tasks until the next
interrupt occurs. For example, the data can be processed or saved to a disk file. As long as the
average rates of storing and extracting data are equal, acquired data will not be missed and your
application should run smoothly.
Interrupts
The slowest but most common method to move acquired data to system memory is for the board to
generate an interrupt request (IRQ) signal. This signal can be generated when one sample is acquired
or when multiple samples are acquired. The process of transferring data to system memory via
interrupts is given below:
1 When data is ready for transfer, the CPU stops whatever it is doing and runs a special interrupt
handler routine that saves the current machine registers, and then sets them to access the board.
2 The data is extracted from the board and placed into system memory.
3 The saved machine registers are restored, and the CPU returns to the original interrupted
process.
1-20
Analog Input Subsystem
The actual data move is fairly quick, but there is a lot of overhead time spent saving, setting up, and
restoring the register information. Therefore, depending on your specific system, transferring data by
interrupts might not be a good choice when the sampling rate is greater than around 5 kHz.
DMA
Direct memory access (DMA) is a system whereby samples are automatically stored in system
memory while the processor does something else. The process of transferring data via DMA is given
below:
1 When data is ready for transfer, the board directs the system DMA controller to put it into in
system memory as soon as possible.
2 As soon as the CPU is able (which is usually very quickly), it stops interacting with the data
acquisition hardware and the DMA controller moves the data directly into memory.
3 The DMA controller gets ready for the next sample by pointing to the next open memory location.
4 The previous steps are repeated indefinitely, with data going to each open memory location in a
continuously circulating buffer. No interaction between the CPU and the board is needed.
Your computer supports several different DMA channels. Depending on your application, you can use
one or more of these channels, For example, simultaneous input and output with a sound card
requires one DMA channel for the input and another DMA channel for the output.
1-21
1 Introduction to Data Acquisition
In this section...
“What Do You Measure?” on page 1-22
“Accuracy and Precision” on page 1-22
“Noise” on page 1-25
“Matching the Sensor Range and A/D Converter Range” on page 1-25
“How Fast Should a Signal Be Sampled?” on page 1-26
In many cases, the sensor signal is a voltage level that is proportional to the physical phenomena of
interest (for example, temperature, pressure, or acceleration). If you are measuring slowly changing
(quasi-static) phenomena like temperature, a slow sampling rate usually suffices. If you are
measuring rapidly changing (dynamic) phenomena like vibration or acoustic measurements, a fast
sampling rate is required.
In general terms, the accuracy of a measurement determines how close the measurement comes to
the true value. Therefore, it indicates the correctness of the result. The precision of a measurement
reflects how exactly the result is determined without reference to what the result means. The relative
precision indicates the uncertainty in a measurement as a fraction of the result.
For example, suppose you measure a table top with a meter stick and find its length to be 1.502
meters. This number indicates that the meter stick (and your eyes) can resolve distances down to at
least a millimeter. Under most circumstances, this is considered to be a fairly precise measurement
with a relative precision of around 1/1500. However, suppose you perform the measurement again
and obtain a result of 1.510 meters. After careful consideration, you discover that your initial
technique for reading the meter stick was faulty because you did not read it from directly above.
Therefore, the first measurement was not accurate.
1-22
Making Quality Measurements
For analog input subsystems, accuracy is usually limited by calibration errors while precision is
usually limited by the A/D converter. Accuracy and precision are discussed in more detail below.
Accuracy
Accuracy is defined as the agreement between a measured quantity and the true value of that
quantity. Every component that appears in the analog signal path affects system accuracy and
performance. The overall system accuracy is given by the component with the worst accuracy.
For data acquisition hardware, accuracy is often expressed as a percent or a fraction of the least
significant bit (LSB). Under ideal circumstances, board accuracy is typically ±0.5 LSB. Therefore, a
12 bit converter has only 11 usable bits.
Many boards include a programmable gain amplifier, which is located just before the converter input.
To prevent system accuracy from being degraded, the accuracy and linearity of the gain must be
better than that of the A/D converter. The specified accuracy of a board is also affected by the
sampling rate and the settling time of the amplifier. The settling time is defined as the time required
for the instrumentation amplifier to settle to a specified accuracy. To maintain full accuracy, the
amplifier output must settle to a level given by the magnitude of 0.5 LSB before the next conversion,
and is on the order of several tenths of a millisecond for most boards.
Settling time is a function of sampling rate and gain value. High rate, high gain configurations
require longer settling times while low rate, low gain configurations require shorter settling times.
Precision
The number of bits used to represent an analog signal determines the precision (resolution) of the
device. The more bits provided by your board, the more precise your measurement will be. A high
precision, high resolution device divides the input range into more divisions thereby allowing a
smaller detectable voltage value. A low precision, low resolution device divides the input range into
fewer divisions thereby increasing the detectable voltage value.
1-23
1 Introduction to Data Acquisition
The overall precision of your data acquisition system is usually determined by the A/D converter, and
is specified by the number of bits used to represent the analog signal. Most boards use 12 or 16 bits.
The precision of your measurement is given by:
numberof bits
precision = one part in 2
voltage range
precision = number of bits
2
For example, if you are using a 12 bit A/D converter configured for a 10 volt range, then
10 volts
precision = 12
2
This means that the converter can detect voltage differences at the level of 0.00244 volts (2.44 mV).
When you configure the input range and gain of your analog input subsystem, the end result should
maximize the measurement resolution and minimize the chance of an overrange condition. The actual
input range is given by the formula:
input range
actual input range =
gain
The relationship between gain, actual input range, and precision for a unipolar and bipolar signal
having an input range of 10 V is shown below.
Input Range Gain Actual Input Range Precision (12 Bit A/D)
0 to 10 V 1.0 0 to 10 V 2.44 mV
2.0 0 to 5 V 1.22 mV
5.0 0 to 2 V 0.488 mV
10.0 0 to 1 V 0.244 mV
-5 to 5 V 0.5 -10 to 10 V 4.88 mV
1.0 -5 to 5 V 2.44 mV
2.0 -2.5 to 2.5 V 1.22 mV
5.0 -1.0 to 1.0 V 0.488 mV
10.0 -0.5 to 0.5 V 0.244 mV
As shown in the table, the gain affects the precision of your measurement. If you select a gain that
decreases the actual input range, then the precision increases. Conversely, if you select a gain that
increases the actual input range, then the precision decreases. This is because the actual input range
varies but the number of bits used by the A/D converter remains fixed.
Note With Data Acquisition Toolbox software, you do not have to specify the range and gain. Instead,
you simply specify the actual input range desired.
1-24
Making Quality Measurements
Noise
Noise is considered to be any measurement that is not part of the phenomena of interest. Noise can
be generated within the electrical components of the input amplifier (internal noise), or it can be
added to the signal as it travels down the input wires to the amplifier (external noise). Techniques
that you can use to reduce the effects of noise are described below.
Internal noise arises from thermal effects in the amplifier. Amplifiers typically generate a few
microvolts of internal noise, which limits the resolution of the signal to this level. The amount of noise
added to the signal depends on the bandwidth of the input amplifier.
To reduce internal noise, you should select an amplifier with a bandwidth that closely matches the
bandwidth of the input signal.
External noise arises from many sources. For example, many data acquisition experiments are subject
to 60 Hz noise generated by AC power circuits. This type of noise is referred to as pick-up or hum,
and appears as a sinusoidal interference signal in the measurement circuit. Another common
interference source is fluorescent lighting. These lights generate an arc at twice the power line
frequency (120 Hz).
Noise is added to the acquisition circuit from these external sources because the signal leads act as
aerials picking up environmental electrical activity. Much of this noise is common to both signal
wires. To remove most of this common-mode voltage, you should
• Configure the input channels in differential mode. Refer to Channel Configuration on page 1-18
for more information about channel configuration.
• Use signal wires that are twisted together rather than separate.
• Keep the signal wires as short as possible.
• Keep the signal wires as far away as possible from environmental electrical activity.
Filtering
Filtering also reduces signal noise. For many data acquisition applications, a low-pass filter is
beneficial. As the name suggests, a low-pass filter passes the lower frequency components but
attenuates the higher frequency components. The cut-off frequency of the filter must be compatible
with the frequencies present in the signal of interest and the sampling rate used for the A/D
conversion.
A low-pass filter that's used to prevent higher frequencies from introducing distortion into the
digitized signal is known as an antialiasing filter if the cut-off occurs at the Nyquist frequency. That is,
the filter removes frequencies greater than one-half the sampling frequency. These filters generally
have a sharper cut-off than the normal low-pass filter used to condition a signal. Antialiasing filters
are specified according to the sampling rate of the system and there must be one filter per input
signal.
1-25
1 Introduction to Data Acquisition
• The expected range of the data produced by your sensor. This range depends on the physical
phenomena you are measuring and the output range of the sensor.
• The range of your A/D converter. For many devices, the hardware range is specified by the gain
and polarity.
You should select the sensor and hardware ranges such that the maximum precision is obtained, and
the full dynamic range of the input signal is covered.
For example, suppose you are using a microphone with a dynamic range of 20 dB to 140 dB and an
output sensitivity of 50 mV/Pa. If you are measuring street noise in your application, then you might
expect that the sound level never exceeds 80 dB, which corresponds to a sound pressure magnitude
of 200 mPa and a voltage output from the microphone of 10 mV. Under these conditions, you should
set the input range of your data acquisition card for a maximum signal amplitude of 10 mV, or a little
more.
If you sample at a rate that is too slow, then signal aliasing can occur. Aliasing can occur for both
rapidly varying signals and slowly varying signals. For example, suppose you are measuring
temperature once a minute. If your acquisition system is picking up a 60-Hz hum from an AC power
supply, then that hum will appear as constant noise level if you are sampling at 30 Hz.
Aliasing occurs when the sampled signal contains frequency components greater than one-half the
sampling rate. The frequency components could originate from the signal of interest in which case
you are undersampling and should increase the sampling rate. The frequency components could also
originate from noise in which case you might need to condition the signal using a filter. The rule used
to prevent aliasing is given by the Nyquist theorem, which states that
• An analog signal can be uniquely reconstructed, without error, from samples taken at equal time
intervals.
• The sampling rate must be equal to or greater than twice the highest frequency component in the
analog signal. A frequency of one-half the sampling rate is called the Nyquist frequency.
However, if your input signal is corrupted by noise, then aliasing can still occur.
For example, suppose you configure your A/D converter to sample at a rate of 4 samples per second
(4 S/s or 4 Hz), and the signal of interest is a 1 Hz sine wave. Because the signal frequency is one-
fourth the sampling rate, then according to the Nyquist theorem, it should be completely
characterized. However, if a 5 Hz sine wave is also present, then these two signals cannot be
distinguished. In other words, the 1 Hz sine wave produces the same samples as the 5 Hz sine wave
when the sampling rate is 4 S/s. The following diagram illustrates this condition.
1-26
Making Quality Measurements
In a real-world data acquisition environment, you might need to condition the signal by filtering out
the high frequency components.
Even though the samples appear to represent a sine wave with a frequency of one-fourth the
sampling rate, the actual signal could be any sine wave with a frequency of:
n ± 0.25 × sampling rate
where n is zero or any positive integer. For this example, the actual signal could be at a frequency of
3 Hz, 5 Hz, 7 Hz, 9 Hz, and so on. The relationship 0.25 × (sampling rate) is called the alias of a
signal that might be at another frequency. In other words, aliasing occurs when one frequency
assumes the identity of another frequency.
If you sample the input signal at least twice as fast as the highest frequency component, then that
signal might be uniquely characterized, but this rate would not mimic the waveform very closely. As
shown below, to get an accurate picture of the waveform, you need a sampling rate of roughly 10 to
20 times the highest frequency.
1-27
1 Introduction to Data Acquisition
As shown in the top figure, the low sampling rate produces a sampled signal that appears to be a
triangular waveform. As shown in the bottom figure, a higher fidelity sampled signal is produced
when the sampling rate is higher. In the latter case, the sampled signal actually looks like a sine
wave.
The primary considerations involved in antialiasing are the sampling rate of the A/D converter and
the frequencies present in the sampled data. To eliminate aliasing, you must
1-28
Selected Bibliography
Selected Bibliography
[1] Transducer Interfacing Handbook — A Guide to Analog Signal Conditioning, edited by Daniel H.
Sheingold; Analog Devices Inc., Norwood, MA, 1980.
[2] Bentley, John P., Principles of Measurement Systems, Second Edition; Longman Scientific and
Technical, Harlow, Essex, UK, 1988.
[3] Bevington, Philip R., Data Reduction and Error Analysis for the Physical Sciences; McGraw-Hill,
New York, NY, 1969.
[4] Carr, Joseph J., Sensors; Prompt Publications, Indianapolis, IN, 1997.
[5] The Measurement, Instrumentation, and Sensors Handbook, edited by John G. Webster; CRC
Press, Boca Raton, FL, 1999.
[6] PCI-MIO E Series User Manual, January 1997 Edition; Part Number 320945B-01, National
Instruments, Austin, TX, 1997.
1-29
2
This topic provides the information you need to get started with Data Acquisition Toolbox software.
The sections are as follows.
Installation Information
In this section...
“Prerequisites” on page 2-2
“Toolbox Installation” on page 2-2
“Hardware and Driver Installation” on page 2-2
Prerequisites
To acquire live, measured data or generate signals between the MATLAB workspace, you must install
these components:
Toolbox Installation
To determine if Data Acquisition Toolbox software is installed on your system, type
ver
at the MATLAB prompt. The Command Window lists information about the software versions you are
running, including installed add-on products and their version numbers. Check the list to see if Data
Acquisition Toolbox appears. For information about installing the toolbox, see the MATLAB
Installation documentation.
If you experience installation difficulties and have Internet access, look for the license manager and
installation information at the MathWorks website (https://www.mathworks.com).
See Also
Related Examples
• “Set Up Your System for Device Detection” on page A-10
2-2
Access Your Hardware
In this section...
“Connect to Your Hardware” on page 2-3
“Examine Your Hardware Resources” on page 2-3
“Acquire Audio Data” on page 2-4
“Generate Audio Data” on page 2-4
“Acquire and Generate Digital Data” on page 2-5
Each example in this topic illustrates a typical data acquisition workflow. A workflow comprises all
the steps you are likely to take when acquiring or outputting data using a supported hardware device.
You should keep these steps in mind when constructing your own data acquisition applications.
Note that the analog input and analog output examples use a sound card, while the digital I/O
example uses a National Instruments board. If you are using a different supported hardware device,
you should modify the vendor name and the device ID as needed.
If you want detailed information about any functions that are used, refer to the list of functions.
Note If you are connecting to a CompactDAQ devices or a counter/timer device, see “Counter and
Timer Input and Output”.
daqlist("directsound")
daqlist("ni")
daqlist
daqvendorlist
2-3
2 Using Data Acquisition Toolbox Software
If you have a sound card installed, you can run the following example, which acquires 1 second of
data an audio input hardware channels, and then plots the acquired data.
You should modify this example to suit your specific application needs.
1 Create a DataAcquisition object — Create the DataAcquisition object d for a sound card.
d = daq('directsound');
2 Identify the system devices and their IDs for audio input and output.
daqlist("directsound")
7×4 table
"Audio0" "DirectSound Primary Sound Capture Driver" "Primary Sound Capture Driver" [1×
"Audio1" "DirectSound Headset Microphone (Plantronics BT600)" "Headset Microphone (Plantronics BT600)" [1×
"Audio2" "DirectSound Primary Sound Driver" "Primary Sound Driver" [1×
"Audio3" "DirectSound Headset Earphone (Plantronics BT600)" "Headset Earphone (Plantronics BT600)" [1×
"Audio4" "DirectSound Speakers (2- Realtek High Definition Audio)" "Speakers (2- Realtek High Definition Audio)" [1×
"Audio5" "DirectSound Speakers (Realtek High Definition Audio)" "Speakers (Realtek High Definition Audio)" [1×
"Audio6" "DirectSound LEN LT2452pwC (NVIDIA High Definition Audio)" "LEN LT2452pwC (NVIDIA High Definition Audio)" [1×
3 Add channel — Add an audio input channel to d for the microphone device.
addinput(d,"Audio1","1","Audio");
ans =
4 Acquire data — Start the acquisition. When all the data is acquired, it is assigned to data.
data = read(d,seconds(1));
plot(data)
5 Clean up — When you no longer need d, you should remove it from memory.
delete(d)
clear d
If you have a sound card installed, you can run the following example, which outputs 1 second of data
to two analog output hardware channels.
You should modify this example to suit your specific application needs.
1 Create a DataAcquisition object — Create the DataAcquisition object d for a sound card.
d = daq('directsound');
2-4
Access Your Hardware
2 Add channel — Add an audio output channel to DataAcquisition d. This example uses the device
ID Audio4 for the speakers.
addoutput(d,"Audio4',"1","Audio");
3 Output data — Create 1 second of output data, and queue the data for output from the device.
You queue a matrix with one column of data for each hardware channel.
data = sin(linspace(0,2*pi*500,44100)');
preload(d,data)
Start the output. When all the data is output, d stops generating.
start(d)
4 Clean up — When you no longer need d, you should remove it from memory and from the
MATLAB workspace.
delete(d)
clear d
If you have a supported National Instruments board with at least two digital I/O ports, you can run
the following example, which writes and reads digital values.
You should modify this example to suit your specific application needs. Adjust the example if the ports
on your device do not support the input/output directions specified here.
s = daq("ni");
2 Add digital input channels — Add two lines from port 0 to d, and configure them for input.
addinput(d,"cDAQ1Mod1","Port0/Line0:1","Digital");
3 Add digital output lines — Add two lines from port 0 to s, and configure them for output.
addoutput(d,"cDAQ1Mod1","Port0/Line2:3","Digital");
ans =
4 Add clock and trigger — To synchronize operations, add a clock and trigger connection.
2-5
2 Using Data Acquisition Toolbox Software
addclock(d,"ScanClock","External","cDAQ1/PFI0");
addtrigger(d,"Digital","StartTrigger","External","cDAQ1/PFI1");
d.Clocks,d.DigitalTriggers
ans =
Source: 'External'
Destination: 'cDAQ1/PFI0'
Type: ScanClock
ans =
Source: 'External'
Destination: 'cDAQ1/PFI1'
Type: StartTrigger
Condition: 'RisingEdge'
Note Digital line values are usually not transferred at a specific rate. Although some specialized
boards support clocked I/O.
5 Queue output data and start device — Create an array of output values, and queue the values.
Note that reading and writing digital I/O line values typically does not require that you configure
specific property values.
preload(d,round(rand(4000,2)));
gval = start(d);
6 Display input — To read only the input lines, type:
gval
7 Clean up — When you no longer need d, you should remove it from memory and from the
MATLAB workspace.
delete(d)
clear d
2-6
3
For an explanation of how this communication works, see Data Acquisition System on page 1-5. The
relationship between you, the application software, the driver software, the chassis, and the devices
is shown here.
For more information about creating a DataAcquisition, see “Create a DataAcquisition Interface” on
page 4-5.
See Also
More About
• “Limitations by Vendor” on page B-2
3-2
Get Command-Line Help
help daq
or
daqhelp
The Command Window displays links for the functions of the DataAcquisition interface.
daqhelp function_name
For example,
daqhelp readwrite
You can get help on individual properties of the toolbox objects. For example, to see help on the
Channels property of a DataAcquisition object, type:
help daq.interfaces.DataAcquisition.Channels
It can be easier to get function and property help if the object exists in the workspace. For example,
d = daq("ni");
help d.Rate
help d.addinput
3-3
4
Interface Workflow
In this section...
“Working a DataAcquisition” on page 4-2
“DataAcquisition Interface and Data Acquisition Toolbox” on page 4-2
Working a DataAcquisition
Use the DataAcquisition object to communicate with data acquisition devices, such as National
Instruments devices including a CompactDAQ chassis.
You can also synchronize operations within the DataAcquisition. See “Synchronization” on page 13-
2 for more information.
You can create a DataAcquisition with both analog input and analog output channels and configure
acquisition and generation simultaneously. See “Acquire Data and Generate Signals Simultaneously”
on page 6-16 for more information.
See Also
More About
• “Transition Your Code from Session to DataAcquisition Interface” on page 14-2
4-2
Digital Input and Output
4-3
4 Using the DataAcquisition Interface
dev = daqlist
dev =
4×5 table
dev.DeviceInfo(2)
ans =
Digital IO supports:
8 channels ('port0/line0' - 'port1/line3')
'InputOnly','OutputOnly' measurement types
4-4
Create a DataAcquisition Interface
daqlist("ni")
2×4 table
d = daq("ni")
Running: 0
Rate: 1000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
After you create a DataAcquisition object, add channels using the addinput and addoutput
functions.
Add an analog input channel, and view the DataAcquisition channel list:
addinput(d,"Dev3","ai0","Voltage")
d.Channels
Index Type Device Channel Measurement Type Range Name
_____ ____ ______ _______ ________________ __________________ __________
Change the channel TerminalConfig property to 'SingleEnded', and view the updated
configuration:
d.Channels.TerminalConfig = "SingleEnded";
d.Channels
Index Type Device Channel Measurement Type Range Name
_____ ____ ______ _______ _____________________ __________________ __________
4-5
4 Using the DataAcquisition Interface
See Also
Related Examples
• “Acquire Counter Input Data” on page 8-3
• “Generate Pulse Data on a Counter Channel” on page 8-6
More About
• “Analog Input and Output”
• “Transition Your Code from Session to DataAcquisition Interface” on page 14-2
4-6
Channel Properties
Channel Properties
d = daq("ni");
ch = addinput(d,"Dev1",1,"Voltage");
get(ch)
Coupling: DC
TerminalConfig: Differential
Range: -10 to +10 Volts
Name: 'Dev1_ai1'
ID: 'ai1'
Device: [1x1 daq.ni.DeviceInfo]
MeasurementType: 'Voltage'
set(ch)
Coupling: [ DC | AC ]
TerminalConfig: [ Differential | SingleEnded | SingleEndedNonReferenced | PseudoDifferential ]
Range: -10 to +10 Volts
Name: {}
ch.TerminalConfig = "SingleEnded"
ch =
You can also request help in the Command Window on a specific property, providing either the object
and property, or the class name and property. For example:
help ch.TerminalConfig
or
help ("daq.AnalogInputVoltageChannel.TerminalConfig")
All Channels
All channel objects have these properties in common for all measurement types:
4-7
4 Using the DataAcquisition Interface
'Voltage'
'Current'
'Thermocouple'
'Digital'
'Audio'
Voltage Measurement
'AC'
'DC'
TerminalConfig Channel terminal configuration character vector of:
as described in “Channel
Configuration” on page 1-18 'Differential'
'SingleEnded'
'SingleEndedNonReferenced'
'PseudoDifferential'
Current Measurement
4-8
Channel Properties
'AC'
'DC'
TerminalConfig Channel terminal configuration character vector of:
as described in “Channel
Configuration” on page 1-18 'Differential'
'SingleEnded'
'SingleEndedNonReferenced'
'PseudoDifferential'
Current Input and Output
ShuntLocation (Only some vendors) Indicates if character vector of:
the shunt resistor is located
internally on the device or 'Internal'
'External'
externally
ShuntResistance (Only some vendors) Indicates double
shunt resistance in ohms
Thermocouple Measurement
'Celsius' (default)
'Fahrenheit'
'Kelvin'
'Rankine'
4-9
4 Using the DataAcquisition Interface
Accelerometer Measurement
'AC'
'DC'
TerminalConfig Channel input configuration as character vector of:
described in “Channel
Configuration” on page 1-18 'Differential'
'SingleEnded'
'SingleEndedNonReferenced'
'PseudoDifferential'
Range Input value range double values depending on
measurement type and device
support
RTD Measurement
'Celsius' (default)
'Fahrenheit'
'Kelvin'
'Rankine'
4-10
Channel Properties
'AC'
'DC'
TerminalConfig Channel input configuration as character vector of:
described in “Channel
Configuration” on page 1-18 'Differential'
'SingleEnded'
'SingleEndedNonReferenced'
'PseudoDifferential'
Range Input value range double values depending on
measurement type and device
support
Bridge Measurement
4-11
4 Using the DataAcquisition Interface
Microphone Measurement
'AC'
'DC'
4-12
Channel Properties
IEPE Measurement
'AC'
'DC'
TerminalConfig Channel input configuration as character vector of:
described in “Channel
Configuration” on page 1-18 'Differential'
'SingleEnded'
'SingleEndedNonReferenced'
'PseudoDifferential'
Range Input value range double values depending on
measurement type and device
support
Digital Channels
Digital channel objects include the following properties:
4-13
4 Using the DataAcquisition Interface
Counter Channels
• “All Counter Channels” on page 4-14
• “Edge Count” on page 4-14
• “Frequency” on page 4-14
• “Position” on page 4-14
• “Pulse Width” on page 4-15
• “Pulse Generation” on page 4-15
Counter input and output channel objects also include these properties:
Edge Count
Counter input edge count channels also include the following properties:
'Increment'
'Decrement'
InitialCount Value to count from uint32
Terminal Terminal on device character vector, for example
'PFI2'
Frequency
Counter input frequency measurement channels also include the following properties:
'PFI2'
Position
For an overview of position measurement, including signals, encoding types, and Z-indexing, see
National Instruments Encoder Measurements: How-To Guide. See also “Measure Angular Position
with an Incremental Rotary Encoder” on page 18-110.
Counter input position measurement channels also include the following properties:
4-14
Channel Properties
Pulse Width
Counter input pulse width measurement channels also include the following properties:
'High'
'Low'
Terminal External terminal on device character vector, for example:
'PFI2'
Pulse Generation
Counter output pulse generation channels also include the following properties:
4-15
4 Using the DataAcquisition Interface
Audio Channels
Audio input and output channel objects also include these properties:
4-16
Channel Properties
'Sine'
'Square'
'Triangle'
'RampUp'
'RampDown'
'DC'
'Arbitrary'
FrequencyLimit Minimum and maximum rates double
that the function generation
channel supports
See Also
Functions
addinput | addoutput | addbidirectional
4-17
5
In this section...
“Install Support Packages” on page 5-2
“Update or Uninstall Support Packages” on page 5-2
To communicate with a data acquisition device, you need to install the required support package on
your system for the device vendor. Data Acquisition Toolbox support packages are available for the
following vendors:
1 On the MATLAB Home tab, in the Environment section, click Add-Ons > Get Hardware
Support Packages.
2 In the left pane of the Add-On Explorer, scroll to Filter by Type and check Hardware Support
Packages.
3 Under Filter by Vendor check the vendor of your device. The Add-On Explorer displays support
packages for that vendor. Click the support package for your vendor and device.
4 Click Install > Install. Sign in to your MathWorks® account if necessary, and proceed.
On the MATLAB Home tab, in the Environment section, click Add-Ons > Manage Add-Ons.
On the MATLAB Home tab, in the Environment section, click Add-Ons > Check for Updates >
Hardware Support Packages.
See Also
More About
• “Get and Manage Add-Ons”
5-2
6
d = daq("ni")
d =
Running: 0
Rate: 1000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
By default, the acquisition is configured to acquire at the rate of 1000 scans per second.
Add an analog input channel for voltage measurement, using the device channel ai0:
addinput(d,"cDAQ1Mod1","ai0","Voltage");
Acquire data for 2 seconds and store it in the variable, data, then plot it:
data = read(d,seconds(2),"OutputFormat","Matrix");
plot(data)
Specify an acquisition of 4096 scans of data. Changing the number of scans changes the duration of
the acquisition to 4.096 seconds at the default rate of 1000 scans per second.
Acquire the data and store it in the variable data, and then plot it:
data = read(d,4096,"OutputFormat","Matrix");
plot(data)
See Also
Related Examples
• “Acquire Data in the Background with Live Plot Updates” on page 6-4
6-2
Acquire Data from Multiple Channels
Create a DataAcquisition object and add two analog input voltage channels for cDAQ1Mod1 with
channel IDs 0 and 1:
d = daq("ni");
addinput(d,"cDAQ1Mod1",0:1,"Voltage")
ch =
Add an additional channel for a separate device, cDAQ1Mod6 with channel ID 0. For NI devices, use
either a terminal name, like ai0, or a numeric equivalent like 0. Then view all channels on the
DataAcquisition.
ch = addinput(d,"cDAQ1Mod6","ai0","Voltage");
d.Channels
Acquire one second of data and store it in the variable data, and then plot it:
data = read(d,seconds(1),"OutputFormat","Matrix");
plot(data)
Change the properties of the channel ai0 on cDAQ1Mod6 and display ch:
ch.TerminalConfig ="SingleEnded";
ch.Name = "Velocity sensor";
ch
ch =
1 "ai" "cDAQ1Mod6" "ai0" "Voltage (SingleEnd)" "-10 to +10 Volts" "Velocity sensor"
Acquire the data and store it in the variable, data, and plot it:
data = read(d,seconds(1),"OutputFormat","Matrix");
plot(data)
See Also
Related Examples
• “Acquire Data in the Foreground” on page 6-2
• “Acquire Data in the Background with Live Plot Updates” on page 6-4
6-3
6 Analog Input and Output
A background acquisition uses callbacks to allow your code to access data as the hardware acquires
it or to react to any errors as they occur. In this example, you acquire data from a microphone with ID
Audio1 using the ScansAvailableFcnCount property to trigger the function call defined by the
ScansAvailableFcn property. Using a callback allows a plot to be updated in real time while
acquisition continues.
Get a list of devices so you can identify the microphone you want to use. The partial listing here
indicates the device ID.
daqlist
Create a directsound DataAcquisition object with a microphone input channel on Audio1. You
might have to use a different device.
d = daq("directsound");
ch = addinput(d,"Audio1",1,"audio");
Create a simple callback function to plot the acquired data and save it as plotMyData.m in your
current working folder. Enter the following code in the file.
function plotMyData(obj,evt)
% obj is the DataAcquisition object passed in. evt is not used.
data = read(obj,obj.ScansAvailableFcnCount,"OutputFormat","Matrix");
plot(data)
end
Set the callback function property of the DataAcquisition object to use your function.
d.ScansAvailableFcn = @plotMyData;
start(d,"Duration",seconds(5))
Speak into the microphone and watch the plot. It updates 10 times per second.
See Also
Functions
daqlist | daq | addinput | start
Related Examples
• “Acquire Data in the Foreground” on page 6-2
6-4
Acquire Bridge Measurements
d = daq("ni");
Add an analog input channel for Bridge measurement type, assigned to the variable ch:
ch = addinput(d,"cDAQ1Mod7","ai1","Bridge");
ch.ADCTimingMode = "HighSpeed"
d.Rate = 10;
Set the channel BridgeMode to 'Full', which uses all four resistors in the device to acquire the
voltage values:
ch.BridgeMode = "Full"
ch =
BridgeMode: Full
ExcitationSource: Internal
ExcitationVoltage: 2.5
NominalBridgeResistance: 'Unknown'
Range: -0.063 to +0.063 VoltsPerVolt
Name: empty
ID: 'ai1'
Device: [1x1 daq.ni.CompactDAQModule]
MeasurementType: 'Bridge'
ADCTimingMode: HighSpeed
ch.NominalBridgeResistance = 350
ch =
BridgeMode: Full
ExcitationSource: Internal
ExcitationVoltage: 2.5
NominalBridgeResistance: 350
Range: -0.063 to +0.063 VoltsPerVolt
6-5
6 Analog Input and Output
Name: empty
ID: 'ai1'
Device: [1x1 daq.ni.CompactDAQModule]
MeasurementType: 'Bridge'
ADCTimingMode: HighSpeed
data = read(d,seconds(1),"OutputFormat","Matrix")
plot(data)
See Also
Related Examples
• “Acquire Data in the Foreground” on page 6-2
• “Acquire Data in the Background with Live Plot Updates” on page 6-4
6-6
Acquire Sound Pressure Data
Create a DataAcquisition object, and add an analog input channel with Microphone measurement
type:
d = daq('ni');
ch = addAnalogInputChannel(d,"cDAQ1Mod3",0,"Microphone");
ch.Sensitivity = 0.037
ch =
Sensitivity: 0.037
MaxSoundPressureLevel: 136
ExcitationCurrent: 0.002
ExcitationSource: Internal
Coupling: AC
TerminalConfig: PseudoDifferential
Range: -135 to +135 Pascals
Name: ''
ID: 'ai0'
Device: [1x1 daq.ni.CompactDAQModule]
MeasurementType: 'Microphone'
ADCTimingMode: ''
ch.MaxSoundPressureLevel = 100
ch =
Sensitivity: 0.037
MaxSoundPressureLevel: 100
ExcitationCurrent: 0.002
ExcitationSource: Internal
Coupling: AC
TerminalConfig: PseudoDifferential
Range: -135 to +135 Pascals
Name: ''
ID: 'ai0'
Device: [1x1 daq.ni.CompactDAQModule]
MeasurementType: 'Microphone'
ADCTimingMode: ''
[data,time] = read(d,seconds(4),"OutputFormat","Matrix");
plot(time,data)
6-7
6 Analog Input and Output
See Also
Related Examples
• “Acquire Data in the Foreground” on page 6-2
• “Acquire Data in the Background with Live Plot Updates” on page 6-4
6-8
Acquire IEPE Data
Create a DataAcquisition object, and add an analog input channel with IEPE measurement type.
d = daq("ni");
ch = addinput(d,"cDAQ1Mod3",0,"IEPE");
ch.ExcitationCurrent = .004;
Acquire the data and the corresponding sample times, storing them in two vectors.
[data,time] = read(d,seconds(1.35),"OutputFormat","Matrix");
plot(time,data)
6-9
6 Analog Input and Output
See Also
Related Examples
• “Acquire Data in the Foreground” on page 6-2
• “Acquire Data in the Background with Live Plot Updates” on page 6-4
6-10
Generate Signals in the Foreground
d = daq("ni");
Change the scan rate of the DataAcquisition to generate 10,000 scans per second:
d.Rate = 10000
d =
Running: 0
Rate: 10000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
You can specify the channel ID on NI devices using a terminal name, like 'ao1', or a numeric
equivalent like 1.
Create the data to define the output signal being generated. The output scans of one channel are
defined by a column vector.
Generate the output signal. The output signal will have a duration of 0.22 seconds, based on the
length of the queued data and the specified scan rate. MATLAB waits for this foreground generation,
and returns when the generation is complete.
write(d,outputData)
See Also
Related Examples
• “Generate Signals in the Background” on page 6-13
6-11
6 Analog Input and Output
Create an NI DAtaAcquisition object and add two analog output voltage channels from cDAQ1Mod2:
d = daq("ni");
addoutput(d, "cDAQ1Mod2', 2:3, "Voltage");
Specify the channel ID on NI devices using a terminal name, like ao1, or a numeric equivalent like 1.
Create a set of 1000 scans of data to output for all channels. Each channel output data is defined by a
column in the 1000-by-3 data matrix.
outputData(:,1) = linspace(-1,1,1000)';
outputData(:,2) = linspace(-2,2,1000)';
outputData(:,3) = linspace(0,0.02,1000)';
write(d,outputData);
See Also
Related Examples
• “Generate Signals in the Foreground” on page 6-11
• “Generate Signals in the Background” on page 6-13
6-12
Generate Signals in the Background
Create an NI DataAcquisition object and add an analog output voltage channel from cDAQ1Mod2:
d = daq("ni");
addoutput(d,"cDAQ1Mod2","ao0","Voltage");
Specify the channel ID on NI devices using a terminal name, like 'ao1', or a numeric equivalent like
1.
outputData = (linspace(-1,1,5000)');
preload(d,outputData);
start(d);
You can execute other MATLAB commands while the generation is in progress. In this example, call
pause, which causes the MATLAB command line to wait for you to press any key.
pause
See Also
Related Examples
• “Generate Signals in the Foreground” on page 6-11
6-13
6 Analog Input and Output
A callback function is configured to run when a certain number of scans are required.
Create an NI DataAcquisition object and add an analog output voltage channel on cDAQ1Mod2:
d = daq("ni");
addoutput(d,"cDAQ1Mod2","ao0","Voltage");
Specify the channel ID on NI devices using a terminal name, like 'ao1', or a numeric equivalent like
1.
preload(d,linspace(1,10,1000)');
Create a simple callback function to load data 1000 samples at a time. Save the function file as
loadMoreData.m in your working folder:
function loadMoreData(obj,evt)
% obj is the DataAcquisition object passed in. evt is not used.
write(obj,linspace(1,10,1000)');
end
d.ScansRequiredFcn = @loadMoreData;
This callback is executed whenever the number of queued scans falls below the threshold defined by
the property ScansRequiredFcnCount. The default threshold is defined at 0.5 seconds of data at
the default scan rate. In other words, with a default Rate at 1000 scans per second, the default
ScansRequiredFcnCount value is 500. As your device generates an output signal, when the queued
data falls below 500 scans, it triggers the ScansRequiredFcn.
d.ScansRequiredFcnCount
ans =
500
start(d,"Continuous")
You can execute other MATLAB commands while the generation is in progress. In this example, issue
a pause, which causes the MATLAB command line to wait for you to press any key.
pause
Tip If you want to continuously generate a repeating or periodic output, preload the waveform data,
and use
6-14
Generate Signals in the Background Continuously
start(d,"RepeatOutput")
See Also
Related Examples
• “Generate Signals in the Background” on page 6-13
6-15
6 Analog Input and Output
You can acquire data and generate signals at the same time, on devices on the same chassis. When
the DataAcquisition contains output channels, the duration of a finite generation and acquisition
depends on the number of scans and the scan rate.
Create an NI DataAcquisition object and add one analog input channel on cDAQ1Mod1 and one analog
output channel on cDAQ1Mod2:
d = daq("ni");
addinput(d,"cDAQ1Mod1","ai0","Voltage");
addoutput(d,"cDAQ1Mod2","ao0","Voltage");
d.Channels
ans =
outData = linspace(-1,10,2500)';
The generated output signal of 2500 scans will run for 2.5 seconds at a scan rate of 1000 samples per
second.
inData = readwrite(d,outData,"OutputFormat","Matrix");
plot(inData)
See Also
Related Examples
• “Generate Signals in the Foreground” on page 6-11
• “Generate Signals in the Background” on page 6-13
• “Acquire Data in the Foreground” on page 6-2
• “Acquire Data in the Background with Live Plot Updates” on page 6-4
6-16
Acquire Data with Analog Input Recorder
To open the Analog Input Recorder, on the MATLAB Toolstrip, on the Apps tab, in the Test and
Measurement section, click Analog Input Recorder.
Upon opening, the Analog Input Recorder attempts to find all your attached analog and audio input
devices.
Note Opening the Analog Input Recorder deletes all your existing DataAcquisition interfaces in
MATLAB.
The DataAcquisition interface created by the Analog Input Recorder is not accessible from the
MATLAB command line.
If you plug in a device while the app is open, you must refresh the listing for access to that device. On
the Devices tab, click Refresh. Use the same procedure to remove a device from the listing after
unplugging it.
Select the device you want to use in the Device List. The app immediately starts a preview of the
analog input using default settings.
6-17
6 Analog Input and Output
Modify any scan and channel settings for your specific needs. The following image shows the app
displaying three channels of the device. Notice that the Max Rate value has changed with the
number of channels; this relationship depends on the device.
6-18
Acquire Data with Analog Input Recorder
Check Continuous if you want to override the duration or number of scans. In this mode, recording
continues until you explicitly stop it.
When recording is complete, either because the specified number of scans is recorded or you click
Stop, the recorded data is assigned to the indicated MATLAB Workspace variable. By default, the
variable starts as DAQ_1, and its name is incremented with every recording, but you can specify any
valid MATLAB variable name not already in use. The variable is assigned an M-by-N timetable, where
M table rows is the number of scans and N columns is the number of channels.
The following commands show the beginning of the acquired timetable for a multiple channel
recording.
whos
ans =
4×3 timetable
6-19
6 Analog Input and Output
The timestamp elements of the table are relative to the first scan. The absolute time of the first scan
is available in the timetable TriggerTime custom property. For example,
DAQ_1.Properties.CustomProperties.TriggerTime
datetime
19-Nov-2019 15:21:01.239
In the Analog Input Recorder, click Generate Script for the app to open the MATLAB editor and
display the equivalent code for recording data. The following code is generated for the finite (non-
continuous) 3-channel recording of this example.
See Also
Apps
Analog Input Recorder | Analog Output Generator
More About
• “Generate Signals with Analog Output Generator” on page 6-21
• “Timetables”
6-20
Generate Signals with Analog Output Generator
To open the Analog Output Generator, on the MATLAB Toolstrip, on the Apps tab, in the Test and
Measurement section, click Analog Output Generator.
Upon opening, the Analog Output Generator attempts to find all your attached analog and audio
output devices.
Note Opening the Analog Output Generator deletes all your existing DataAcquisition interfaces in
MATLAB.
The DataAcquisition interface created by the Analog Output Generator is not accessible from the
MATLAB command line.
If you plug in a device while the app is open, you must refresh the listing for access to that device. On
the Devices tab, click Refresh. Use the same procedure to remove a device from the listing after
unplugging it.
Select the device you want to use in the Device List. By default, the app immediately displays a
preview of a test signal.
Use the following steps to produce an audio output of the "Hallelujah" chorus from Handel's Messiah.
1 Select the device for your output. This might be the primary sound driver, speakers, or a headset.
2 Load the sound data into the workspace with the following command in MATLAB:
load handel
This loads two variables into your workspace. The sound data is contained in array named y. The
sampling rate is contained in the variable Fs. You will need to know the sampling rate, so display
its value.
Fs
8192
3 In the Signal Type section of the Analog Output Generator toolstrip, select Workspace
Variable. In the adjacent selection list, choose y. This indicates the source of the data for the
generator to output.
4 Enter the Fs value of 8192 in the Rate text box in the Analog Output Generator. This indicates
the sampling rate. The app should now look something like this.
6-21
6 Analog Input and Output
If you were successful in producing a sound output, try experimenting with some of the settings in
the app. For example, modify the Rate value or the Number of Cycles.
Tip If you could not hear any sound, use the Test Signal option to generate a constant tone. Check
all your hardware connections and different devices in the app until you hear the tone.
In the Analog Output Generator, click Generate Script for the app to open the MATLAB Editor
and display the code for producing the signal. The code is generated for the finite (non-continuous)
output of this example.
6-22
Generate Signals with Analog Output Generator
See Also
Apps
Analog Input Recorder | Analog Output Generator
More About
• “Acquire Data with Analog Input Recorder” on page 6-17
6-23
7
Data Acquisition Toolbox supports the Analog Devices ADALM1000 active learning module.
ADALM1000 is an inexpensive evaluation platform designed for learning the fundamentals of
electrical engineering. You can download associated teaching materials, reference designs, and lab
projects from the Analog Devices website.
The support package lets you perform the following tasks in MATLAB with the ADALM1000:
See Also
More About
• “Generate and Measure Signals with Analog Devices ADALM1000” on page 7-3
• “Analog Devices ADALM1000 Limitations” on page B-6
External Websites
• ADALM1000 Overview
7-2
Generate and Measure Signals with Analog Devices ADALM1000
dev = daqlist("adi")
dev =
1×4 table
dev{1,"DeviceInfo"}
7-3
7 Analog Devices Active Learning Module
d = daq("adi")
d =
Running: 0
Rate: 100000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: [100000 100000]
Add an analog input channel to measure current on the same device channel A.
addinput(d,"SMU1","A","Current");
R_load =
50.3005
Tip The ADALM1000 continues to generate the last value programmed until you release the
hardware. When you are finished with your signals, reset the device to output 0 volts.
Generate a Pulse
This example shows how to generate a 1-millisecond, 5-volt pulse, surrounded on either side by 10
milliseconds at 0 volts.
pdata = zeros(2100,1); % Column vector of 2100 samples.
pdata (1001:1100) = 5; % Pulse in middle of vector.
d = daq("adi");
addoutput(d,"SMU1","B","Voltage");
7-4
Generate and Measure Signals with Analog Devices ADALM1000
write(d,pdata)
Generate Waveforms
This example shows how to simultaneously generate a 1-kHz square wave on channel A, and a 100 Hz
sine wave on channel B. Each output lasts for 5 seconds.
The example requires two DataAcquisition channels for device channels A and B, both as output
channels for voltage.
d = daq("adi");
addoutput(d,"SMU1","A","Voltage");
addoutput(d,"SMU1","B","Voltage");
d.Channels
ans =
Start the output signal generation. The 500000 scans at 100000 scans per second lasts for 5 seconds.
write(d,[Sq Sw])
See Also
Functions
daq | addinput | addoutput | read | write
More About
• “Analog Devices ADALM1000 Hardware” on page 7-2
• “Analog Devices ADALM1000 Limitations” on page B-6
External Websites
• ADALM1000 Overview
7-5
8
• Frequency
• Edges
• PWM
• Position
• Pulse generation
See Also
Related Examples
• “Acquire Counter Input Data” on page 8-3
• “Generate Pulse Data on a Counter Channel” on page 8-6
8-2
Acquire Counter Input Data
d = daq("ni");
Step 2. Add a counter input channel with an edge count measurement type.
ch = addinput(d,"cDAQ1Mod5","ctr0","EdgeCount")
ch =
Step 3. Change the channel ActiveEdge property to 'Falling' and view the channel properties to
see the change.
ch.ActiveEdge = 'Falling';
get(ch)
ActiveEdge: Falling
CountDirection: Increment
InitialCount: 0
Terminal: 'PFI0'
SampleTimingType: 10388
Name: 'cDAQ1Mod5_ctr0'
ID: 'ctr0'
Device: [1x1 daq.ni.DeviceInfo]
MeasurementType: 'EdgeCount'
count = read(d)
8-3
8 Counter Input and Output
count =
133
Step 5. Reset counters from the initial count and acquire an updated count value. This value is the
number of detections since resetting the counter.
resetcounters(d);
count = read(d)
count =
71
d = daq("ni");
addinput(d,"cDAQ1Mod5","ctr0","Frequency")
Index Type Device Channel Measurement Type Range Name
_____ ____ ___________ _______ ________________ _____ ________________
f = read(d,"OutputFormat","Matrix")
f =
9.5877e+003
d = daq("ni");
Step 2. Add a counter input channel with an edge count measurement type.
addinput(d,"cDAQ1Mod5","ctr0","EdgeCount")
Index Type Device Channel Measurement Type Range Name
_____ ____ ___________ _______ ________________ _____ ________________
8-4
Acquire Counter Input Data
The counter input channel requires an external clock to perform a foreground acquisition. If you do
not have an external clock, add an analog input channel from a clocked device on the same
CompactDAQ chassis to the DataAcquisition. This example uses an NI 9205 device on the same
chassis with the device ID cDAQ1Mod1. Alternatively, the analog input channel could be on the same
device as the counter channel.
addinput(d,"cDAQ1Mod1","ai1","Voltage");
Step 4. Acquire the data and assign it to the variable data, and plot the results.
data = read(d,seconds(1),"OutputFormat","Matrix");
plot(data)
The plot displays the results from both channels in the DataAcquisition:
8-5
8 Counter Input and Output
d = daq("ni");
Step 3. Configure the output counter channel properties for signal frequency and duty cycle.
ch.Frequency = 50000;
ch.DutyCycle = 0.25;
start(d,"Continuous")
stop(d)
See Also
More About
• “Synchronize Counter Outputs from Multiple Devices” on page 13-8
8-6
9
Digital Operations
Digital Channels
Digital subsystems transfer digital or logical values in bits via digital lines. You can perform clocked
and non-clocked digital operations using the DataAcquisition interface in the Data Acquisition
Toolbox.
Add lines of the digital subsystem as channels to your DataAcquisition using addinput, addoutput,
or addbidirectional. Digital channels can be:
With clocked operations, you can acquire or generate clocked signals at a specified scan rate for a
specified duration or number of scans. These operations use hardware timing to acquire or generate
at specific times. The operation is controlled by events tied to subsystem clocks. In a clocked
acquisition, data is transferred from the device to your system memory and displays when the event
calls for the data. In signal generation, data generated from the device is stored in memory until the
configured event occurs. When an event occurs, data is sent via the digital channels to the specified
devices.
Your device might or might not have an onboard clock. However, Data Acquisition Toolbox does not
support direct access to device onboard clocks for clocked sampling when using only digital input/
output channels with a DataAcquisition object. You can enable clocked operation by adding a clock in
one of these ways:
• Import a clock from an external source. See “Acquire Digital Data Using an External Clock” on
page 9-6 for more information.
• Generate a clock from a Counter Output subsystem in your DataAcquisition and import that clock.
See “Acquire Digital Data Using a Counter Output Channel as External Clock” on page 9-8 for
more information.
• Share a clock from the analog input subsystem. See “Acquire Digital Data Using a Shared Clock”
on page 9-5 for more information.
Find devices connected to your system and find the NI model USB-6509 device.
dev = daqlist("ni")
dev =
2×4 table
9-2
Digital Channels
View the subsystem information in the DeviceInfo for Dev2 using index 1.
DevInf = dev.DeviceInfo(1)
DevInf =
See Also
More About
• “Acquire Digital Data Using a Shared Clock” on page 9-5
• “Acquire Digital Data Using an External Clock” on page 9-6
9-3
9 Digital Operations
Discover NI devices connected to your system and find the ID for the NI 6255:
dev = daqlist("ni")
dev =
3×4 table
Create a DataAcquisition object and add two input lines from port 0 on Dev1:
d = daq("ni");
ch = addinput(d,"Dev1","Port0/Line0:1","Digital")
ch =
data = read(d,"OutputFormat","Matrix")
data =
1 0
9-4
Acquire Digital Data Using a Shared Clock
Create a DataAcquisition object and add a digital input line from port 0 line 0 on Dev1.
d = daq("ni");
addinput(d,"Dev1","Port0/Line0","Digital")
Note Not all devices support clocked digital I/O operations with hardware timing. For these devices
you can use software timed operations with single scan calls to read and write.
Devices that support clocked digital I/O operations might not support them on all ports. Check your
device specifications.
addinput(d,"Dev1",0,"Voltage");
d.Channels
ans =
Read and plot the acquired digital data. The device acquires digital data at the scan rate determined
by its analog subsystem.
dataIn = read(d,seconds(1),"OutputFormat","Matrix");
plot(dataIn(1:100,1)) % Column 1 is data from the first channel.
See Also
Related Examples
• “Acquire Digital Data Using an External Clock” on page 9-6
• “Acquire Digital Data Using a Counter Output Channel as External Clock” on page 9-8
More About
• “Synchronization” on page 13-2
9-5
9 Digital Operations
You can use a function generator or the on-board clock from a digital circuit. Here, a function
generator is physically wired to terminal PFI9 on device NI 6255.
Create a DataAcquisition object and add a output line at port 0 line 2 on Dev1.
d = daq("ni");
ch = addinput(d,"Dev1","Port0/Line2","Digital")
ch =
Note Not all devices support clocked digital I/O operations with hardware timing. For these devices
you can use software timed operations with single scan calls to read and write.
Devices that support clocked digital I/O operations might not support them on all ports. Check your
device specifications.
Set the rate of your DataAcquisition to the expected rate of your external scan clock.
d.Rate = 1000;
Note Importing an external clock does not automatically set the scan rate of your DataAcquisition.
Manually set the DataAcquisition Rate property value to match the expected external clock
frequency.
Programmatically add a scan clock to your DataAcquisition, indicating the source as external and the
target as device terminal PFI9.
clk = addclock(d,"ScanClock","External","Dev1/PFI9")
clk =
9-6
Acquire Digital Data Using an External Clock
Source: 'External'
Destination: 'Dev1/PFI9'
Type: ScanClock
dataIn = read(d,seconds(1),"OutputFormat","Matrix");
plot(dataIn(1:100,1))
See Also
Related Examples
• “Acquire Digital Data Using a Shared Clock” on page 9-5
• “Acquire Digital Data Using a Counter Output Channel as External Clock” on page 9-8
9-7
9 Digital Operations
In this example, you generate a clock in one DataAcquisition using a counter output channel and
export the clock to another DataAcquisition that acquires digital data. The counter output and the
digital subsystem can be on the same device or on different devices. If using multiple devices not in
the same chassis, you must wire a physical connection between the counter output of one device to
the digital clock input of the other.
Note Importing an external clock does not automatically set the scan rate of your DataAcquisition.
Manually set the DataAcquisition Rate property value to match the expected external clock
frequency.
Define the clock frequency to be used for synchronizing the scan rate of your counter output as well
as the rate of your digital acquisition.
clockFreq = 100;
Create a DataAcquisition object and add a counter output channel for PulseGeneration
measurement type.
daqClk = daq("ni");
ch1 = addoutput(daqClk,"Dev1","ctr0","PulseGeneration");
Tip Make sure the counter channel you add is not being used in a different DataAcquisition,
otherwise a terminal conflict error occurs.
9-8
Acquire Digital Data Using a Counter Output Channel as External Clock
Save the counter output terminal ID to a variable so you can use it later to specify the external clock
that synchronizes your digital clocked operations.
clkTerminal = ch1.Terminal;
ch1.Frequency = clockFreq;
Create a DataAcquisition and add a digital input line from port 0 line 2 on Dev1.
daqDgt = daq("ni");
addinput(daqDgt,"Dev1","Port0/Line2","Digital")
Note Not all devices support clocked digital I/O operations with hardware timing. For these devices
you can use software timed operations with single scan calls to read and write.
Devices that support clocked digital I/O operations might not support them on all ports. Check your
device specifications.
Tip PFI terminal resources might be shared. Check your device routing in the NI MAX app.
Set the DataAcquisition scan rate to the same value as the rate of the counter output channel.
daqDgt.Rate = clockFreq;
Import the clock from your clock DataAcquisition to synchronize your acquisition.
addclock(daqDgt,"ScanClock","External",clkTerminal)
start(daqClk,"Continuous")
Pulse generation begins immediately on the counter output. It does not need data.
dataIn = read(daqDgt,seconds(1),"OutputFormat","Matrix");
plot(dataIn(1:100,1))
9-9
9 Digital Operations
stop(daqClk)
See Also
Related Examples
• “Acquire Digital Data Using a Shared Clock” on page 9-5
• “Acquire Digital Data Using an External Clock” on page 9-6
9-10
Acquire Digital Data Using an External Clock via Chassis PFI Terminal
d = daq("ni");
addinput(d,"cDAQ2Mod3","Port0/Line0","Digital");
Add a clock specifying source and destination. Then set the DataAcquisition scan rate to match the
external clock frequency.
addclock(d,"ScanClock","External","cDAQ2/PFI0");
d.Rate = 100e3;
[data,timestamps] = read(d,seconds(1),"OutputFormat","Matrix");
plot(timestamps,data(1:100,1))
See Also
9-11
9 Digital Operations
Discover devices connected to your system and find the ID for the NI 6255.
dev = daqlist
dev =
3×4 table
Create a DataAcquisition and add four digital input lines from port 0 on Dev1.
d = daq("ni");
addinput(d,"Dev1","Port0/Line0:3","Digital");
d.Channels
ans =
hData = binaryVectorToHex(read(d,"OutputFormat","Matrix"))
hData =
'C'
9-12
Generate Non-Clocked Digital Data
Discover NI devices connected to your system and find the ID for the NI 6255.
d = daqlist("ni")
dev =
3×4 table
Create a DataAcquisition object and add two digital output lines from port 0 on Dev1.
d = daq("ni");
addoutput(d,"Dev1","Port0/Line0:1","Digital");
d.Channels
ans =
write(d,[1 0])
9-13
9 Digital Operations
Discover NI devices connected to your system and find the ID for the NI 6255.
d = daqlist("ni")
dev =
3×4 table
Create a DataAcquisition and add two digital output lines from port 0 on Dev1.
d = daq("ni");
addoutput(d,"Dev1","Port0/Line0:1","Digital");
d.Channels
ans =
Convert the decimal number 2 to a binary vector, and generate that digital output value on the two
lines.
write(d,decimalToBinaryVector(2))
9-14
Generate and Acquire Data on Bidirectional Channels
Discover NI devices connected to your system and find the ID for the NI 6255.
d = daqlist("ni")
dev =
3×4 table
Create a DataAcquisition and add two lines from port 0 and 2 lines from port 1 on Dev1.
d = daq("ni");
addbidirectional(d,"Dev1","Port0/Line0:1","Digital");
addbidirectional(d,"Dev1","Port1/Line0:1","Digital");
d.Channels
ans =
set(d.Channels,"Direction","Output");
write(d,[1 0 1 0])
set(d.Channels,"Direction","Input");
read(d,"OutputFormat","Matrix")
ans =
1 0 1 0
9-15
9 Digital Operations
Discover NI devices connected to your system and find the ID for the NI 6255.
d = daqlist("ni")
dev =
3×4 table
Create a DataAcquisition and add two digital output lines from port 0 on Dev1.
d = daq("ni");
addoutput(d,"Dev1","Port0/Line0:1","Digital")
Add an analog output channel from Dev1, then view all channels.
addoutput(d,'Dev1',0,'Voltage')
d.Channels
ans =
Output a single scan of data on both the digital and analog channels.
9-16
10
Multichannel Audio
10 Multichannel Audio
Data Acquisition Toolbox does not read directly from or write directly to audio files using the
multichannel audio feature. Instead, use the MATLAB functions audioread and audiowrite.
Discover DirectSound audio devices installed on your system and create a DataAcquisition for these
devices.
dev = daqlist;
dev =
4×4 table
"Audio0" "DirectSound Primary Sound Capture Driver" "Primary Sound Capture Driver" [1×1 daq.audio.Devic
"Audio1" "DirectSound Headset Microphone (Plantronics BT600)" "Headset Microphone (Plantronics BT600)" [1×1 daq.audio.Devic
"Audio2" "DirectSound Primary Sound Driver" "Primary Sound Driver" [1×1 daq.audio.Devic
"Audio3" "DirectSound Headset Earphone (Plantronics BT600)" "Headset Earphone (Plantronics BT600)" [1×1 daq.audio.Devic
d = daq("directsound")
d =
10-2
Audio Input and Output
Running: 0
Rate: 44100
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Add an audio input channel for the microphone with id Audio1. The measurement type is Audio.
addinput(d,"Audio1",1,"Audio");
ch =
Acquire 7 seconds of data in the foreground and plot the data versus time.
10-3
10 Multichannel Audio
See Also
Related Examples
• “Generate Audio Signals” on page 18-86
10-4
11
The Data Acquisition Toolbox Support Package for Digilent Analog Discovery hardware lets you
perform the following tasks in MATLAB:
See Also
Related Examples
• “Getting Started Acquiring Data with Digilent Analog Discovery” on page 18-68
• “Getting Started Generating Data with Digilent Analog Discovery” on page 18-71
More About
• “Install Hardware Support Package for Vendor Support” on page 5-2
11-2
Digilent Function Waveform Generator Channels
To test the Analog Discovery device, create the following connection to acquire the generated
waveform, and use it with the corresponding code:
11-3
11 Waveform Function Generation
Unlike analog input channels, the waveform generator channels control their own frequency. If your
DataAcquisition contains both waveform generator channels and any other type of acquisition
channels, the waveform generator channels will have their own frequency and all other channels will
inherit the DataAcquisition scan rate. If you have analog input channels in the DataAcquisition with
waveform generator channels, the analog input channels start first and act as a trigger for the
waveform generator channels.
See Also
Related Examples
• “Generate Standard Periodic Waveforms Using Digilent Analog Discovery” on page 18-76
• “Generate Arbitrary Periodic Waveforms Using Digilent Analog Discovery” on page 18-79
More About
• “Waveform Types” on page 11-5
11-4
Waveform Types
Waveform Types
Digilent Analog Discovery devices support generation of arbitrary waveforms, standard waveforms,
or both. If your device supports standard waveforms, you can set the gain, offset, and frequency to
control the output. Standard waveform types include:
• Sine
• Square
• Triangle
• RampUp
• RampDown
• DC
You can control the behavior of different waveform types using the associated properties. This table
shows you which properties work with the supported waveform types for Digilent devices.
This diagram illustrates how these properties affect a standard square waveform.
11-5
11 Waveform Function Generation
11-6
Waveform Types
Standard waveforms cannot be clipped. You must keep gain and offset values so that the waveform
amplitude remains within voltage range. You cannot change gain and offset of arbitrary waveforms.
See Also
Related Examples
• “Generate Standard Periodic Waveforms Using Digilent Analog Discovery” on page 18-76
• “Generate Arbitrary Periodic Waveforms Using Digilent Analog Discovery” on page 18-79
More About
• “Digilent Function Waveform Generator Channels” on page 11-3
11-7
11 Waveform Function Generation
dev =
1×4 table
"AD1" "Digilent Inc. Analog Discovery 2 Kit Rev. C" "Analog Discovery 2" [1×1 daq.di.DeviceInfo]
d = daq("digilent")
d =
Running: 0
Rate: 10000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Add a waveform function generator channel for device AD1 with a Sine waveform type.
fgenCh = addoutput(d,"AD1",1,"Sine")
fgenCh =
Set the channel amplitude to 5 v using the Gain property and the channel frequency to 100 kHz.
fgenCh.Gain = 5;
fgenCh.Frequency = 100e3;
Specify the output duration to run for 5 seconds and start the generation.
write(d,seconds(5))
See Also
Related Examples
• “Generate Standard Periodic Waveforms Using Digilent Analog Discovery” on page 18-76
• “Generate Arbitrary Periodic Waveforms Using Digilent Analog Discovery” on page 18-79
11-8
12
Trigger Connections
In this section...
“When to Use Triggers” on page 12-2
“External Triggering” on page 12-2
Note You can have multiple destinations for your trigger, but only one source.
Note You cannot use trigger and clock connections with audio channels.
External Triggering
You can configure devices in a DataAcquisition to receive an external trigger. To use an external
trigger source, your connection parameters must correctly specify the exact device and terminal
pairs to which the external source is connected. Two circumstances of externally clocked and
triggered synchronization are:
12-2
Trigger Connections
• An external hardware event that controls the operation of one or more devices in a
DataAcquisition object. For example, opening and closing a switch starts a background acquisition
on a DataAcquisition.
• An external hardware event synchronizes multiple devices in a DataAcquisition. For example,
opening and closing of a switch starts a background operation across multiple devices or
CompactDAQ chassis in a DataAcquisition.
See Also
Related Examples
• “Multiple-Device Synchronization Using USB or PXI Devices” on page 13-7
• “Multiple-Chassis Synchronization with CompactDAQ Devices” on page 13-12
• “Acquire Voltage Data Using a Digital Trigger” on page 12-4
More About
• “Synchronization” on page 13-2
12-3
12 Triggers and Clocks
d = daq("ni");
addinput(d,"Dev1",0,"Voltage")
Physically connect the switch to terminal PFI0 on NI USB-6211. The trigger comes from the switch,
which is an external source. Programmatically add the trigger to the DataAcquisition, indicating
source, destination, and device PFI terminal.
t = addtrigger(d,"Digital","StartTrigger","External","Dev1/PFI0")
t =
Source: 'External'
Destination: 'Dev1/PFI0'
Type: StartTrigger
Condition: 'RisingEdge'
t.Condition = 'FallingEdge';
Acquire data and store it in dataIn. The DataAcquisition waits for the trigger to occur, and starts
acquiring data when the switch closes.
dataIn = read(d,seconds(1),"OutputFormat","Matrix");
See Also
Related Examples
• “Multiple-Device Synchronization Using USB or PXI Devices” on page 13-7
• “Multiple-Chassis Synchronization with CompactDAQ Devices” on page 13-12
More About
• “Synchronization” on page 13-2
• “Trigger Connections” on page 12-2
12-4
Clock Connections
Clock Connections
In this section...
“When to Use Clocks” on page 12-5
“Import Scan Clock from External Source” on page 12-5
“Export Scan Clock to External System” on page 12-5
Note You cannot use trigger and clock connections with audio channels.
• Synchronizing operations on all devices within a DataAcquisition by sharing the clock on a device
within the DataAcquisition or an external clock
• Synchronizing operations on all devices within a DataAcquisition and some external devices, by
sharing an external clock
Note Importing an external clock does not automatically set the scan rate of your DataAcquisition.
Manually set the DataAcquisition Rate property value to match the expected external clock
frequency.
Create a DataAcquisition and add a voltage input channel from an NI USB-6211 with device ID Dev1.
d = daq("ni");
addinput(d,"Dev1",0,"Voltage")
Add a clock to the DataAcquisition, to export an external scan clock sourced at terminal PFI6 on
Dev1, and physically connect it to an external destination.
c = addclock(d,"ScanClock","Dev1/PFI6","External")
12-5
12 Triggers and Clocks
c =
Source: 'Dev1/PFI6'
Destination: 'External'
Type: ScanClock
dataIn = read(d,seconds(1),"OutputFormat","Matrix");
See Also
Related Examples
• “Multiple-Device Synchronization Using USB or PXI Devices” on page 13-7
• “Multiple-Chassis Synchronization with CompactDAQ Devices” on page 13-12
More About
• “Synchronization” on page 13-2
12-6
13
Synchronization
Synchronization
Synchronization of data acquisition operations between multiple channels or devices has two aspects:
Synchronization can involve the coordination of triggering, clocking, or both. To synchronize the start
of operations on multiple channels or devices, they must use a shared start trigger. To synchronize
the clocked scanning operations on multiple channels or devices, they must use a shared scan clock.
• Multiple subsystems in a device (analog input, analog output, counter input, etc.)
• Multiple devices
• Multiple CompactDAQ or PXI chassis
Note Counter output channels run independently and are unaffected by synchronization connections.
13-2
Synchronization
• Devices in a DataAcquisition connected to a start trigger or scan clock source on another device in
the DataAcquisition
• Devices and chassis in a DataAcquisition connected to a start trigger or scan clock source on
another device in the DataAcquisition
13-3
13 Synchronization
A source device and terminal pair generates the synchronization signal and is connected to the
destination device and terminal pairs. You must physically connect the source and destination
terminals, unless they are internally connected. Check your device specifications for more
information. Synchronization connections are added from the source device to one or more
destination devices.
• The source device provides the start trigger or scan clock signals.
• The destination device receives a start trigger or scan clock signal.
For example, if you determine that a terminal on Dev1 will provide a start trigger and a terminal on
Dev2 will receive that trigger, then Dev1 becomes your source device and Dev2 your destination
device. You can have multiple destinations for your trigger and clock connections, but only one
source.
Use addtrigger to add start trigger connections, and addclock to add a scan clock connection to
your DataAcquisition.
Automatic Synchronization
In most cases, a DataAcquisition automatically starts all its devices at the same time when you start
an operation. You must configure them to start synchronously when devices are not on a single
chassis and do not share a clock. If you have not configured synchronization on such devices, the
start operation reduces the latency between devices, running them very close together to achieve
near-simultaneous signals. However, devices are automatically and perfectly synchronized in the
DataAcquisition if they are:
• Subsystems on a single device in the DataAcquisition. This synchronizes your analog input, analog
output, and counter input channels.
Note Counter output channels run independently and are unaffected by synchronization
connections.
• Modules on a single CompactDAQ chassis in the DataAcquisition.
• PXI modules synchronized with a reference clock on a PXI chassis. For perfect synchronization,
you must share a trigger as well. See “Acquire Synchronized Data Using PXI Devices” on page 13-
9 for more information.
Synchronization Scenarios
You must employ different techniques for synchronization, depending on the configurations of your
channels, devices, and chassis. The following sections describe these different scenarios.
In this topic, hardware that performs the signal conversion when not plugged into a chassis is
referred to as a device; this includes USB devices. When the conversion hardware is a card plugged
into a chassis, it is usually referred to as a module.
Data Acquisition Toolbox DataAcquisition software is based on the assumption that all channels of the
same acquisition device or module use the same internal scan clock and start trigger. As such, these
channels meet the requirements for perfect synchronization. For most vendors, this includes digital
channels, analog channels, and counter input channels, but does not include counter output channels.
13-4
Synchronization
The following topics illustrate this scenario, providing automatic synchronization between multiple
channels.
• “Acquire Data from Multiple Channels using an MCC Device” on page 18-22
• “Acquiring and Generating Data at the Same Time with Digilent Analog Discovery” on page 18-73
Exceptions: Some devices do not support setting the source of the start trigger or do not internally
route start trigger signals between subsystems. These include National Instruments myDAQ and
USB-6002. In such devices, only channels of the same subsystem support start trigger
synchronization by default.
Modules in the same CompactDAQ chassis use the chassis scan clock and start trigger. The Data
Acquisition Toolbox DataAcquisition interface configures the chassis scan clock rate and issues the
start trigger signal. The chassis in turn provides synchronized signals to its modules.
The following examples illustrate this scenario, providing synchronization between multiple modules
in the same chassis without external connections or extra programming.
Exceptions: Some CompactDAQ modules have their own onboard clocks, for example, DSA modules.
Modules in a PXI chassis share a common scan clock, but a Data Acquisition Toolbox DataAcquisition
does not synchronize the start trigger for multiple modules in the chassis by default. The start
triggers of multiple DSA modules can be synchronized using the AutoSyncDSA property, while other
PXI modules require an external trigger connection for start trigger synchronization.
The following topics illustrate these scenarios, showing how to synchronize start triggers on multiple
modules.
This scenario represents multiple devices or modules in their most independent configuration. The
configuration could be multiple USB devices, for example, or modules in separate chassis. Neither
the start triggers nor the scan clocks of these devices are synchronized by default.
The following topics illustrates these scenarios, showing how to synchronize start triggers and scan
clocks on multiple devices without chassis or in different chassis, by way of an external connection.
13-5
13 Synchronization
See Also
More About
• “Multiple-Device Synchronization Using USB or PXI Devices” on page 13-7
• “Synchronize DSA Devices” on page 13-13
13-6
Multiple-Device Synchronization Using USB or PXI Devices
Requirement You must register your RTSI cable using the National Instruments Measurement &
Automation Explorer.
Create a DataAcquisition and add one voltage input channel from each device:
d = daq("ni");
addinput(d,"Dev1",0,"Voltage")
addinput(d,"Dev2",0,"Voltage")
addinput(d,"Dev3",0,"Voltage")
Choose terminal PFI4 on Dev1 as the start trigger source. Connect the trigger source to the
destination terminals PFI0 on Dev2 and PFI0 on Dev3.
addtrigger(d,"Digital","StartTrigger","Dev1/PFI4","Dev2/PFI0")
addtrigger(d,"Digital","StartTrigger","Dev1/PFI4","Dev3/PFI0")
Choose terminal PFI5 on Dev1 as the scan clock source. Connect it to destination terminals PFI1 on
Dev2, and PFI1 on Dev3.
addclock(d,"ScanClock","Dev1/PFI5","Dev2/PFI1")
addclock(d,"ScanClock","Dev1/PFI5","Dev3/PFI1")
dataIn = read(d,350,"OutputFormat","Matrix");
plot(dataIn)
13-7
13 Synchronization
All channels are connected to the same function generator, so the plot displays overlapping signals,
indicating synchronization.
This example uses two USB or PCI devices, but could be modified for channels across CompactDAQ
or PXI chassis. If you have counter output CompactDAQ modules in the same chassis, it is not
necessary to call addtrigger; but it is required for multiple modules in the same PXI chassis.
Create a DataAcquisition and add one voltage analog input channel from each of the two PXI devices
d = daq("ni");
addinput(d,"PXI1Slot2",0,"Voltage")
addinput(d,"PXI1Slot3",0,"Voltage")
13-8
Multiple-Device Synchronization Using USB or PXI Devices
[data,time] = read(d,seconds(1),"OutputFormat","Matrix");
plot(time,data)
d.AutoSyncDSA = true;
[data,time] = read(d,seconds(1),"OutputFormat","Matrix");
plot(time,data)
Create a DataAcquisition and add one voltage input channel from each NI-PXI 4461 device with IDs
PXI1Slot2 and PXI1Slot3.
d = daq("ni");
addinput(d,"PXI1Slot2",0,"Voltage")
addinput(d,"PXI1Slot3",0,"Voltage")
Add a start trigger connection to terminal PXI_Trig0 on PXI1Slot2 and connect it to terminal
PXI_Trig0 on PXI1Slot3. PXI cards are connected through the chassis backplane, so you do not
have to wire them physically.
addtrigger(d,"Digital","StartTrigger","PXI1Slot2/PXI_Trig0","PXI1Slot3/PXI_Trig0")
dataIn = read(d,seconds(1),"OutputFormat","Matrix");
plot(dataIn)
13-9
13 Synchronization
All channels are connected to the same function generator and have a shared reference clock. The
signals overlap, indicating synchronization.
See Also
More About
• “Multiple-Chassis Synchronization with CompactDAQ Devices” on page 13-12
• “Generate Pulse Data on a Counter Channel” on page 8-6
13-10
Synchronize with PFI on CompactDAQ Chassis Without Terminals
Some CompactDAQ chassis (e.g., NI 9174 and 9172) do not support built-in triggers, because they do
not have external BNC PFI connectors on the chassis itself. However, the PFI pins for these chassis
can be accessed through a digital module such as the NI 9402.
d = daq("ni");
addinput(d,"cDAQ2Mod4","ai0","Voltage")
addtrigger(d,"Digital","StartTrigger","External","cDAQ2Mod3/PFI0")
[data,timestamps] = read(d,seconds(1),"OutputFormat","Matrix");
plot(timestamps,data)
Use an external scan clock from a function generator providing a 100 kHz clock to terminal PFI1 on
NI 9402.
d = daq("ni");
addinput(d,"cDAQ2Mod3","Port0/Line2","Digital")
addclock(d,"ScanClock","External","cDAQ2Mod3/PFI1)
d.Rate = 100E+3;
[data,timestamps] = read(d,seconds(1),"OutputFormat","Matrix");
plot(timestamps,data);
Tip If you want your devices to run at multiple scan rates, use two separate DataAcquisition objects
with different scan rate settings.
See Also
See Also
Related Examples
• “Start a Multi-Trigger Acquisition on an External Event” on page 18-128
• “Acquire Data from Two Devices at Different Rates” on page 18-136
13-11
13 Synchronization
You can synchronize multiple CompactDAQ chassis in a DataAcquisition using one chassis to provide
clocking and triggering for all chassis in the DataAcquisition. Clock and trigger sources are attached
to terminals on the chassis, itself. All modules on the chassis as well as other connected devices, are
synchronized using these signals.
Create a DataAcquisition and add channels. Add one voltage input channel each from the two NI
9201 devices with IDs cDAQ1Mod1 and cDAQ2Mod1.
d = daq("ni");
addinput(d,"cDAQ1Mod1",0,"Voltage")
addinput(d,"cDAQ2Mod1",0,"Voltage")
Choose terminal PFI0 on cDAQ1 as your trigger source, and connect it to destination terminal PFI0
on cDAQ2. Make sure the wiring on the hardware runs between these two terminals. Note that you
are using the chassis and terminal pair here, not device and terminal pair.
addtrigger(d,"Digital","StartTrigger","cDAQ1/PFI0","cDAQ2/PFI0")
Choose terminal PFI1 on cDAQ1 as your clock source, and connect it to destination terminal PFI1 on
cDAQ2. Make sure the wiring on the hardware runs between these terminals.
addclock(d,"ScanClock","cDAQ1/PFI1","cDAQ2/PFI1")
dataIn = read(d,seconds(1),"OutputFormat","Matrix");
See Also
More About
• “Synchronize Counter Outputs from Multiple Devices” on page 13-8
13-12
Synchronize DSA Devices
The Digital Signal Analyzer (DSA) product family is designed to make highly accurate audio
frequency measurements. You can synchronize other PCI and PXI product families using “Trigger
Connections” on page 12-2 and “Clock Connections” on page 12-5. To synchronize PXI and PCI
families of DSA devices you need to use a sample clock with time-based synchronization or a
reference clock time-based synchronization. The DataAcquisition AutoSyncDSA property allows you
to automatically enable both homogeneous and heterogeneous synchronization between PCI and PXI
device families. The AutoSyncDSA property automatically configures all the necessary clocks,
triggers, and sync pulses needed to synchronize DSA devices in your DataAcquisition.
Hardware Restrictions
Before you synchronize, ensure that your device combinations adhere to these hardware restrictions:
Chassis restriction
You can synchronize these series using either a PXI or a PXIe chassis. Make sure all your modules
are on the same chassis.
Slot placement restriction
You can use any slot on the chassis that supports your module.
Chassis restriction
You can synchronize this series both homogeneously and heterogeneously only on a PXI chassis.
You can use them on a PXIe chassis to acquire unsynchronized data.
Slot placement restriction
On the PXI chassis, only the system timing slot can drive the trigger bus. Refer to your device
manual to find the system timing slot. This image shows the system timing slot on a PXIe 1062Q
chassis.
• Homogeneous synchronization: You can synchronize PXI 447x devices homogeneously if one
device is plugged into the system timing slot of a PXI chassis.
• Heterogeneous synchronization:
13-13
13 Synchronization
• You can synchronize a PXI 447x device with a PXI 446x device when the 446x is plugged
into the system timing slot of a PXI chassis.
• You cannot synchronize PXI 447x devices with PXI 449x devices.
• You cannot use hybrid-slot compatible 446x devices.
Note If you are synchronizing PCI devices make sure you register the RTSI cables in Measurement
and Automation Explorer. For more information, see the NI knowledge base article Real-Time System
Integration (RTSI) and Configuration Explained.
Create a DataAcquisition and add one voltage analog input channel from each of the two PCI devices
d = daq("ni");
addinput(d,"Dev1",0,"Voltage")
addinput(d,"Dev2",0,"Voltage")
13-14
Synchronize DSA Devices
This example shows how to account for filter delays when you use the same sine wave to acquire from
two different channels from two different PXI devices. Perfectly synchronized channels will show zero
phase lag between the two acquired signals.
Create a DataAcquisition and add two analog input channels with 'Voltage' measurement type,
from National Instruments PXI-4462 and NI PXI-4472.
d = daq("ni");
ch1 = addinput(d,"PXI1Slot2",0,"Voltage");
ch2 = addinput(d,"PXI1Slot3",0,"Voltage");
Use AutoSyncDSA to automatically configure the triggers, clocks, and sync pulses of the channels to
synchronize the devices:
d.AutoSyncDSA = true;
The data sheets for the NI PXI 4462 and PXI-4472 indicate a phase lag for each to be 63 and 38
samples, respectively, when the EnhancedAliasRejectionEnable property is disabled. Check to
make sure that this property is set to false or 0 on both channels:
ch1.EnhancedAliasRejectionEnable
ans =
ch2.EnhancedAliasRejectionEnable
ans =
13-15
13 Synchronization
Visually verify in the plotted data that the phase difference is 25 samples apart.
See Also
More About
• “Synchronize DSA PXI Devices Using AutoSyncDSA” on page 13-8
13-16
14
preload(d,outputSignal)
Start synchronous foreground Acquire input signal. Duration is an input argument to
operation that blocks MATLAB the read function.
s.DurationInSeconds = 5;
inData = startForeground(s); inData = read(d,seconds(5));
Generate output signal. Output data is provided directly to
the write function.
queueOutputData(s,outputSignal);
startForeground(s); write(d,signalData)
Generate and acquire signals Use readwrite for simultaneous
simultaneously. input and output.
queueOutputData(s,outputSignal);inData = readwrite(d,outputSignal);
inData = startForeground(s);
Start asynchronous background s.DurationInSeconds = 5; start(d,"Duration",seconds(5))
read operation that runs without startBackground(s) ⋮
blocking MATLAB inData = read(d,"all")
14-2
Transition Your Code from Session to DataAcquisition Interface
start(d,"Continuous")
Start continuous background write If data is preloaded, generation
lh = addlistener(s,'DataRequired',@queueMoreData);
operation s.IsContinuous = true; begins with the start function.
queueOutputData(s,outputSignal);
startBackground(s); d.ScansRequiredFcn = @writeMoreData;
preload(d,outputSignal);
⋮
start(d,"Continuous")
d.ScansRequiredFcn = @writeMoreData;
start(d,"Continuous")
⋮
write(d,outputSignal)
Configure callbacks listenDA = addlistener(s,'DataAvailable',@logData);
d.ScansAvailableFcn = @logData;
listenDR = addlistener(s,'DataRequired',@queueMoreData);
d.ScansRequiredFcn = @writeMoreData;
listenEO = addlistener(s,'ErrorOccurred',@handleError);
d.ErrorOccurredFcn = @handleError;
Specify external trigger addTriggerConnection... addtrigger(d,"Digital","StartTrigger","Ext
(s,'External','Dev3/PFI0','StartTrigger');
Specify input signal range ch = addAnalogInputChannel... ch = addinput(d,"Dev1","ai4","Voltage");
(s,'Dev1',1,'Voltage');
ch.Range = [-5 5];
ch.Range = [-5 5];
Using the session interface, you create a vendor session and add channels to the session. You can use
any device or chassis from the same vendor available to your system and can add a combination of
analog, digital, and counter input and output channels. All the channels operate together when you
start the session.
d = daq.getDevices
2 Create a session for National Instruments devices.
s = daq.createSession('ni');
3 Set the session scan rate to 8000.
s.Rate = 8000
4 Add an analog input channel for the device with ID Dev1 for voltage measurement, and then start
the acquisition.
addAnalogInputChannel(s,'Dev1',1,'Voltage');
startForeground(s);
14-3
14 Transition Your Code to New Interfaces
DataAcquisition Interface
devs = daqlist
2 Create a DataAcquisition for National Instruments devices.
d = daq("ni");
3 Set the DataAcquisition scan rate to 8000.
d.Rate = 8000
4 Add an analog input channel for the device with ID Dev1 for voltage measurement, and then
start the acquisition.
addinput(d,"Dev1","ai1","Voltage");
data = read(d,4000);
Use Triggers
Acquire analog data using hardware triggers.
Session Interface
You can specify an external event to trigger data acquisition using the session interface.
s = daq.createSession('ni');
ch = addAnalogInputChannel(s,'Dev1',0:1,'Voltage');
2 Configure the terminal and range of the channels in the session.
ch(1).TerminalConfig = 'SingleEnded';
ch(1).Range = [-10.0 10.0];
ch(2).TerminalConfig = 'SingleEnded';
ch(2).Range = [-10.0 10.0];
3 Create an external trigger connection and set the trigger to run one time.
addTriggerConnection(s,'External','Dev1/PFI0','StartTrigger');
s.Connections(1).TriggerCondition = 'RisingEdge';
s.TriggersPerRun = 1;
4 Set the rate and the duration of the acquisition.
s.Rate = 50000;
s.DurationInSeconds = 0.01;
5 Acquire data in the foreground and plot the data.
[data,timestamps] = startForeground(s);
plot(timestamps,data)
DataAcquisition Interface
14-4
Transition Your Code from Session to DataAcquisition Interface
d = daq("ni");
ch = addinput(d,"Dev1",0:1,"Voltage");
2 Configure the terminal configuration and range of the channels in the DataAcquisition.
ch(1).TerminalConfig = "SingleEnded";
ch(1).Range = [-10.0 10.0];
ch(2).TerminalConfig = "SingleEnded";
ch(2).Range = [-10.0 10.0];
3 Create an external trigger connection and set the trigger to run one time.
addtrigger(d,"Digital","StartTrigger","Dev1/PFI0","External");
d.DigitalTriggers(1).Condition = "RisingEdge";
d.NumDigitalTriggersPerRun = 1;
4 Set the scan rate of the acquisition.
d.Rate = 50000;
5 Acquire data in the foreground for 0.01 seconds and plot the data from all channels.
data = read(d,seconds(0.01));
plot(data.Time, data.Variables)
Session Interface
The session interface uses listeners and events to trigger certain actions. The
NotifyWhenDataAvailableExceeds property can fire a DataAvailable event. A listener defines
the operation to execute at that time.
s = daq.createSession('ni');
addAnalogInputChannel(s,'Dev1','ai0','Voltage');
2 Set the scan rate to 800,000 scans per second, which automatically sets the DataAvailable
notification to automatically fire 10 times per second.
s.Rate = 800000;
s.NotifyWhenDataAvailableExceeds
ans =
80000
3 Increase NotifyWhenDataAvailableExceeds to 160,000.
s.NotifyWhenDataAvailableExceeds = 160000;
4 Add a listener to determine the function to call when the event occurs.
L = addlistener(s,'DataAvailable', ...
@(src,event)readAndLogData(src));
14-5
14 Transition Your Code to New Interfaces
DataAcquisition Interface
The DataAcquisition interface uses callback functions that execute at occurrences determined by
certain properties. The ScansAvailableFcnCount property determines when to initiate the
callback function defined by ScansAvailableFcn.
d = daq("ni");
ch = addinput(d,"Dev1",1,"Voltage");
2 Set the scan rate to 800,000 scans per second, which automatically adjusts the
ScansAvailableFcnCount property.
d.Rate = 800000;
d.ScansAvailableFcnCount
80000
3 Increase ScansAvailableFcnCount to 160,000.
d.ScansAvailableFcnCount = 160000;
4 Identify a callback function for when the count occurs.
d.ScansAvailableFcn = @readAndLogData;
d = daq("ni");
%% Add Channels
% Add channels and set channel properties, if any.
addoutput(d,"Dev1","ao0","Voltage");
%% Set DataAcquisition Rate
% Set scan rate.
d.Rate = 250000;
%% Define Test Signal
% Create a test sine wave signal of specified peak-to-peak amplitude for each
% channel.
amplitudePeakToPeak_ch1 = 20;
sineFrequency = 10; % 10 Hz
totalDuration = 1; % 1 seconds
outputSignal = [];
outputSignal(:,1) = createSine(amplitudePeakToPeak_ch1/2, ...
sineFrequency, d.Rate, "bipolar", totalDuration);
outputSignal(end+1,:) = 0;
%% Generate Signal
% Write the signal data.
write(d,outputSignal);
%% Clean Up
% Clear all DataAcquisition and channel objects.
clear d outputSignal
%% Create Test Signal
14-6
Transition Your Code from Session to DataAcquisition Interface
numSamplesPerCycle = floor(sampleRate/f);
T = 1/f;
timestep = T/numSamplesPerCycle;
t = (0 : timestep : T-timestep)';
if type == "bipolar"
y = A*sin(2*pi*f*t);
elseif type == "unipolar"
y = A*sin(2*pi*f*t) + A;
end
numCycles = round(f*duration);
sine = repmat(y,numCycles,1);
end
s = daq.createSession('ni');
%% Set Session Properties
% Set properties that are not using default values.
s.Rate = 250000;
%% Add Channels to Session
% Add channels and set channel properties.
addAnalogOutputChannel(s,'Dev1','ao0','Voltage');
%% Define Test Signal
% Create a test sine wave signal of specified peak-to-peak amplitude for each
% channel.
amplitudePeakToPeak_ch1 = 20;
sineFrequency = 10; % 10 Hz
totalDuration = 1; % 1 seconds
queueOutputData(s,outputSignal);
%% Generate Signal
% Start foreground generation
startForeground(s);
%% Clean Up
% Clear the session and channels.
clear s outputSignal
%% Create Test Signal
% Helper function for creating test sine wave signal.
sampleRatePerCycle = floor(sampleRate/frequency);
period = 1/frequency;
s = period/sampleRatePerCycle;
t = (0 : s : period-s)';
if strcmpi(type, 'bipolar')
y = amplitude*sin(2*pi*frequency*t);
elseif strcmpi(type, 'unipolar')
y = amplitude*sin(2*pi*frequency*t) + amplitude;
end
numCycles = round(frequency*duration);
sine = repmat(y, numCycles, 1);
end
14-7
14 Transition Your Code to New Interfaces
The DataAcquisition interface is supported in R2020a and later. If you are using an earlier release,
use the session interface instead. For more information and examples of the session interface, see
Data Acquisition Toolbox Documentation (R2019b).
14-8
15
Functions
15 Functions
addbidirectional
Package: daq.interfaces
Syntax
addbidirectional(d,deviceID,channelID,"Digital")
ch = addbidirectional( ___ )
[ch,idx] = addbidirectional( ___ )
Description
addbidirectional(d,deviceID,channelID,"Digital") adds the digital bidirectional channel
channelID of device deviceID to the specified DataAcquisition interface, d.
[ch,idx] = addbidirectional( ___ ) adds the channel and also returns the channel index from
the DataAcquisition interface. The channel index reflects only the sequence in which channels are
added to the DataAcquisition; not to be confused with the device channel ID.
Examples
Add bidirectional digital channels to a DataAcquisition, and use indices to view their settings.
d = daq("ni");
ch1 = addbidirectional(d,"Dev1","port0/line0","Digital");
[ch2,idx2] = addbidirectional(d,"Dev1","port0/line1","Digital");
d.Channels
Index Type Device Channel Measurement Type Range Name
_____ _____ ______ _____________ _______________________ _____ __________________
d.Channels(idx2).ID
'port0/line1'
Input Arguments
d — DataAcquisition interface
DataAcquisition object
15-2
addbidirectional
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
deviceID — Device ID
character vector or string
Device ID specified as a character vector or string, as defined by the device vendor. Obtain the device
ID by calling daqlist.
Example: "Dev1"
Data Types: char | string
channelID — Channel ID
numeric value, character vector, or string
Channel ID specified as a numeric value, character vector, or string; often indicating the physical
location of the channel on the device. Supported values are specific to the vendor and device. You can
add multiple channels by specifying the channel ID as a numeric vector, or an array of character
vectors or strings. The index returned for this channel in the DataAcquisition display indicates the
position of this channel. This channel ID is not the same as channel index in the DataAcquisition: if
you add a channel with ID 2 as the first channel in a DataAcquisition, the DataAcquisition channel
index is 1.
Example: "port1/line1"
Data Types: char | string | numeric
Output Arguments
ch — Channel
Channel object
Device
Direction
ID
MeasurementType
Name
Channel index returned as a numeric value. With this index, you can access the array of the
DataAcquisition Channels property.
Version History
Introduced in R2020a
15-3
15 Functions
See Also
Functions
daqlist | daq | addinput | addoutput | removechannel
Properties
“Channel Properties” on page 4-7
15-4
addclock
addclock
Package: daq.interfaces
Syntax
addclock(d,"ScanClock",clkSrc,clkDest)
clk = addclock( ___ )
[clk,idx] = addclock( ___ )
Description
addclock(d,"ScanClock",clkSrc,clkDest) adds a clock connection to the DataAcquisition
interface for sharing, importing, or exporting a clock configuration. The created clock connection is
appended to the Clocks property of the DataAcquisition object.
clk = addclock( ___ ) adds the clock and returns the clock object.
[clk,idx] = addclock( ___ ) adds the clock and returns the clock object and the clock index
from the DataAcquisition interface.
Examples
d = daq("ni");
addinput(d,"Dev1","ai0","Voltage")
addinput(d,"Dev2","ai0","Voltage")
addclock(d,"ScanClock","Dev1/PFI0","Dev2/PFI0")
d = daq("ni");
addinput(d,"Dev1","ai0","Voltage")
addclock(d,"ScanClock","External","Dev1/PFI0")
d = daq("ni");
addinput(d,"Dev1","ai0","Voltage")
addclock(d,"ScanClock","Dev1/PFI0","External")
15-5
15 Functions
d = daq("ni");
addinput(d,"PXI1Slot5",0,"Voltage")
addclock(d,"ScanClock","External","PXI1Slot5/PXI_Star")
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Clock signal source, specified as a string or character vector indicating a device terminal, or
"external" when importing a clock from an external source.
Example: "external"
Data Types: char | string
Clock signal destination, specified as a string or character vector indicating a device terminal, or
"external" when exporting a clock to an external destination.
Example: "external"
Data Types: char | string
Output Arguments
clk — Clock
Clock object
Clock connection, returned as a Clock object with properties Source, Destination, and Type.
Clock index, returned as a numeric value. With this index, you can access the array of the
DataAcquisition Clocks property.
Version History
Introduced in R2020a
See Also
Functions
daq | removeclock
15-6
addinput
addinput
Package: daq.interfaces
Syntax
addinput(d,deviceID,channelID,measurementType)
ch = addinput( ___ )
[ch,idx] = addinput( ___ )
Description
addinput(d,deviceID,channelID,measurementType) adds the input channel channelID from
device deviceID to the specified DataAcquisition interface, d, configured for the specified
measurement type.
[ch,idx] = addinput( ___ ) adds the channel and also returns the channel index from the
DataAcquisition interface. The channel index indicates only the sequence in which channels are
added to the DataAcquisition; not to be confused with the device channel ID.
Examples
Add multiple input channels to a DataAcquisition, and use indices to view their settings.
d = daq('directsound');
ch1 = addinput(d,"Audio0","1","Audio");
[ch2,idx2] = addinput(d,"Audio1","1","Audio");
d.Channels
d.Channels(idx2).Range
Units: ''
15-7
15 Functions
Max: 1
Min: -1
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
deviceID — Device ID
character vector or string
Device ID specified as a character vector or string, as defined by the device vendor. Obtain the device
ID by calling daqlist.
Example: "Dev1"
Data Types: char | string
channelID — Channel ID
numeric value, character vector, or string
Channel ID specified as a numeric value, character vector, or string; often indicating the physical
location of the channel on the device. Supported values are specific to the vendor and device. You can
add multiple channels by specifying the channel ID as a numeric vector, or an array of character
vectors or strings. The index returned for this channel in the DataAcquisition display indicates the
position of this channel. This channel ID is not the same as channel index in the DataAcquisition: if
you add a channel with ID 2 as the first channel in a DataAcquisition, the DataAcquisition channel
index is 1.
Example: "ai2"
Data Types: char | string | numeric
15-8
addinput
Output Arguments
ch — Channel
channel object
Channel, returned as a channel object with properties depending on the measurement type as
described in “Channel Properties” on page 4-7.
Channel index, returned as a numeric value. With this index, you can access the array of the
DataAcquisition Channels property.
Version History
Introduced in R2020a
See Also
Functions
addoutput | daq | daqlist | addbidirectional | removechannel
Properties
“Channel Properties” on page 4-7
15-9
15 Functions
addoutput
Package: daq.interfaces
Syntax
addoutput(d,deviceID,channelID,measurementType)
ch = addoutput( ___ )
[ch,idx] = addoutput( ___ )
Description
addoutput(d,deviceID,channelID,measurementType) adds the output channel channelID of
device deviceID to the specified DataAcquisition interface, d, configured for the specified
measurement type.
[ch,idx] = addoutput( ___ ) adds the channel and also returns the channel index from the
DataAcquisition interface. The channel index reflects only the sequence in which channels are added
to the DataAcquisition; not to be confused with the device channel ID.
Examples
Add multiple channels to a DataAcquisition, and use indices to view their settings.
d = daq('directsound');
ch1 = addoutput(d,"Audio3","1","Audio");
[ch2,idx2] = addoutput(d,"Audio6","1","Audio");
d.Channels
Index Type Device Channel Measurement Type Range Name
_____ ______ ________ _______ ________________ ______________ __________
'AudioOutputChannel'
Input Arguments
d — DataAcquisition interface
DataAcquisition object
15-10
addoutput
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
deviceID — Device ID
character vector or string
Device ID specified as a character vector or string, as defined by the device vendor. Obtain the device
ID by calling daqlist.
Example: "Dev1"
Data Types: char | string
channelID — Channel ID
numeric value, character vector, or string
Channel ID specified as a numeric value, character vector, or string; often indicating the physical
location of the channel on the device. Supported values are specific to the vendor and device. You can
add multiple channels by specifying the channel ID as a numeric vector, or an array of character
vectors or strings. The index returned for this channel in the DataAcquisition display indicates the
position of this channel. This channel ID is not the same as channel index in the DataAcquisition: if
you add a channel with ID 2 as the first channel in a DataAcquisition, the DataAcquisition channel
index is 1.
Example: "ao2"
Data Types: char | string | numeric
15-11
15 Functions
Output Arguments
ch — Channel
channel object
Channel, returned as a channel object with properties depending on the measurement type as
described in “Channel Properties” on page 4-7.
Channel index, returned as a numeric value. With this index, you can access the array of the
DataAcquisition Channels property.
Version History
Introduced in R2020a
See Also
Functions
daqlist | daq | addinput | addbidirectional | removechannel
Properties
“Channel Properties” on page 4-7
15-12
addtrigger
addtrigger
Package: daq.interfaces
Syntax
addtrigger(d,"Digital","StartTrigger",trigSrc,trigDest)
trg = addtrigger( ___ )
[trg,idx] = addtrigger( ___ )
Description
addtrigger(d,"Digital","StartTrigger",trigSrc,trigDest) adds a trigger connection to
the DataAcquisition interface. The created connection is appended to the DigitalTriggers
property of the DataAcquisition object.
trg = addtrigger( ___ ) adds the trigger and returns the trigger object.
[trg,idx] = addtrigger( ___ ) adds the trigger and returns the trigger object and the trigger
index from the DataAcquisition interface.
Examples
d = daq("ni");
addinput(d,"Dev1","ai0","Voltage")
addinput(d,"Dev2","ai0","Voltage")
addtrigger(d,"Digital","StartTrigger","Dev1/PFI0","Dev2/PFI0")
d = daq("ni");
addinput(d,"Dev1","ai0","Voltage")
addtrigger(d,"Digital","StartTrigger","External","Dev1/PFI0")
d = daq("ni")
addinput(d,"Dev1","ai0","Voltage")
addtrigger(d,"Digital","StartTrigger","Dev1/PFI0","External")
15-13
15 Functions
d = daq("ni");
addinput(d,"PXI1Slot5",0,"Voltage")
addtrigger(d,"Digital","StartTrigger","External","PXI1Slot5/PXI_Trig0")
d = daq("ni");
addinput(d,"PXI1Slot5",0,"Voltage")
addtrigger(d,"Digital","StartTrigger","External","PXI1Slot5/PXI_Star")
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Trigger signal source, specified as a string or character vector indicating a device terminal, or
"external" when importing a terminal from an external source.
Example: "external"
Data Types: char | string
Trigger signal destination, specified as a string or character vector indicating a device terminal, or
"external" when exporting a trigger to an external destination.
Example: "external"
Data Types: char | string
Output Arguments
trg — Trigger
Trigger object
Trigger connection, returned as a trigger object, whose type and properties depend on the kind of
trigger. For example:
Source: 'External'
Destination: 'Dev4/PFI1'
Type: StartTrigger
Condition: 'RisingEdge'
15-14
addtrigger
Trigger index, returned as a numeric value. With this index, you can access the array of the
DataAcquisition DigitalTriggers property.
Version History
Introduced in R2020a
See Also
Functions
daq | removetrigger
Topics
“Synchronize NI PCI Devices Using RTSI” on page 18-125
“Start a Multi-Trigger Acquisition on an External Event” on page 18-128
“Acquire Data from Two Devices at Different Rates” on page 18-136
15-15
15 Functions
binaryVectorToDecimal
Convert binary vector value to decimal value
Syntax
decVal = binaryVectorToDecimal(binaryVector)
binaryVectorToDecimal(binaryVector,bitOrder)
Description
decVal = binaryVectorToDecimal(binaryVector) converts a binary vector to a decimal.
Examples
decVal =
decVal =
8
4
decVal =
1
2
15-16
binaryVectorToDecimal
decVal =
Input Arguments
binaryVector — Binary vector to convert to decimal
binary vectors
Binary vector to convert to a decimal, specified as a single binary vector or a row or column-based
array of binary vectors.
Bit order for the binary vector representation, specified as a character vector or string. Accepted
values are:
• 'MSBFirst' — The first element of the binary vector is the most significant bit.
• 'LSBFirst' — The first element of the binary vector is the least significant bit.
Output Arguments
decVal — Decimal value
double
Version History
Introduced in R2012b
See Also
Functions
hexToBinaryVector | decimalToBinaryVector | binaryVectorToHex
Topics
“Generate Digital Output Using Decimal Data Across Multiple Lines” on page 9-14
15-17
15 Functions
binaryVectorToHex
Convert binary vector value to hexadecimal
Syntax
hexVal = binaryVectorToHex(binaryVector)
hexVal = binaryVectorToHex(binaryVector,bitOrder)
Description
hexVal = binaryVectorToHex(binaryVector) converts the input binary vector to a
hexadecimal.
Examples
hexVal =
'3D'
hexVal =
{'C4'}
{'0A'}
The output is appended with 0s to make all hex values the same length character vectors.
hexVal =
'BC'
15-18
binaryVectorToHex
hexVal =
{'23'}
{'50'}
If necessary, the output is appended with 0s to make all hex values the same length character vectors.
Note The binary vector array is converted to a cell array of hexadecimal numbers. If you input a
single binary vector, it is converted to a hexadecimal character vector.
Input Arguments
binaryVector — Binary vector to convert to hexadecimal
numeric vector of 1s and 0s
Binary vector to convert to hexadecimal, specified as a numeric vector with 0s and 1s. The vector can
be a column or row vector.
Bit order for the binary vector representation, specified as a character vector or string. Accepted
values are:
• 'MSBFirst' — The first element of the binary vector is the most significant bit.
• 'LSBFirst' — The first element of the binary vector is the least significant bit.
Output Arguments
hexVal — Hexadecimal value
character vector
Hexadecimal value returned as a character vector. Multiple values are returned as a cell array of
character vectors.
Version History
Introduced in R2012b
See Also
Functions
hexToBinaryVector | binaryVectorToDecimal | decimalToBinaryVector
15-19
15 Functions
Topics
“Acquire Digital Data in Hexadecimal Values” on page 9-12
15-20
daq
daq
Package: daq.interfaces
Syntax
d = daq(vendor)
Description
d = daq(vendor) creates a DataAcquisition interface object for configuring and operating data
acquisition devices from the specified vendor.
Examples
Create a DataAcquisition
d = daq("directsound")
d =
Running: 0
Rate: 44100
NumScansAvailable: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
Input Arguments
vendor — Device vendor
"ni" | "adi" | "mcc" | "directsound" | "digilent"
15-21
15 Functions
Output Arguments
d — DataAcquisition interface
DataAcquisition object
Version History
Introduced in R2020a
See Also
Functions
daqvendorlist | daqlist | addinput | addoutput | addbidirectional | removechannel |
addclock | removeclock | addtrigger | removetrigger
Objects
DataAcquisition
15-22
daqhelp
daqhelp
Help for toolbox interface
Syntax
daqhelp
daqhelp(functionname)
helptext = daqhelp('functionname')
Description
daqhelp displays a comprehensive listing of Data Acquisition Toolbox functions along with a brief
description of each. Links in the output provide access to more detailed information.
daqhelp(functionname) returns help for the function specified as a character vector or string.
helptext = daqhelp('functionname') assigns the help text output to the variable out.
Examples
daqhelp
daqhelp("addinput")
Get help for a specified function, assigning the help text to a variable.
helptext = daqhelp("addinput");
Input Arguments
functionname — Function for which you want help
char vector or string
Function for which you want help, specified as a character vector or string.
Example: "addinput"
15-23
15 Functions
Output Arguments
helptext — Help text
char vector
Version History
Introduced before R2006a
15-24
daqlist
daqlist
List data acquisition devices available to toolbox
Syntax
daqlist
daqlist(vendor)
dev = daqlist( ___ )
Description
daqlist displays a table of all available devices for all supported vendors. The information for each
device includes device IDs, descriptions, models, and device subsystems.
daqlist(vendor) lists all available devices for the specified vendor in table format.
dev = daqlist( ___ ) assigns the device table to dev. You can access individual table cells by
indexing position or column labels.
Examples
dev = daqlist
dev =
12×5 table
dev = daqlist("ni")
dev =
15-25
15 Functions
12×5 table
devinfo = dev.DeviceInfo(1)
devinfo =
Digital IO supports:
Rates from 0.1 to 10000000.0 scans/sec
48 channels ('port0/line0' - 'port2/line7')
'InputOnly','OutputOnly','Bidirectional' measurement types
Input Arguments
vendor — Device vendor
"ni" | "adi" | "mcc" | "directsound" | "digilent"
Output Arguments
dev — Table of devices
table
Version History
Introduced in R2020a
15-26
daqlist
See Also
Functions
daqvendorlist | daq
15-27
15 Functions
daqreset
Reset Data Acquisition Toolbox
Syntax
daqreset
Description
daqreset resets Data Acquisition Toolbox and deletes all data acquisition objects.
Examples
d = daq("ni");
daqreset
d
d =
Version History
Introduced before R2006a
See Also
Functions
15-28
daqvendorlist
daqvendorlist
List vendors available to toolbox
Syntax
daqvendorlist
v = daqvendorlist
Description
daqvendorlist displays a list of supported vendors with information about adaptor versions, driver
versions, and operational status. Vendor support requires installation of the appropriate support
package. See “Data Acquisition Toolbox Supported Hardware”.
Examples
daqvendorlist
ans =
5×5 table
Output Arguments
v — Vendor information
table
Version History
Introduced in R2020a
15-29
15 Functions
See Also
Functions
daqlist | daq
15-30
DataAcquisition
DataAcquisition
Interface to data acquisition device
Description
The DataAcquisition object provides access to the devices of a specified vendor.
Creation
Use the daq function to create a DataAcquisition object.
Properties
AutoSyncDSA — Automatically Synchronize DSA devices
false (default) | true
Automatically Synchronize DSA devices, specified as a logical true or false. Use this property to
enable or disable automatic synchronization between DSA (PXI or PCI) devices in the same
DataAcquisition. By default automatic synchronization capability is disabled.
Example: true
Data Types: logical
Device channels, returned as an array of channel objects. Create channels with the functions
addinput, addoutput, and addbidirectional.
Example: addinput(d,…)
Device clock connections, returned as an array of clock objects. Create clocks with the addclock
function.
Example: addclock(d,…)
Device digital trigger connections, returned as an array of DigitalTrigger objects. Use the
addtigger function to add digital triggers to the DataAcquisition.
15-31
15 Functions
Example: addtrigger(d,…)
Time allowed for occurrence of digital trigger, specified as a numeric value in seconds or a duration.
Example: 30
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 |
duration
Number of data scans acquired in background operation since the last start, returned as a uint64
value. This value is reset each time start is called, and does not reflect whether the scans have been
read into MATLAB.
Example: 1000
Data Types: uint64
15-32
DataAcquisition
Number of data scans available for reading, returned as a uint64 value. These scans have been
acquired by the device input channels in a background operation, but have not yet been read into
MATLAB. The value decreases with each call to read; and is reset by a call to start.
Example: 1000
Data Types: uint64
Number of scans queued to the device output channels, returned as a uint64 value.
Example: 4000
Data Types: uint64
Lower and upper scan rate limits, returned as a 1-by-2 vector of doubles indicating minimum and
maximum allowed scan rates in samples per second. The scan rate limits depend on the hardware
and its configurations. In devices that multiplex channels to a converter, the rate limit is impacted by
the number of channels you use. For more information, see “Sampling” on page 1-13.
Example: [8000 192000]
Data Types: double
15-33
15 Functions
Example: true
Data Types: logical
Callback function to execute when scans are available from the input channels, specified as a function
handle
Example: @read
Data Types: function_handle
Callback function to execute when scan data is required for device output channels. specified as a
function handle.
Example: @write
Data Types: function_handle
15-34
DataAcquisition
Data acquisition hardware vendor information, returned as a vendor object with the following
properties:
ID
FullName
AdaptorVersion
DriverVersion
IsOperational
This object is the same as the corresponding vendor object returned by the daqvendorlist
function.
Object Functions
addinput Add input channel to device interface
read Read data acquired by hardware
readwrite Simultaneously read and write device channel data
start Start DataAcquisition background operation
stop Stop background operation
removechannel Remove channel from device interface
flush Flush DataAcquisition input and output buffers
write Write output scans to hardware channels
preload Queue scan data for device output
addoutput Add output channel to device interface
addbidirectional Add digital bidirectional channel to device interface
resetcounters Reset hardware scan count for all counter inputs
addclock Add clock connection to device interface
removeclock Remove clock from device interface
addtrigger Add trigger connection to device interface
removetrigger Remove trigger from device interface
Examples
Create a DataAcquisition
Create and configure a DataAcquisition object for interfacing with National Instruments devices.
15-35
15 Functions
d = daq("ni")
d.Rate = 20000;
Version History
Introduced in R2020a
See Also
Functions
daqlist | daqvendorlist | daqreset | daq | daqhelp
15-36
decimalToBinaryVector
decimalToBinaryVector
Convert decimal value to binary vector
Syntax
binVal = decimalToBinaryVector(decimalNumber)
binVal = decimalToBinaryVector(decimalNumber,numberOfBits)
binVal = decimalToBinaryVector(decimalNumber,numberOfBits,bitOrder)
binVal = decimalToBinaryVector(decimalNumber,[],bitOrder)
Description
binVal = decimalToBinaryVector(decimalNumber) converts a positive decimal number to a
binary vector, represented using the minimum number of bits.
Examples
binVal = decimalToBinaryVector(6)
binVal =
1 1 0
binVal = decimalToBinaryVector(0:4)
binVal =
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
15-37
15 Functions
binVal = decimalToBinaryVector(6,8,'MSBFirst')
binVal =
0 0 0 0 0 1 1 0
binVal = decimalToBinaryVector(6,[],'LSBFirst')
binVal =
0 1 1
Convert an Array of Decimals into a Binary Vector Array with LSB First
binVal =
0 0 0 0
1 0 0 0
0 1 0 0
1 1 0 0
0 0 1 0
Input Arguments
decimalNumber — Number to convert to binary vector
numeric
The number of bits required to correctly represent the decimal. This is an optional argument. If you
do not specify the number of bits, the number is represented using the minimum number of bits
needed. By default minimum number of bits needed to represent the value is specified, unless you
specify a value
Bit order for the binary vector representation, specified as a character vector or string. Accepted
values are:
• 'MSBFirst' — The first element of the binary vector is the most significant bit.
15-38
decimalToBinaryVector
• 'LSBFirst' — The first element of the binary vector is the least significant bit.
Output Arguments
binVal — Binary value
array of 1s and 0s
Version History
Introduced in R2012b
See Also
Functions
hexToBinaryVector | binaryVectorToDecimal | binaryVectorToHex
Topics
“Generate Digital Output Using Decimal Data Across Multiple Lines” on page 9-14
15-39
15 Functions
disableVendorDiagnostics
Suppress vendor diagnostic display in device listing
Syntax
disableVendorDiagnostics
Description
disableVendorDiagnostics turns off the display of diagnostic information in the daqlist
function output related to non-operational vendors. The display is enabled by default.
Examples
Allow diagnostic information to display in the device listing. The installation does not include drivers
for 'ni' or 'mcc'.
enableVendorDiagnostics
daqlist
ans =
1×5 table
Suppress diagnostic information in the device listing. The installation is the same.
disableVendorDiagnostics
daqlist
ans =
1×5 table
15-40
disableVendorDiagnostics
Version History
Introduced in R2020a
See Also
Functions
daqlist | daqvendorlist | enableVendorDiagnostics
15-41
15 Functions
enableVendorDiagnostics
Allow diagnostic display in vendor listing
Syntax
enableVendorDiagnostics
Description
enableVendorDiagnostics turns on the display of diagnostic information in the daqlist function
output related to non-operational vendors. The display is enabled by default.
Examples
Allow diagnostic information to display in the device listing. The installation does not include drivers
for 'ni' or 'mcc'.
enableVendorDiagnostics
daqlist
ans =
1×5 table
Suppress diagnostic information in the device listing. The installation is the same.
disableVendorDiagnostics
daqlist
ans =
1×5 table
15-42
enableVendorDiagnostics
Version History
Introduced in R2020a
See Also
Functions
daqlist | daqvendorlist | disableVendorDiagnostics
15-43
15 Functions
flush
Package: daq.interfaces
Syntax
flush(d)
Description
flush(d) removes all acquired and queued scans in the input and output buffers of the
DataAcquisition interface.
Examples
d = daq("ni")
% :
flush(d)
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Version History
Introduced in R2020a
See Also
Functions
daq
15-44
hasdata
hasdata
Package: matlab.io.datastore
Syntax
tf = hasdata(tdmsds)
Description
tf = hasdata(tdmsds) returns logical 1 (true) if there is data available to read from the TDMS
datastore specified by tdmsds. Otherwise, it returns logical 0 (false).
Examples
In a while-loop, use hasdata to determine if there is any more data to read at the current location.
tdmsds = tdmsDatastore(tdmsDatastore("C:\data\tdms"));
while hasdata(tdmsds)
m = read(tdmsds);
⋮
end
Input Arguments
tdmsds — TDMS datastore
TDMSDatastore object
Output Arguments
tf — Indicator of data to read
1|0
Version History
Introduced in R2022a
15-45
15 Functions
See Also
Functions
tdmsDatastore | read | reset
15-46
hexToBinaryVector
hexToBinaryVector
Convert hexadecimal value to binary vector
Syntax
binVal = hexToBinaryVector(hexNumber)
binVal = hexToBinaryVector(hexNumber,numberOfBits)
binVal = hexToBinaryVector(hexNumber,numberOfBits,bitOrder)
Description
binVal = hexToBinaryVector(hexNumber) converts hexadecimal numbers to a binary vector.
Examples
binVal = hexToBinaryVector('A1')
binVal =
1 0 1 0 0 0 0 1
binVal = hexToBinaryVector('0xA')
binVal =
1 0 1 0
binVal = hexToBinaryVector(['A1';'B1'])
binVal =
15-47
15 Functions
1 0 1 0 0 0 0 1
1 0 1 1 0 0 0 1
binVal = hexToBinaryVector('A1',12,'MSBFirst')
binVal =
0 0 0 0 1 0 1 0 0 0 0 1
Convert a Cell Array of Hexadecimal Numbers into a Binary Vector of Specific Bits
binVal = hexToBinaryVector({'A1';'B1'},8)
binVal =
1 0 1 0 0 0 0 1
1 0 1 1 0 0 0 1
binVal =
1 0 0 0 0 1 0 1
Input Arguments
hexNumber — Hexadecimal to convert to binary vector
hexadecimal value
Number of bits to represent the decimal number, specified as a numeric value. This is an optional
argument. If you do not specify the number of bits, the number is represented using the minimum
number of bits needed.
15-48
hexToBinaryVector
Bit order for the binary vector representation, specified as a character vector or string. Accepted
values are:
• 'MSBFirst' — The first element of the binary vector is the most significant bit.
• 'LSBFirst' — The first element of the binary vector is the least significant bit.
Output Arguments
binVal — Binary value
array of 1s and 0s
Version History
Introduced in R2012b
See Also
Functions
decimalToBinaryVector | binaryVectorToDecimal | binaryVectorToHex
Topics
“Acquire Digital Data in Hexadecimal Values” on page 9-12
15-49
15 Functions
preload
Package: daq.interfaces
Syntax
preload(d,scanData)
Description
preload(d,scanData) provides scan data to the DataAcquisition interface d for device output.
You queue data before calling start on your DataAcquisition. Calling start runs the
DataAcquisition in the background, without blocking MATLAB.
Examples
Queue scan data to the DataAcquisition interface in preparation for device output.
Define and queue a sine wave for output of one cycle on a single channel.
scanData = sin(linspace(0,2*pi,5000)');
preload(d,scanData)
% ⋮
start(d)
Define and queue a sine wave for repeated output on a single channel.
scanData = sin(linspace(0,2*pi,5000)');
preload(d,scanData)
% ⋮
start(d,"RepeatOutput")
% ⋮
stop(d)
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq(...)
15-50
preload
Scan data for device output, specified as an M-by-N matrix, where M is the number of data scans and
N is the number of output channels in the DataAcquisition interface. For a single channel, the data is
a column vector.
Data Types: double
Version History
Introduced in R2020a
See Also
Functions
daq | start | flush
15-51
15 Functions
preview
Package: matlab.io.datastore
Syntax
data = preview(tdmsds)
Description
data = preview(tdmsds) returns the first 8 records from TDMS datastore tdmsds, without
changing the current read position in the datastore.
Examples
data =
data{3}
ans =
8×2 table
Torque1 Torque2
________ ________
0.15 -0.55729
-0.18286 0.1
-0.18286 -0.55729
-0.18286 -0.88593
-0.18286 0.1
0.15 -0.22864
-0.51572 -0.88593
0.15 0.1
Input Arguments
tdmsds — TDMS datastore
TDMSDatastore object
15-52
preview
Output Arguments
data — Start of TDMS datastore records
cell array of tables
Start of TDMS datastore records, returned as a cell array of tables from the TDMS data.
Version History
Introduced in R2022a
See Also
Functions
tdmsDatastore | read | readall | hasdata
15-53
15 Functions
read
Package: daq.interfaces
Syntax
scanData = read(d)
scanData = read(d,span)
[scanData,triggerTime] = read( ___ )
scanData = read( ___ ,"OutputFormat","Matrix")
[scanData,timeStamp,triggerTime] = read( ___ ,"OutputFormat","Matrix")
Description
scanData = read(d) reads a single input scan from all input channels on the DataAcquisition, and
returns a timetable to scanData.
scanData = read(d,span) reads a span of input scans from the DataAcquisition interface, and
returns a timetable to scanData. You can specify span as a duration, a number of scans, or "all".
• If the DataAcquisition is not running and has no acquired data, the DataAcquisition starts a
foreground finite acquisition to read the requested number of scans. MATLAB is blocked until the
acquisition and read are complete.
• If the DataAcquisition is running when you call this function, it reads data already acquired, if
necessary waiting until the specified number of scans are available. MATLAB is blocked until the
acquisition and read are complete. This is typical when start is called to run a background
acquisition prior to calling read.
• If the DataAcquisition is not running but has acquired data from a previous run, it reads the
specified number of scans or all the data, whichever is less.
[scanData,triggerTime] = read( ___ ) performs the specified read, and returns a timetable to
scanData and scan trigger time to triggerTime as a datetime.
scanData = read( ___ ,"OutputFormat","Matrix") performs the specified read, and returns
an M-by-N matrix of doubles to scanData, where M is the number of scans and N is the number of
input channels. Each column contains the data from one channel.
Examples
15-54
read
Without specifying a duration or number of scans, the read function acquires a single on-demand
scan on all channels.
d = daq("ni")
addinput(d,"Dev1",1,"Voltage"); % add more channels as needed
scanData = read(d)
data =
timetable
Time Dev1_ai1
_____ ________
0 sec -1.9525
If there is no data available to be read from the device, the read function initiates a foreground
acquisition, blocking MATLAB until complete.
d = daq("ni");
ch = addinput(d,"Dev1",1:2,"Voltage")
ch =
scanData = read(d,5)
scanData =
5×2 timetable
d.Rate = 1000;
scanData = read(d,seconds(0.005))
scanData =
5×2 timetable
15-55
15 Functions
You can also read the data into arrays of double values. Five scans on two channels results in a 5-by-2
matrix, with a column for each channel.
scanData = read(d,5,"OutputFormat","Matrix")
scanData =
0.0424 0.0644
0.0572 0.0621
0.0605 0.0638
0.0618 0.0641
0.0631 0.0648
When a background acquisition is initiated with the start function, use read to import the data.
d = daq("ni");
ch = addinput(d,"Dev1",1:2,"Voltage")
start(d,"NumScans",5)
scanData = read(d,"all")
scanData =
5×2 timetable
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
15-56
read
Example: d = daq()
Length of read operation, specified as a duration or double. If this is a duration type, it specifies the
time duration of acquisition; if a double, it specifies the number of scans.
Example: seconds(5)
Data Types: double | duration
Output Arguments
scanData — Input scan data from the device
timetable | double
Input scan data from the device, returned as a timetable or matrix of doubles, depending on the
OutputFormat setting.
The time stamp for each scan in the timetable is a duration, relative to the trigger time. You can
access the scan trigger time in the timetable property
scanData.Properties.CustomProperties.TriggerTime, returned as a datetime.
Times of scan acquisitions, returned as a matrix of doubles. Each value represents relative time in
seconds after the first scan. This argument is returned only when OutputFormat is specified as
"Matrix".
Version History
Introduced in R2020a
See Also
Functions
start
15-57
15 Functions
read
Package: matlab.io.datastore
Syntax
data = read(tdmsds)
[data,info] = read(tdmsds)
Description
data = read(tdmsds) reads data from the files in the TDMS datastore tdmds, and returns a cell
array of tables or timetables. Each element of the cell array corresponds to a channel group in the
datastore file data.
The read function returns a subset of data from the datastore. The size of the subset is determined
by the ReadSize property of the datastore object. On the first call, read starts reading from the
beginning of the datastore, and subsequent calls continue reading from the endpoint of the previous
call. Use reset to read from the beginning again.
The function returns a cell array of tables or a cell array of timetables, depending on the value of the
tdmds.RowTimes property. See “Read TDMS-File Data into Timetables” on page 15-58.
[data,info] = read(tdmsds) also returns the output argument info, with information and
metadata about the extracted data.
Examples
Read data from a TDMS datastore one file at a time. Set the read size and read the first data set.
tdmsds = tdmsDatastore("C:\data\tdms",ReadSize="file");
data1 = read(tdmsds);
Read the second file and view information about the data.
[data2,info2] = read(tdmsds);
info2
info2 =
struct with fields:
Filename: "C:\data\tdms\Turbine_002.tdms"
FileSize: 172098
Offset: 0
15-58
read
By providing a vector of durations, you can read TDMS-file data into timetables.
Define a vector of 1000 elements of 1 ms duration. Set up the datastore object to read 1000 records
(ReadSize) and return a timetable (RowTimes).
durvec = milliseconds(1:1000);
tdmsds = tdmsDatastore("C:\data\tdms",ReadSize=1000,RowTimes=durvec)
tdmsds =
dd =
ans =
1000×2 timetable
: : :
15-59
15 Functions
Input Arguments
tdmsds — TDMS datastore
TDMSDatastore object
Output Arguments
data — Output data
cell array of tables
Output data, returned as a cell array of tables from the TDMS records.
Information about the data source file, returned as a structure with the following fields:
Filename
FileSize
Offset
The offset field indicates the position of the data in the file.
Version History
Introduced in R2022a
See Also
Functions
tdmsDatastore | reset | preview | readall | hasdata
15-60
readall
readall
Package: matlab.io.datastore
Syntax
data = readall(tdmsds)
Description
data = readall(tdmsds) reads all the data in the datastore specified by tdmsds, and returns a
cell array of tables or timetables. Each element of the cell array corresponds to a channel group in
the datastore file data.
The function returns a cell array of tables or a cell array of timetables, depending on the value of the
tdmds.RowTimes property. See tdmsDatastore.
After the readall function returns all the data, it resets tdmsds to point to the beginning of the
datastore.
Examples
Read all the data from a multiple file TDMS datastore into an array of tables.
data =
ans =
9936×2 table
Acceleration1 Acceleration2
_____________ _____________
-1.9851 0
-3.9702 0
11.911 1.5521
5.9553 -1.5521
1.9851 -4.6562
5.9553 4.6562
3.9702 -1.5521
15-61
15 Functions
3.9702 -4.6562
: :
-4.8046 6.7826
-7.2068 2.2609
-7.2068 4.5218
-7.2068 6.7826
-2.4023 9.0435
-2.4023 4.5218
-9.6091 2.2609
-12.011 4.5218
Input Arguments
tdmsds — TDMS datastore
TDMSDatastore object
Output Arguments
data — Output data
cell array of tables
Output data, returned as a cell array of tables from all TDMS-files in the datastore.
Version History
Introduced in R2022a
See Also
Functions
tdmsDatastore | read | preview
15-62
readwrite
readwrite
Package: daq.interfaces
Syntax
inScanData = readwrite(d,outScanData)
[inScanData,triggerTime] = readwrite(d,outScanData)
inScanData = readwrite(d,outScanData,"OutputFormat","Matrix")
[inScanData,timeStamp,triggerTime] = readwrite( ___ ,"OutputFormat","Matrix")
Description
inScanData = readwrite(d,outScanData) writes outScanData to the DataAcquisition
interface output channels, and reads inScanData from the DataAcquisition interface input channels.
Input and output have the same number of scans, determined by the number of rows in the matrix
outScanData. By default, data is returned to inScanData as a timetable. readwrite supports only
foreground clocked operations, blocking MATLAB until complete.
Examples
Configure the DataAcquisition to measure and generate voltage simultaneously, in the foreground.
d = daq("ni");
addinput(d, "Dev1","ai0","Voltage");
addoutput(d, "Dev1","ao0","Voltage");
outScanData = linspace(0,1,d.Rate)'; % Increase output voltage with each scan.
inScanData = readwrite(d,outScanData);
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
15-63
15 Functions
Scan data for device output, specified as an M-by-N matrix, where M is the number of data scans and
N is the number of output channels in the DataAcquisition interface. For a single channel, the data is
a column vector. Single scans are not supported by this function, so M must be greater than 1.
Data Types: double
Output Arguments
inScanData — Input scan data from the device
timetable | double
Input scan data from the device, returned as a timetable or matrix of doubles, depending on the
OutputFormat setting.
You can access the scan trigger time in the timetable property
inScanData.Properties.CustomProperties.TriggerTime, returned as a datetime.
Times of scan acquisitions, returned as a matrix of doubles. Each value represents relative time in
seconds after the first scan. This argument is returned only when OutputFormat is specified as
"Matrix".
Version History
Introduced in R2020a
See Also
Functions
daq
15-64
removechannel
removechannel
Package: daq.interfaces
Syntax
removechannel(d,idx)
Description
removechannel(d,idx) removes the specified channels from the DataAcquisition interface. If the
DataAcquisition has channels with indices higher than the channels being removed, they are
renumbered to fill the empty gaps left by the removal, but the channel names do not change.
Examples
d = daq("directsound");
addinput(d,"Audio0","1","Audio");
addinput(d,"Audio1","1","Audio");
addoutput(d,"Audio3","1","Audio");
addoutput(d,"Audio6","1","Audio");
d.Channels
removechannel(d,2)
d.Channels
Note that after removal of the second channel, the remaining channels are numbered 1, 2, and 3. The
channel names are not changed.
15-65
15 Functions
removechannel(d,[1:length(d.Channels)])
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Channel index, specified as a numeric scalar or vector. Removing a channel shifts down the indices of
remaining higher channels, but does not change the channel names. Do not confuse the channel
index in the DataAcquisition with the channel ID of the data acquisition device.
Example: [1,3]
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
Version History
Introduced in R2020a
See Also
Functions
daqlist | daq | addinput | addoutput | addbidirectional
15-66
removeclock
removeclock
Package: daq.interfaces
Syntax
removeclock(d,idx)
Description
removeclock(d,idx) removes the specified clock from the DataAcquisition interface. If the
DataAcquisition has clocks with indices higher than the clock being removed, they are renumbered to
fill the empty gaps left by the removal.
Examples
d = daq("ni");
% :
Cidx = addclock(d,"ScanClock","Dev1/PFI0","Dev2/PFI0");
% :
removeclock(d,Cidx);
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Clock index, specified as a numeric scalar or vector. Removing a clock shifts down the indices of
remaining higher clocks.
Example: 1
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
Version History
Introduced in R2020a
15-67
15 Functions
See Also
Functions
daq | addclock
15-68
removetrigger
removetrigger
Package: daq.interfaces
Syntax
removetrigger(d,idx)
Description
removetrigger(d,idx) removes the specified trigger from the DataAcquisition interface. If the
DataAcquisition has triggers with indices higher than the trigger being removed, they are
renumbered to fill the empty gaps left by the removal.
Examples
d = daq("ni");
% :
Tidx = addtrogger(d,"Digital","StartTrigger","Dev1/PFI0","Dev2/PFI0");
% :
removetrigger(d,Tidx);
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Trigger index, specified as a numeric scalar or vector. Removing a trigger shifts down the indices of
remaining higher triggers.
Example: 1
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
Version History
Introduced in R2020a
15-69
15 Functions
See Also
Functions
daq | addtrigger
15-70
reset
reset
Package: matlab.io.datastore
Syntax
reset(tdmsds)
Description
reset(tdmsds) resets the TDMS datastore specified by tdmsds to its initial read state, where no
data has been read from it. Resetting allows you to reread from the same datastore.
Examples
Input Arguments
tdmsds — TDMS datastore
TDMSDatastore object
Version History
Introduced in R2022a
See Also
Functions
tdmsDatastore | read | hasdata
15-71
15 Functions
resetcounters
Package: daq.interfaces
Syntax
resetcounters(d)
Description
resetcounters(d) resets hardware scan count for all counter inputs between on-demand reads on
the DataAcquisition d.
Examples
Configure a DataAcquisition to measure an EdgeCount until the count exceeds a threshold, then reset
the counter.
d = daq("ni");
addinput(d,"Dev1","ctr0","EdgeCount");
maxCount = 100;
count = read(d);
while count <= maxCount
count = read(d);
end
resetcounters(d);
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Version History
Introduced in R2020a
See Also
15-72
start
start
Package: daq.interfaces
Syntax
start(d)
start(d,"Continuous")
start(d,"RepeatOutput")
start(d,"Duration",span)
start(d,"NumScans",span)
Description
start(d) starts the DataAcquisition interface background operation. When the input acquisition and
output generation begin depends on channel configuration and preloaded output data:
• If the DataAcquisition has only input channels, the acquisition begins immediately, collecting scan
data, which you can access later with the read function. The default scan duration is 1 second.
• If the DataAcquisition interface has only output channels, generation begins immediately if data is
already queued with the preload function. If no data is queued, output begins when data is made
available with write function.
• If the DataAcquisition has both input and output channels, the input acquisition begins and ends
at the same time as the output generation, resulting in the same number of scans.
Examples
When a background acquisition is initiated with the start function, use read to import the data.
15-73
15 Functions
d = daq("ni");
ch = addinput(d,"Dev1",1:2,"Voltage")
start(d,"NumScans",5)
scanData = read(d,"all")
scanData =
5×2 timetable
Define and preload data for device output, then start output generation to repeat in the background
while MATLAB continues.
d = daq("ni");
addoutput(d,"Dev1",1,"Voltage");
signalData = sin((1:1000)*2*pi/1000);
preload(d,signalData') % Column of data for one channel
start(d,"RepeatOutput")
% Device output now repeated while MATLAB continues.
stop(d)
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
15-74
start
Version History
Introduced in R2020a
See Also
Functions
daq | preload | stop | read | write
Topics
“Generate Signals in the Background” on page 6-13
“Generate Signals in the Background Continuously” on page 6-14
“Generate Continuous and Background Signals Using NI Devices” on page 18-57
“Acquire Continuous and Background Data Using NI Devices” on page 18-18
“Log Analog Input Data to a File Using NI Devices” on page 18-64
“Communicate with I2C Devices and Analyze Bus Signals Using Digital IO” on page 18-118
“Generate Pulse Width Modulated Signals Using NI Devices” on page 18-108
“Acquire Continuous Audio Data” on page 18-83
“Create an Echometer Using Audio Measurements” on page 18-162
“Acquire Data from Two Devices at Different Rates” on page 18-136
15-75
15 Functions
stop
Package: daq.interfaces
Syntax
stop(d)
Description
stop(d) stops the DataAcquisition interface background operations, and flushes queued output data.
Input data acquired by the operation is not flushed.
Examples
d = daq("ni")
% :
start(d)
% :
stop(d)
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Version History
Introduced in R2020a
See Also
Functions
daq | start
15-76
tdmsDatastore
tdmsDatastore
Datastore for collection of TDMS-files
Description
Use the TDMSDatastore object to access data from a collection of TDMS-files.
Creation
Syntax
tdmsds = tdmsDatastore(location)
tdmsds = tdmsDatastore(__,Name=Value)
Description
Input Arguments
Location of TDMS datastore files, specified as a string, character vector, or cell array identifying
either files or folders. The path can be relative or absolute, and can contain the wildcard characters ?
and *. If location specifies a folder, the datastore includes all files in that folder with the
extension .tdms.
Example: "C:\data\tdms_set1"
Data Types: char | string | cell
You can specify file information or object “Properties” on page 15-78. Allowed options are
IncludeSubfolders, AlternateFileSystemRoots, and the properties
SelectedChannelGroup, SelectedChannels, RowTimes, and ReadSize.
Example: SelectedChannelGroup="Acceleration"
15-77
15 Functions
Include files in subfolders, specified as a logical. Specify true to include files in each folder and
recursively in subfolders.
Example: IncludeSubfolders=true
Data Types: logical
Root paths to the TDMS-files for different platforms, specified as an array of strings.
Example: AlternateFileSystemRoots=["Z:\datasets", "/tdms/datasets"]
Data Types: char | string | cell
Properties
Files — Files included in datastore
char | string | cell
Files included in the datastore, specified as a character vector or string identifying a relative or
absolute path to a file or folder. The wildcard characters ? and * are supported. All TDMS-files in the
specified folder are included in the datastore. The property value is stored as a string vector of file
names.
Example: "file*.tdms"
Data Types: char | string
Those channels targeted for reading must have the same name and belong to the same channel group
in each file of the TDMS datastore.
Data Types: table
Channel group containing the channels to read from, specified as a string or character vector.
Example: "Torque"
Data Types: string | char
15-78
tdmsDatastore
Names of channels to read, specified as a character vector, string, or array of either. The channels
must be in the channel group specified by SelectedChannelGroup in each file of the TDMS
datastore.
Example: ["Torque1" "Torque2"]
Data Types: char | string | cell
Times associated with rows of the table, specified as a selected time channel name, a datetime vector,
or a duration vector. Setting this property causes the read and readall functions to output a cell
array of timetables. Each time element labels a row in the output timetable.
Example: duration(seconds([1:1000]/1000))
Data Types: datetime | duration | string
Size of data returned by the read function, specified as "file" or a numeric value. A string value of
"file" causes a read of one TDMS-file at a time; a numeric value specifies the number of records to
read. The readall function ignores this property.
If you change the ReadSize property value after creating the TDMSDatastore object, the datastore
resets.
Example: 5000
Data Types: double | string | char
Object Functions
read Read data in TDMS datastore
readall Read all data in TDMS datastore
preview Read first 8 records from TDMS datastore
hasdata Determine if data is available to read from TDMS datastore
reset Reset TDMS datastore to initial state
combine Combine data from multiple datastores
transform Transform datastore
Examples
Create a TDMS datastore from all the TDMS-files in the folder C:\data\tdms, and read the data into
tables.
ans =
15-79
15 Functions
6×4 table
data_set =
data_set{1}
ans =
9936×2 table
Acceleration1 Acceleration2
_____________ _____________
-1.9851 0
-3.9702 0
11.911 1.5521
5.9553 -1.5521
1.9851 -4.6562
5.9553 4.6562
3.9702 -1.5521
3.9702 -4.6562
13.896 0
: :
-4.8046 -2.2609
-4.8046 6.7826
-7.2068 2.2609
-7.2068 4.5218
-7.2068 6.7826
-2.4023 9.0435
-2.4023 4.5218
-9.6091 2.2609
-12.011 4.5218
15-80
tdmsDatastore
data_set =
{9936×2 table}
data_set =
{500×2 table}
Limitations
• As a special case of a datastore, the TDMSDatastore object does not support the following
functionality:
Version History
Introduced in R2022a
See Also
External Websites
The NI TDMS File Format
15-81
15 Functions
tdmsinfo
Information about TDMS-file
Syntax
info = tdmsinfo(tdmsfile)
Description
info = tdmsinfo(tdmsfile) returns a TdmsInfo object with properties containing general
information about the TDMS-file, such as file name, location, description, author, version, and list of
channels.
Examples
info =
Path: "C:\data\tdms\Turbine_003.tdms"
Name: "Turbine_003"
Description: "Test the Acceleration, Force and Torque of Turbine"
Title: "Turbine Tests"
Author: "xyz"
Version: "2.0"
ChannelList: [6×8 table]
6×8 table
Input Arguments
tdmsfile — TDMS file name
string
15-82
tdmsinfo
For local files, use a full or relative path that contains a file name and extension. You also can specify
a file on the MATLAB path.
For Internet files, specify the URL. For example, to read a remote file from the Amazon S3 cloud:
data = tdmsread("s3://bucketname/path_to_file/data.tdms");
Example: "airlinesmall.tdms"
Data Types: char | string
Output Arguments
info — TDMS-file information
TdmsInfo object
Version History
Introduced in R2022a
15-83
15 Functions
See Also
Functions
tdmsread | tdmsreadprop | tdmswriteprop | tdmswrite
15-84
tdmsread
tdmsread
Read data from TDMS-file
Syntax
data = tdmsread(tdmsfile)
data = tdmsread(tdmsfile,Name=Value)
Description
data = tdmsread(tdmsfile) retrieves data from the specified TDMS-file and returns a cell array
of tables. Each element of the cell array is a table corresponding to a channel group.
data = tdmsread(tdmsfile,Name=Value) uses name-value pairs to filter the data reading and
specify output format.
Examples
Read data from a specified TDMS-file. You can determine which channels are read, and what format
the result has.
data = tdmsread("airlinesmall.tdms");
Read a subset of the variables in a TDMS-file into MATLAB as a timetable. Use the variable ArrTime
in the TDMS-file as the time vector of the output timetable.
Read the channel data into a timetable with a specified start time and step duration.
Input Arguments
tdmsfile — TDMS file name
string
15-85
15 Functions
For local files, use a full or relative path that contains a file name and extension. You also can specify
a file on the MATLAB path.
For Internet files, specify the URL. For example, to read a remote file from the Amazon S3 cloud:
data = tdmsread("s3://bucketname/path_to_file/data.tdms");
Example: "airlinesmall.tdms"
Data Types: char | string
Channel group containing the channels to read from, specified as a string or character vector.
Example: "Torque"
Data Types: string | char
Names of channels to read, specified as a string, string array, character vector, or cell array of
character vectors. The channels must be in the channel group specified by ChannelGroupName.
Example: ["Torque1" "Torque2"]
Data Types: char | string | cell
Times associated with rows of the table, specified as a selected time channel name, a datetime vector,
or a duration vector. Specifying this option causes the function to output a cell array of timetables.
Each time element labels a row in the output timetable.
Example: duration(seconds([1:1000]/1000))
Data Types: datetime | duration | string
Start time of the output timetable, specified as a scalar datetime or duration indicating the time of
the first data record in the timetable.
Example: StartTime=seconds(60)
Data Types: datetime | duration
15-86
tdmsread
Sample rate of the output timetable, specified as a positive scalar double indicating samples per
second.
Example: SampleRate=1000
Data Types: double
Time step of the output timetable, specified as a scalar duration or calendarDuration indicating the
time span between data records.
Example: TimeStep=seconds(0.01)
Data Types: duration | calendarDuration
Output Arguments
data — Output data
cell array of tables
Output data, returned as a cell array of tables or timetables with data records from the TDMS-file.
Each element of the cell array is a table or timetable for a channel group. The cell array index
corresponds to the channel group number.
When the start time for the first sample is 0 and the sample times are relative to that (duration), the
sample times returned to the timetable are based on seconds since the epoch in the local time zone
equivalent to 01/01/1904 00:00:00.00 UTC (using the Gregorian calendar and ignoring leap seconds).
For more information, see TDMS File Format Internal Structure.
Version History
Introduced in R2022a
See Also
Functions
tdmsinfo | tdmsreadprop | tdmswrite | tdmswriteprop
15-87
15 Functions
tdmsreadprop
Read properties as single row table from TDMS-file
Syntax
props = tdmsreadprop(tdmsfile)
props = tdmsreadprop(tdmsfile,Name=Value)
Description
props = tdmsreadprop(tdmsfile) returns a table of properties from the specified TDMS-file.
Examples
props = tdmsreadprop("Turbine_003.tdms")
props =
1×7 table
"Turbine_003" "Turbine Tests" "xyz" "Test the Acceleration, Force and Torque of Tur
props = tdmsreadprop("Turbine_003.tdms",ChannelGroupName="Torque")
props =
1×2 table
name description
________ ___________
"Torque" "CGTorque"
props =
1×19 table
15-88
tdmsreadprop
props =
1×3 table
Input Arguments
tdmsfile — TDMS file name
string
For local files, use a full or relative path that contains a file name and extension. You also can specify
a file on the MATLAB path.
For Internet files, specify the URL. For example, to read a remote file from the Amazon S3 cloud:
data = tdmsread("s3://bucketname/path_to_file/data.tdms");
Example: "airlinesmall.tdms"
Data Types: char | string
Channel group containing the channels to read from, specified as a string or character vector.
Example: "Torque"
Data Types: string | char
15-89
15 Functions
Name of channel to read, specified as a string or character vector. The channel must be in the
channel group specified by ChannelGroupName.
Example: "Torque2"
Data Types: char | string
Property names to read, specified as a string, string array, character vector, or cell array of character
vectors.
Example: ["Torque1" "Torque2"]
Data Types: char | string | cell
Output Arguments
props — Table of properties from TDMS-file
table
Version History
Introduced in R2022a
See Also
Functions
tdmswriteprop | tdmsinfo | tdmsread | tdmswrite
15-90
tdmswrite
tdmswrite
Write data to TDMS-file
Syntax
tdmswrite(tdmsfile,tdmsdata)
tdmswrite(tdmsfile,tdmsdata,ChannelGroupNames=chGrpName)
tdmswrite( ___ ,TimeChannel=timeChan)
Description
With the tdmswrite function you can write table or timetable data to a new or existing TDMS-file.
tdmswrite( ___ ,TimeChannel=timeChan) specifies how measurement time is included in the file
when writing data from a timetable. A TimeChannel value of "none" adds the start time and step
time to the channel properties. A value of "single" adds a single channel with a timestamp for
every measurement. If you are writing data from a regular table, the TimeChannel setting is
ignored.
Examples
Write data to a specified TDMS-file. You can use default channel groups or specify channel group
names.
Write a table or timetable of data, T, to a new channel group in the TDMS-file named
sinewave.tdms.
tdmswrite("sinewave.tdms",T)
Write table or timetable of data, T, to a specific channel group in a TDMS-file. If the channel group
does not exist, it is added to the file.
tdmswrite("sinewave.tdms", T, ChannelGroupNames="MeasuredData")
15-91
15 Functions
Input Arguments
tdmsfile — TDMS file name
string
For local files, use a full or relative path that contains a file name and extension. You also can specify
a file on the MATLAB path.
Example: "sample332.tdms"
Data Types: char | string
TDMS data, specified as table, timetable, or cell array of tables and timetables. Alternatively, you can
specify several tables or timetables as a series of arguments, such as T1,T2,T3.
For a duration timetable, the written start time is 0. When reading this file with tdmsread, the start
time is the epoch in the local time zone equivalent to 01/01/1904 00:00:00.00 UTC (using the
Gregorian calendar and ignoring leap seconds). For more information, see TDMS File Format Internal
Structure.
Data Types: table | timetable | cell
Channel group name, specified as a string or character vector. Use an array of channel group names
when writing multiple tables.
• If the channel group does not exist in the TDMS-file, a new channel group is created.
• If the channel group exists, data is appended to channels with names matching the table variables.
New channels are added to the channel group for table variables not already represented by
existing channel names.
Example: "ChannelGroup1"
Data Types: char | string | cell
Time channel format layout, specified as a string or character vector with value "single" or
"none":
• A value of "single" (default) adds a single channel with a timestamp for every measurement.
This is appropriate for timetables with irregular timing, when each measurement has a unique
datetime or duration, shared across the channels in the channel group. This Time channel is
derived from the Time variable of the input timetable.
15-92
tdmswrite
• A value of "none" adds only the start time and step time to the channel properties
wf_start_time and wf_increment, respectively. Appropriate for regular timetables with fixed
sample rates, this option can reduce the size of the TDMS-file.
Example: "none"
Data Types: char | string
Version History
Introduced in R2022b
See Also
Functions
tdmswriteprop | tdmsread | tdmsinfo | tdmsreadprop
External Websites
TDMS Fragmentation: Why Your TDMS Files Use Too Much Memory
15-93
15 Functions
tdmswriteprop
Write properties to TDMS-file
Syntax
tdmswriteprop(tdmsfile,propname,propvalue)
tdmswriteprop(tdmsfile,propname,propvalue,ChannelGroupName=chGrpName)
tdmswriteprop(tdmsfile,propname,propvalue,ChannelGroupName=
chGrpName,ChannelName=chName)
Description
With the tdmswriteprop function you can write file properties, channel properties and channel
group properties to a TDMS-file.
tdmswriteprop(tdmsfile,propname,propvalue,ChannelGroupName=chGrpName) and
tdmswriteprop(tdmsfile,propname,propvalue,ChannelGroupName=
chGrpName,ChannelName=chName) specify the existing channel group or channel that the property
is assigned to. You can set the properties of only one channel or channel group at a time.
Examples
Input Arguments
tdmsfile — TDMS file name
string | char
15-94
tdmswriteprop
For local files, use a full or relative path that contains a file name and extension. You also can specify
a file on the MATLAB path.
Example: "sinewave.tdms"
Data Types: char | string
Property name, specified as a string or character vector. When writing multiple properties, use an
array of strings to identify them. To create custom properties, specify a name that does not already
exist.
Example: "title"
Data Types: char | string
Property value, specified as a supported type for its property. To set multiple properties, use an array
of values. If the values are different types, for example numeric and string, use a cell array.
Example: {"Input Channel",2.0,"mV"}
Version History
Introduced in R2022b
See Also
Functions
tdmsinfo | tdmsreadprop | tdmsread | tdmswrite
15-95
15 Functions
write
Package: daq.interfaces
Syntax
write(d,scanData)
Description
write(d,scanData) writes scan data to the DataAcquisition interface for the device output. The
DataAcquisition might already be started or not.
• If the DataAcquisition has not been started, write sends the data and starts device output
generation. As a finite foreground generation, this blocks MATLAB until completed.
• If the DataAcquisition had already been started, write provides the data for the output operation
to begin, which then runs in the background without blocking MATLAB. The start function
arguments determine if the generation is finite, repeating, or continuous. Continuous output
requires write to provide data for as long as output is needed; multiple calls to write might be
necessary.
Examples
If the supplied data value specifies only a single scan of data for all output channels, the write
function generates an on-demand output without clocking.
d = daq("ni");
ch = addoutput(d,"Dev1",0:1,"Voltage");
ch =
write(d,[5 5])
Start a DataAcquisition interface for background operation, then provide data for device output.
15-96
write
d = daq("ni");
addoutput(d,"Dev1",1,"Voltage");
signalData = sin((1:1000)*2*pi/1000);
start(d,"RepeatOutput")
% ⋮
write(d,signalData')
% Device output now repeated while MATLAB continues.
pause(5)
stop(d)
Input Arguments
d — DataAcquisition interface
DataAcquisition object
DataAcquisition interface, specified as a DataAcquisition object, created using the daq function.
Example: d = daq()
Scan data for device output, specified as an M-by-N matrix, where M is the number of data scans and
N is the number of output channels in the DataAcquisition interface. Each column of scanData
contains the data for one channel. For a single channel, the data is a column vector.
Data Types: double
Version History
Introduced in R2020a
See Also
Functions
start | read
15-97
16
Apps
16 Apps
Description
The Analog Input Recorder app provides a graphical interface to data acquisition devices.
16-2
Analog Input Recorder
Note Opening the Analog Input Recorder deletes all your existing DataAcquisition interfaces in
MATLAB.
The DataAcquisition interface created by the Analog Input Recorder is not accessible from the
MATLAB command line.
Limitations
This app supports devices only from the following vendors:
The app device list includes only those devices with supported subsystems.
Version History
Introduced in R2017b
See Also
Apps
Analog Output Generator
Topics
“Acquire Data with Analog Input Recorder” on page 6-17
16-3
16 Apps
Description
The Analog Output Generator provides a graphical interface to data acquisition devices.
16-4
Analog Output Generator
Note Opening the Analog Output Generator deletes all your existing DataAcquisition interfaces in
MATLAB.
The DataAcquisition interface created by the Analog Output Generator is not accessible from the
MATLAB command line.
Limitations
The Analog Output Generator currently supports only analog voltage and current outputs, and
audio output generation.
The app device list includes only those devices with supported subsystems.
Version History
Introduced in R2019a
See Also
Apps
Analog Input Recorder
Topics
“Generate Signals with Analog Output Generator” on page 6-21
16-5
17
Blocks
17 Blocks
Analog Input
Acquire data from multiple analog channels of data acquisition device
Library: Data Acquisition Toolbox
Description
The Analog Input block opens, initializes, configures, and controls an analog data acquisition device.
The opening, initialization, and configuration of the device occur once at the start of the model
execution. During the model run time, the block acquires data either synchronously (deliver the
current block of data the device is providing) or asynchronously (stream buffered incoming data).
The block has no input ports. It has one or more output ports, depending on the configuration you
choose in its dialog box.
Use the Analog Input block to incorporate live measured data into Simulink for:
• System characterization
• Algorithm verification
• System and algorithm modeling
• Model and design validation
• Controller design
The following diagram shows the basic analog input usage configuration, with which you can:
• Read acquired data at each time step or once per model execution.
• Analyze the data, or use it as input to a system in the model.
• Optionally display results.
Notes To use this block, you need both Data Acquisition Toolbox and Simulink software.
Some devices are not supported by the Simulink blocks in Data Acquisition Toolbox. To see if your
device supports Simulink, refer to Supported Hardware.
17-2
Analog Input
You can use the Analog Input block only with devices that support clocked acquisition. To acquire
data using devices that do not support clocking, use the Analog Input (Single Sample) block.
• If you have DSP System Toolbox™, you can use this block for signal applications.
• This block supports the use of Simulink Accelerator™ mode, but not Rapid Accelerator or code
generation.
• The block supports the use of model referencing, so that your model can include other Simulink
models as modular components.
Ports
Output
Acquired analog input data, returned as doubles. If using only one output port for all channels, each
scan is available as a matrix of scan blocksize by number of channels, M-by-N. If using a port for each
channel, each scan results in a blocksize-by-1 column vector on each port. Multiple ports are named
by channel names or device specified channel IDs.
Data Types: double
Relative timestamp of each scan, returned as a double. This port is available when you check the
Output relative timestamps on page 17-0 parameter.
Data Types: double
Parameters
Use the Block Parameters dialog box to select your acquisition mode and to set other configuration
options.
The device from which you want to acquire data. The items in the list vary, depending on which
devices you have connected to your system. Devices in the list are specified by adaptor or vendor
name and unique device ID, followed by the model name of the device, for example, ni Dev1
(USB-6255). The first available device is selected by default. A CompactDAQ chassis would be
shown as a single device identified by vendor name, chassis ID, and chassis model; for example, ni
cDAQ2 (cDAQ-9172).
17-3
17 Blocks
Asynchronous — In asynchronous mode, the data acquisition from the device and the simulation
happen in parallel. The model initiates the acquisition from the device when the simulation starts.
Data from the device is continuously acquired into a FIFO (first in, first out) buffer in parallel as the
simulation runs. At each time step, the model fetches data from the FIFO buffer and outputs a block
of data. The data in the FIFO buffer is contiguous according to the hardware acquisition clock.
Synchronous — In synchronous mode, the simulation is blocked while acquiring data from the
device. The model initiates the acquisition from the device at each time step and immediately enters a
wait state until the acquisition request has completed. This is unbuffered input; the block outputs the
latest block of data at each time step.
The following diagrams show the difference between synchronous and asynchronous modes for the
Analog Input block.
At the first time step (T1), the acquisition is initiated for the required block of data (B1). The
simulation does not continue until B1 is completely acquired.
17-4
Analog Input
Scenario 1 shows the case when simulation speed outpaces data acquisition speed. At the first time
step (T1), the required block of data (B1) is still being acquired. Therefore, the simulation does not
continue until B1 is completely acquired.
Scenario 2 shows the case when data acquisition speed outpaces simulation speed. At the first time
step (T1), the required block of data (B1) has been completely acquired. Therefore, the simulation
runs continuously.
Note Several factors, including device hardware and model complexity, can affect the simulation
speed, causing both scenarios 1 and 2 to occur within the same simulation.
Device channel selection and configuration table. The channel configuration table lists the hardware
channels of your device, and lets you select and configure them. Specify which channels to acquire
data from (by default all the channels are selected). The following parameters are specified for each
selected channel:
Channel ID — Hardware channel ID specified by the device. The Channel ID column is read-only,
and the parameters are defined when the device is selected.
Name — Channel name. By default the table displays any names provided by the hardware, but you
can edit the names. For example, if the device is a sound card with two channels, you can name them
Left and Right.
Module — Device ID the channel belongs to. The Module column is read-only. If a CompactDAQ
chassis is selected, it shows the ID of the CompactDAQ module which the channel belongs to;
otherwise the ID of the device.
Measurement Type — Measurement type of the channel. This block supports only voltage
measurement types. (For other measurement types, use a DataAcquisition object in MATLAB.)
Input Range — Input ranges available for each channel supported by the hardware, defined when a
device is selected.
17-5
17 Blocks
Coupling — Hardware coupling configuration, such as AC or DC. The coupling type is defined when
a device is selected
1 for all channels — Output data from a single port as a matrix, with a size of blocksize by number
of channels selected.
1 per channel — Output data from N ports, where N is equal to the number of selected channels.
Each output port is a column vector with a size of blocksize-by-1. For naming, each output port uses
the channel name if one was specified, otherwise the channel ID, for example, ai0.
The rate at which samples are acquired from the device, in samples per second. This is the sampling
rate for the hardware. The sample rate must be a positive real number within the range supported by
the selected hardware.
The number of data samples to read from the block output at each time step for each channel. It must
be a positive integer greater than or equal to 2, within the range supported by the selected hardware.
Select this option to output the relative data timestamps, one for each sample. This option adds a new
output port to the block. The data type of this port is double, and corresponds to the time offset in
seconds of the sample related to the start of acquisition. For asynchronous acquisition, the acquisition
is initiated once at the start of model execution, the relative timestamp is a monotonically-increasing
number relative to the start of simulation. For synchronous acquisition, an acquisition is initiated at
every time step; as a result, the relative timestamp is reset to zero every time an acquisition is
initiated.
Version History
Introduced in R2016b
See Also
Blocks
Analog Output | Analog Input (Single Sample) | Analog Output (Single Sample) | Digital Input (Single
Sample) | Digital Output (Single Sample)
17-6
Analog Output
Analog Output
Output data to multiple analog channels of data acquisition device
Library: Data Acquisition Toolbox
Description
The Analog Output block opens, initializes, configures, and controls an analog data acquisition device.
The opening, initialization, and configuration of the device occur once at the start of the model
execution. During the model run time, the block outputs data to the hardware synchronously (outputs
the block of data as it is provided). On every time step, the block performs a blocking synchronous
write to the hardware, outputting the entire input data.
The following diagram shows the timing of the synchronous analog output.
At the first time step (T1), data output is initiated and the corresponding block of data (B1) is output
to the hardware. The simulation does not continue until B1 is output completely.
The block has one or more input ports, depending on the option you choose in its parameters dialog
box. It has no output ports.
The Analog Output block inherits the sample time from the driving block connected to the input port.
The valid data types of the signal at the input port are double or native data types supported by the
hardware.
Notes To use this block, you need both Data Acquisition Toolbox and Simulink software.
You can use the Analog Output block only with devices that support clocked generation. To generate
data using devices that do not support clocking, use the Analog Output (Single Sample) block.
Some devices are not supported by the Simulink blocks in Data Acquisition Toolbox. To see if your
device supports Simulink, refer to Supported Hardware.
17-7
17 Blocks
• This block supports the use of Simulink Accelerator mode, but not Rapid Accelerator or code
generation.
• The block supports the use of model referencing, so that your model can include other Simulink
models as modular components.
Ports
Input
Analog output to generate, specified as doubles. If using only one input port for all channels, specify
an M-by-N matrix for a blocksize of M scans on N channels. Each scan is a row across N channels.
Each channel outputs a column of M scans.
If using a port for each channel, specify a column of data for each channel on each port. Multiple
ports are named by channel names or device specified channel IDs.
Data Types: double
Parameters
Device — Device through which you want to output data
select available device
The device from which you want to generate data. The items in the list vary, depending on which
devices you have connected to your system. Devices in the list are specified by adaptor/vendor name
and unique device ID, followed by the model name of the device, for example, ni Dev1
(USB-6255). The first available device is selected by default. A CompactDAQ chassis is shown as a
single device; vendor name, chassis ID, and chassis model would be shown in the list, for example, ni
cDAQ2 (cDAQ-9172).
Device channel selection and configuration table. The channel configuration table lists the hardware
channels of your device, and lets you select and configure them. Specify which channels to acquire
data from (by default all the channels are selected). The following parameters are specified for each
selected channel:
Channel ID — Hardware channel ID specified by the device. The Channel ID column is read-only,
and the parameters are defined when the device is selected.
Name — Channel name. By default the table displays any names provided by the hardware, but you
can edit the names. For example, if the device is a sound card with two channels, you can name them
Left and Right.
17-8
Analog Output
Module — Device ID the channel belongs to. The Module column is read-only. If a CompactDAQ
chassis is selected, it shows the ID of the CompactDAQ module which the channel belongs to;
otherwise the ID of the device.
Measurement Type — Measurement type of the channel. This block supports only voltage
measurement types. (For other measurement types, use a DataAcquisition object in MATLAB.)
Output Range — Output ranges available for each channel supported by the hardware, defined
when a device is selected.
1 for all channels (default) — One input port on the block for all channels. Provide data as a matrix,
with a size of scan blocksize by number of channels, M-by-N.
1 per channel — N input ports on the block, where N is equal to the number of selected channels.
Provide each port data as a column vector with a size of blocksize-by-1. For naming, each output port
uses the channel name if one was specified, otherwise the channel ID, for example, ao1.
The rate at which samples are output from Simulink to the device, in samples per second. This is the
sampling rate for the hardware. The default is defined when a device is selected. The sample rate
must be a positive real number within the range allowed for the selected hardware.
Version History
Introduced in R2016b
See Also
Blocks
Analog Input | Analog Input (Single Sample) | Analog Output (Single Sample) | Digital Input (Single
Sample) | Digital Output (Single Sample)
17-9
17 Blocks
Description
The Analog Input (Single Sample) block opens, initializes, configures, and controls an analog data
acquisition device. The opening, initialization, and configuration of the device occur once at the start
of the model execution. The block acquires a single sample every time step, synchronously from the
device, during the model run time.
The block has no input ports. It has one or more output ports, depending on the configuration you
choose in its dialog box.
Use the Analog Input (Single Sample) block to incorporate live measured data into Simulink for:
• System characterization
• Algorithm verification
• System and algorithm modeling
• Model and design validation
• Controller design
At the first time step (T1), data is acquired from the selected hardware channels. The simulation does
not continue until data is read from all channels.
Notes To use this block, you need both Data Acquisition Toolbox and Simulink software.
17-10
Analog Input (Single Sample)
Some devices are not supported by the Simulink blocks in Data Acquisition Toolbox. To see if your
device supports Simulink, refer to Supported Hardware.
You can use Analog Input (Single Sample) block only with devices that support single sample
acquisition. If the device does not support single sample acquisition, the model generates an error. To
acquire data from devices that do not support acquisition of a single sample (such as devices
designed for sound and vibration), use the Analog Input block.
• If you have DSP System Toolbox, you can use this block for signal applications.
• This block supports the use of Simulink Accelerator mode, but not Rapid Accelerator or code
generation.
• The block supports the use of model referencing, so that your model can include other Simulink
models as modular components.
Ports
Output
Acquired analog input data, returned as doubles. If using only one output port for all channels, the
output is an array of data. If using a port for each channel, each scan results in a single value on each
port. Multiple ports are named by channel names or device specified channel IDs.
Data Types: double
Timestamp of scan, returned as a double. This port is available when you check the Output timestamp
on page 17-0 parameter.
Data Types: double
Parameters
Use the Block Parameters dialog box to select your device and to set other configuration options.
The device from which you want to acquire data. The items in the list vary, depending on which
devices you have connected to your system. Devices in the list are specified by adaptor or vendor
name and unique device ID, followed by the model name of the device, for example, ni Dev1
(USB-6255). The first available device is selected by default. A CompactDAQ chassis would be
shown as a single device identified by vendor name, chassis ID, and chassis model; for example, ni
cDAQ2 (cDAQ-9172).
17-11
17 Blocks
Device channel selection and configuration table. The channel configuration table lists the hardware
channels of your device, and lets you select and configure them. Specify which channels to acquire
data from (by default all the channels are selected). The following parameters are specified for each
selected channel:
Channel ID — Hardware channel ID specified by the device. The Channel ID column is read-only,
and the parameters are defined when the device is selected.
Name — Channel name. By default the table displays any names provided by the hardware, but you
can edit the names. For example, if the device is a sound card with two channels, you can name them
Left and Right.
Module — Device ID the channel belongs to. The Module column is read-only. If a CompactDAQ
chassis is selected, it shows the ID of the CompactDAQ module which the channel belongs to;
otherwise the ID of the device.
Measurement Type — Measurement type of the channel. This block supports only voltage
measurement types. (For other measurement types, use a DataAcquisition object in MATLAB.)
Input Range — Input ranges available for each channel supported by the hardware, defined when a
device is selected.
Coupling — Hardware coupling configuration, such as AC or DC. The coupling type is defined when
a device is selected
1 for all channels — Outputs the acquired data from a single port as a 1-by-N vector with a length
equal to the number of channels selected.
1 per channel — Outputs the acquired data from N ports, where N is equal to the number of
selected channels. Each port output is a 1-by-1 double. For naming, each output port uses the channel
name if one was specified, otherwise the channel ID, for example, ai0.
Specifies the sample time of the block during the simulation. This is the rate at which the block is
executed during simulation. The default value is 1 (seconds). For more information, see “What Is
Sample Time?” (Simulink).
Select this option to output the absolute timestamp of the scan. This option adds a new output port to
the block. The data type of this port is double (datenum), which corresponds to a serial date number.
You can convert the datenum into a datetime value with the datetime function.
17-12
Analog Input (Single Sample)
Version History
Introduced in R2016b
See Also
Blocks
Analog Input | Analog Output | Analog Output (Single Sample) | Digital Input (Single Sample) | Digital
Output (Single Sample)
17-13
17 Blocks
Description
The Analog Output (Single Sample) block opens, initializes, configures, and controls an analog data
acquisition device. The opening, initialization, and configuration of the device occur once at the start
of the model execution. The block outputs a single sample every time step, synchronously to the
hardware, during the model run time.
The block has one or more input ports, depending on the option you choose in its dialog box. It has no
output ports. The valid data type of the signal at the input port is double.
The Analog Output (Single Sample) block inherits the sample time from the driving block connected
to the input port. Analog output is done synchronously, according to the following diagram.
At the first time step (T1), data is output to the selected hardware channels. The simulation does not
continue until data is output to all channels.
Notes To use this block, you need both Data Acquisition Toolbox and Simulink software.
You can use the Analog Output (Single Sample) block only with devices that support single sample
output. To send data using devices that do not support acquisition of a single sample (such as devices
designed for sound and vibration), use the Analog Output block.
Some devices are not supported by the Simulink blocks in Data Acquisition Toolbox. To see if your
device supports Simulink, refer to Supported Hardware.
17-14
Analog Output (Single Sample)
• This block supports the use of Simulink Accelerator mode, but not Rapid Accelerator or code
generation.
• The block supports the use of model referencing, so that your model can include other Simulink
models as modular components.
Ports
Input
Analog output to generate, specified as doubles. If using only one input port for all channels, provide
a 1-by-N vector for a single scan on all N channels.
If using a port for each channel, provide a double value to each port. Multiple ports are named by
channel names or device specified channel IDs.
Data Types: double
Parameters
Device — Device through which you want to output data
select available device
The device from which you want to generate data. The items in the list vary, depending on which
devices you have connected to your system. Devices in the list are specified by adaptor/vendor name
and unique device ID, followed by the model name of the device, for example, ni Dev1
(USB-6255). The first available device is selected by default. A CompactDAQ chassis is shown as a
single device; vendor name, chassis ID, and chassis model would be shown in the list, for example, ni
cDAQ2 (cDAQ-9172).
Device channel selection and configuration table. The channel configuration table lists the hardware
channels of your device, and lets you select and configure them. Specify which channels to acquire
data from (by default all the channels are selected). The following parameters are specified for each
selected channel:
Channel ID — Hardware channel ID specified by the device. The Channel ID column is read-only,
and the parameters are defined when the device is selected.
Name — Channel name. By default the table displays any names provided by the hardware, but you
can edit the names. For example, if the device is a sound card with two channels, you can name them
Left and Right.
Module — Device ID the channel belongs to. The Module column is read-only. If a CompactDAQ
chassis is selected, it shows the ID of the CompactDAQ module which the channel belongs to;
otherwise the ID of the device.
17-15
17 Blocks
Measurement Type — Measurement type of the channel. This block supports only voltage
measurement types. (For other measurement types, use a DataAcquisition object in MATLAB.)
Output Range — Output ranges available for each channel supported by the hardware, defined
when a device is selected.
1 for all channels (default) — One input port on the block provides data for all channels. Provide
data as a 1-by-N vector for N channels.
1 per channel — N input ports on the block, where N is equal to the number of selected channels.
Provide data as a double value to each port. For naming, each output port uses the channel name if
one was specified, otherwise the channel ID, for example, ao1.
Block sample time, specifies the sample time of the block during the simulation. This is the rate at
which the block is executed during simulation. The default value is 1. For more information, see
“What Is Sample Time?” (Simulink).
Version History
Introduced in R2016b
See Also
Blocks
Analog Input | Analog Output | Analog Input (Single Sample) | Digital Input (Single Sample) | Digital
Output (Single Sample)
17-16
Digital Input (Single Sample)
Description
The Digital Input (Single Sample) block synchronously outputs the latest scan of data available from
the digital lines selected at each simulation time step. It acquires unbuffered digital data, and
delivers this as a vector of boolean values.
The block has no input ports. It has one or more output ports, depending on the option you choose in
its dialog box.
The block inherits the sample time of the model. Digital input acquisition is done synchronously,
according to the following diagram.
At the first time step (T1), data is acquired from the selected hardware lines. The simulation does not
continue until data is read from all lines.
Note To use this block, you need both Data Acquisition Toolbox and Simulink software.
Some devices are not supported by the Simulink blocks in Data Acquisition Toolbox. To see if your
device supports Simulink, refer to Supported Hardware.
• This block supports the use of Simulink Accelerator mode, but not Rapid Accelerator or code
generation.
17-17
17 Blocks
• The block supports the use of model referencing, so that your model can include other Simulink
models as modular components.
Ports
Output
Acquired digital input data, returned as booleans. If using only one output port for all lines, the
output is a 1-by-N vector for N channels. If using a port for each line, each scan results in a single
boolean on each port. Multiple ports are named by line names or device specified line IDs.
Data Types: Boolean
Timestamp of scan, returned as a double. This port is available when you check the Output timestamp
on page 17-0 parameter.
Data Types: double
Parameters
Device — Device from which you want to acquire data
The device from which you want to acquire data. The items in the list vary, depending on which
devices you have connected to your system. Devices in the list are specified by adaptor or vendor
name and unique device ID, followed by the model name of the device, for example, ni Dev1
(USB-6255). The first available device is selected by default. A CompactDAQ chassis would be
shown as a single device identified by vendor name, chassis ID, and chassis model; for example, ni
cDAQ2 (cDAQ-9172).
Line ID — ID of the hardware line (for example, port0/line0). This is automatically detected and filled
in by the selected device, and is read-only.
Name — Hardware line name. This is automatically detected and filled in from the hardware, though
you can edit the name.
Module — Device ID that the line belongs to. The Module column is read-only. If a CompactDAQ
chassis is selected, it shows the ID of the CompactDAQ module which the line belongs to; otherwise
the ID of the device.
17-18
Digital Input (Single Sample)
1 for all lines — The block has only one output port for all of the lines that are selected in the table.
Acquired data is returned as a 1-by-N vector of boolean values, whose size is the number of lines.
1 per line — The block has one output port per selected line. Data is returned as a 1-by-1 boolean
value on each port. The name of each output port is the name specified in the table for each line. If no
name is provided, the name is the Line ID. For example, if line 2 of hardware port 3 is selected, and
you did not specify a name in the line table, port3/line2 appears in the block. Data size for each
line is 1-by-1.
Specifies the sample time of the block during the simulation. This is the rate at which the block is
executed during simulation. The default value is 1 (seconds). For more information, see “What Is
Sample Time?” (Simulink).
Select this option to output the absolute timestamp of the scan. This option adds a new output port to
the block. The data type of this port is double (datenum), which corresponds to a serial date number.
You can convert the datenum into a datetime value with the datetime function.
Version History
Introduced in R2016b
See Also
Blocks
Analog Input | Analog Output | Analog Input (Single Sample) | Analog Output (Single Sample) | Digital
Output (Single Sample)
17-19
17 Blocks
Description
The Digital Output (Single Sample) block synchronously outputs the latest set of data to the hardware
at each simulation time step. It outputs unbuffered digital data. Specify the output data as a vector of
boolean values.
The block has no output ports. It can have one or more input ports, depending on the option you
choose in its dialog box. The data type of the signal at the input port must be a boolean data type.
The Digital Output (Single Sample) block inherits the sample time from the driving block connected
to the input port. Digital output is done synchronously, according to the following diagram.
At the first time step (T1), data is output to the selected hardware lines. The simulation does not
continue until data is output to all lines.
Note To use this block, you need both Data Acquisition Toolbox and Simulink software.
Some devices are not supported by the Simulink blocks in Data Acquisition Toolbox. To see if your
device supports Simulink, refer to Supported Hardware.
• This block supports the use of Simulink Accelerator mode, but not Rapid Accelerator or code
generation.
17-20
Digital Output (Single Sample)
• The block supports the use of model referencing, so that your model can include other Simulink
models as modular components.
Ports
Input
Generated digital output data, specified as booleans. If using only one input port for all lines, provide
a 1-by-N vector of data. If using a port for each line, provide a single value on each port. Multiple
ports are named by line names or device specified line IDs.
Data Types: Boolean
Parameters
Device — Device with which you want to generate data
The device from which you want to acquire data. The items in the list vary, depending on which
devices you have connected to your system. Devices in the list are specified by adaptor or vendor
name and unique device ID, followed by the model name of the device, for example, ni Dev1
(USB-6255). The first available device is selected by default. A CompactDAQ chassis would be
shown as a single device identified by vendor name, chassis ID, and chassis model; for example, ni
cDAQ2 (cDAQ-9172).
Line ID — ID of the hardware line (for example, port0/line0). This is automatically detected and filled
in by the selected device, and is read-only.
Name — Hardware line name. This is automatically detected and filled in from the hardware, though
you can edit the name.
Module — Device ID that the line belongs to. The Module column is read-only. If a CompactDAQ
chassis is selected, it shows the ID of the CompactDAQ module which the line belongs to; otherwise
the ID of the device.
1 for all lines — The block has only one input port for all of the lines that are selected in the table.
Generated data is defined as a 1-by-N row vector of boolean values, whose size is the number of lines.
1 per line — The block has one input port per selected line. The name of each input port is the name
specified in the table for each line. If no name is provided, the name is the Line ID. For example, if
line 2 of hardware port 3 is selected, and you did not specify a name in the line table, port3/line2
appears in the block. Data size for each line is 1-by-1.
17-21
17 Blocks
Specifies the sample time of the block during the simulation. This is the rate at which the block is
executed during simulation. The default value is 1 (seconds). For more information, see “What Is
Sample Time?” (Simulink).
Version History
Introduced in R2016b
See Also
Blocks
Analog Input | Analog Output | Analog Input (Single Sample) | Analog Output (Single Sample) | Digital
Input (Single Sample)
17-22
A
Troubleshooting Tips
In this section...
“Find Devices and Create a DataAcquisition Interface” on page A-2
“Is My Device Driver Supported?” on page A-3
“Cannot Find Hardware Vendor” on page A-3
“Cannot Detect My Device” on page A-4
“Why Doesn’t My NI Hardware Work?” on page A-5
“Why Was My DataAcquisition Object Deleted?” on page A-5
“What Is a Reserved Hardware Error?” on page A-5
“Network Device Appears Unsupported” on page A-5
“Cannot Add Channels” on page A-6
“ADC Overrun Error with External Clock” on page A-6
“Cannot Add Clock Connection to PXI Devices” on page A-6
“Cannot Complete Long Foreground Acquisition” on page A-6
“Cannot Use PXI 4461 and 4462 Together” on page A-6
“Cannot Get Correct Scan Rate with Digilent Devices” on page A-7
“Cannot Simultaneously Acquire and Generate with myDAQ Devices” on page A-7
“Simultaneous Analog Input and Output Not Synchronized Correctly” on page A-7
“Counter Single Scan Returns NaN” on page A-7
“External Clock Will Not Trigger Scan” on page A-7
“Why Does My S/PDIF Device Time Out?” on page A-7
“MOTU Device Not Working Correctly” on page A-7
9×5 table
For more information on the DataAcquisition interface, see “The DataAcquisition Object” on page 3-2.
A-2
Troubleshooting Tips
To learn more about how to communicate with CompactDAQ devices, see “Interface Workflow” on
page 4-2.
v =
5×4 table
If the DriverVersion field does not match the minimum requirements specified on the product page
on the MathWorks website, use the Add-On Manager to update your support package.
If your driver is incompatible with Data Acquisition Toolbox, verify that your hardware is functioning
properly before updating drivers. If your hardware is not functioning properly, you might be using
unsupported drivers.
• NI-DAQmx Drivers
Data Acquisition Toolbox software is compatible with only specific versions of the NI-DAQmx
driver, and is not guaranteed to work with other versions. For a list of the NI-DAQmx driver
versions that are compatible with Data Acquisition Toolbox software, see NI-DAQmx Support from
Data Acquisition Toolbox.
For the latest NI-DAQmx drivers, visit the NI™ website at https://www.ni.com/.
To find your installed driver version in the NI Measurement & Automation Explorer use these
steps:
1 In the Windows taskbar, click Start > NI MAX.
2 In the Measurement & Automation Explorer select Help > System Information.
• Measurement Computing (MCC) Drivers
For a list of the MCC driver versions that are compatible with Data Acquisition Toolbox software,
see Measurement Computing DAQ Support from Data Acquisition Toolbox.
If you try to get vendor information using daqvendorlist, and receive one of the following errors:
• No vendors found:
No data acquisition vendors available.
A-3
A Troubleshooting Tips
There are various reasons that the adaptor can appear as 'Not operational' related to MCC
installation issues. Click the 'Not operational' text link to get its error code. When you have
the error code, see specific troubleshooting steps at Why Does the MCC Data Acquisition Adaptor
Show as 'Not Operational'?
If you try to find information using daqlist and do not see the expected device listed, refresh the
toolbox and get a new device listing with the commands:
daqreset
daqlist
If you still do not see the expected devices, try the following.
• Make sure that your system is properly set up as described in “Set Up Your System for Device
Detection” on page A-10.
• NI Devices
• Go to the NI Measurement & Automation Explorer (NI MAX) and examine your devices to
make sure your device is listed as available.
• If you cannot see your device in NI MAX, check all device connections and power sources.
• If you can see your device in NI MAX, run daqreset and daqlist in MATLAB again.
• If you are using an Ethernet or WiFi network CompactDAQ chassis or FieldDAQ device, reserve
the chassis or device in NI MAX first. Only one system can reserve a network device at any one
time. For more information, see Why can't Data Acquisition Toolbox detect my NI DAQ devices
connected through a cDAQ network chassis?.
• Measurement Computing (MCC) Devices
• If your MCC device does not appear in the output of daqlist, close MATLAB and make sure
that that the device is working correctly in Instacal. You must configure the device in Instacal
before MATLAB can recognize it.
• If your device is still not recognized in MATLAB, make sure your device is supported by
checking Measurement Computing DAQ Support from Data Acquisition Toolbox.
A-4
Troubleshooting Tips
For example, to verify that the analog input subsystem on your PCIe-6363 device is operating,
connect a known signal (similar to the signal produced by a function generator) to one or more
channels, using a screw terminal panel.
If the Test Panel does not provide you with the expected results for the subsystem, and you are sure
that your test setup is configured correctly, then the hardware is not performing correctly.
Identify the DataAcquisition that is currently not using this device but has reserved it, and release the
associated hardware resources. If the device is reserved by:
A-5
A Troubleshooting Tips
reconnect the device in the NI Measurement and Automation Explorer and execute daqreset in
MATLAB to reset the devices settings.
• Note Your network device might also appear as unsupported in the device information if it is
reserved or disconnected.
• Using an output device to add input channels, or an input device to add output channels.
• Using an unsupported device. See “Data Acquisition Toolbox Supported Hardware”.
• Counter Channels
If you are using an NI 9402 with a counter/timer subsystem in a cDAQ-9172 chassis, plug the
module only into slot 5 or 6. If you plug the module into any other slot, it will not show any
counter/timer subsystem.
NI DSA devices like the PXI 447x, do not support sample clock synchronization. You cannot
synchronize these devices in the DataAcquisition interface using addclock.
A-6
Troubleshooting Tips
• Make sure that the signal voltage complies with TTL voltage specifications.
• Make sure that the channel frequency is within the specified frequency range.
• If you add this device (port) to your DataAcquisition and you have no device plugged into the port,
the operation times out.
• If you have a device plugged into the S/PDIF port, you may need to match the DataAcquisition rate
to the device scan rate to get accurate readings. Refer to your device documentation for
information.
• In your MOTU Audio Console, select the Use Stereo Pairs for Windows Audio check box.
• Specify the required sample rate in the Sample Rate field.
A-7
A Troubleshooting Tips
See Also
Functions
daqvendorlist | daqlist | daqreset
Related Examples
• “Set Up Your System for Device Detection” on page A-10
• “Limitations by Vendor” on page B-2
A-8
Contact MathWorks for Technical Support
Before contacting MathWorks, you should run the daqsupport function in MATLAB. This function
returns diagnostic information such as:
The output from daqsupport is automatically saved to a text file, which you can use to help
troubleshoot your problem or send to MathWorks technical support if requested.
A-9
A Set Up Your System for Device Detection
For interfacing with your device from MATLAB and Data Acquisition Toolbox, you must have the
required support package, drivers, and sometimes third-party apps installed. See the following
sections for your particular vendor to set up your system or to troubleshoot device discovery issues.
NI Devices
• Make sure the supported NI-DAQmx version is installed. You can install the Data Acquisition
Toolbox Support Package for National Instruments NI-DAQmx Devices using Add-On Explorer.
• Reboot the computer after the NI-DAQmx support package installation completes.
• If the support package fails to install or if you are using a MATLAB release that does not have a
support package for NI-DAQmx, you can install NI-DAQmx separately from MATLAB as described
in Why does "Data Acquisition Toolbox Support Package for National Instruments NI-DAQmx
Devices" fail to install?
• Confirm that the "ni" vendor is listed as operational by daqvendorlist.
• Confirm that you are using the supported NI-DAQmx driver version.
• Data Acquisition Toolbox software is compatible with only specific versions of the NI-DAQmx
driver, and is not guaranteed to work with other versions. For a list of the NI-DAQmx driver
versions that are compatible with Data Acquisition Toolbox, see the driver version table in the
“Required Products and Hardware section” in NI-DAQmx Support from Data Acquisition
Toolbox.
• You can find the installed NI-DAQmx driver version with daqvendorlist or in the NI
Measurement & Automation Explorer (NI MAX).
• If an unsupported NI-DAQmx version is currently installed on the computer, you can:
1 Uninstall it from NI Package Manager from Windows Control Panel > Programs > Uninstall a
program.
2 Install the supported NI-DAQmx version as described above.
• If you are using an Ethernet or WiFi network CompactDAQ chassis or FieldDAQ device, first
reserve the chassis or device in NI MAX. Only one system can reserve a network device at any one
time. For more information, see Why can't Data Acquisition Toolbox detect my NI DAQ devices
connected through a cDAQ network chassis?
A-10
Set Up Your System for Device Detection
• Some audio interface devices require the installation of DirectSound compatible drivers provided
by the device vendor.
• Audio input devices might require connecting a microphone to be detected correctly.
• Verify that your audio device is detected and operating as expected when using other applications
that use DirectSound, such as Audacity.
• Data Acquisition Toolbox software is compatible with only specific versions of the MCC DAQ
driver (Instacal), and is not guaranteed to work with other versions. For a list of the driver
versions that are compatible with Data Acquisition Toolbox, see the driver version table in the
“Required Products and Hardware” section of Measurement Computing DAQ Support from
Data Acquisition Toolbox.
• You can find the installed Instacal version with the Instacal app or with the MATLAB function
daqvendorlist.
• If an unsupported Instacal version is currently installed on the computer, you can:
1 Uninstall it from Windows Control Panel > Programs > Uninstall a program.
2 Uninstall the Data Acquisition Toolbox Support Package for Measurement Computing
Hardware using Add-On Manager.
3 Install the Data Acquisition Toolbox Support Package for Measurement Computing Hardware
using Add-On Explorer.
• Open the Instacal app and configure your device. The device must be configured in Instacal before
MATLAB can recognize it.
• Data Acquisition Toolbox software is compatible with only specific versions of the Digilent
WaveForms driver, and is not guaranteed to work with other versions. For a list of the driver
versions that are compatible with Data Acquisition Toolbox, see the driver version table in the
“Required Products and Hardware” section in Digilent Analog Discovery Support from
MATLAB.
• You can find the installed WaveForms version with daqvendorlist or in Digilent Waveforms.
• If an unsupported Waveforms version is currently installed on the computer, you can:
1 Uninstall it from Windows Control Panel > Programs > Uninstall a program.
2 Uninstall the Data Acquisition Toolbox Support Package for Digilent Analog Discovery
Hardware using Add-On Manager
A-11
A Set Up Your System for Device Detection
3 Install the Data Acquisition Toolbox Support Package for Digilent Analog Discovery Hardware
using Add-On Explorer.
• Confirm that the device is detected by Digilent WaveForms.
See Also
Functions
daqvendorlist | daqlist | daqreset
Related Examples
• “Troubleshooting Tips” on page A-2
• “Limitations by Vendor” on page B-2
A-12
B
Limitations by Vendor
For some vendors, there are limitations in the toolbox support for their functionality. See the
following topics for each vendor.
See Also
More About
• “Set Up Your System for Device Detection” on page A-10
• “Troubleshooting Tips” on page A-2
B-2
National Instruments Hardware Limitations
• The first time the command is used with the object, the corresponding subsystem of the device
is reserved by the DataAcquisition object in MATLAB.
• If you then try to access that subsystem in a different MATLAB DataAcquisition, or any other
application from the same computer, you might receive an error message informing you that
the subsystem is reserved. Use release to unreserve the subsystem from the other
DataAcquisition.
• You cannot acquire and generate synchronous data using myDAQ devices because they do not
share a hardware clock. If you have both input and output channels in a DataAcquisition, when
you start it you achieve near-simultaneous acquisition and generation. See “Automatic
Synchronization” on page 13-4 for more information.
• NI USB devices that have their own power supply can shut down if the driver does not set the
USB power correctly.
• Data Acquisition Toolbox does not support direct access to device onboard clocks for clocked
sampling when using only digital input/output channels with a DataAcquisition object. For
workarounds and information on clocked digital sampling, see the following topics:
B-3
B Digilent Analog Discovery Hardware Limitations
Data Acquisition Toolbox conforms to the Digilent Player Mode for the Arbitrary Waveform
Generator.
• You cannot use background operations with Digilent devices. You can only perform foreground
operations.
• You cannot perform synchronous and triggered operations using a Digilent device.
• You cannot access the digital input and output capabilities of a Digilent device.
B-4
Measurement Computing Hardware Limitations
B-5
B Analog Devices ADALM1000 Limitations
B-6
Examples by Vendor
Examples by Vendor
See the following topics for examples of each hardware vendor.
B-7
B Analog Devices ADALM1000 Examples
See Also
More About
• “Digilent Analog Discovery Hardware Examples” on page B-9
• “Measurement Computing Hardware Examples” on page B-10
• “National Instruments Hardware Examples” on page B-11
• “Windows Sound Card Examples” on page B-13
B-8
Digilent Analog Discovery Hardware Examples
“Getting Started Generating Data with Digilent Analog Discovery” on page 18-71
“Acquiring and Generating Data at the Same Time with Digilent Analog Discovery” on page 18-73
“Generate Standard Periodic Waveforms Using Digilent Analog Discovery” on page 18-76
“Generate Arbitrary Periodic Waveforms Using Digilent Analog Discovery” on page 18-79
See Also
More About
• “Analog Devices ADALM1000 Examples” on page B-8
• “Measurement Computing Hardware Examples” on page B-10
• “National Instruments Hardware Examples” on page B-11
• “Windows Sound Card Examples” on page B-13
B-9
B Measurement Computing Hardware Examples
“Acquire Data from Multiple Channels using an MCC Device” on page 18-22
See Also
More About
• “Analog Devices ADALM1000 Examples” on page B-8
• “Digilent Analog Discovery Hardware Examples” on page B-9
• “National Instruments Hardware Examples” on page B-11
• “Windows Sound Card Examples” on page B-13
B-10
National Instruments Hardware Examples
“Acquire and Analyze Sound Pressure Data From an IEPE Microphone” on page 18-37
“Communicate with I2C Devices and Analyze Bus Signals Using Digital IO” on page 18-118
B-11
B National Instruments Hardware Examples
See Also
More About
• “Analog Devices ADALM1000 Examples” on page B-8
• “Digilent Analog Discovery Hardware Examples” on page B-9
• “Measurement Computing Hardware Examples” on page B-10
• “Windows Sound Card Examples” on page B-13
B-12
Windows Sound Card Examples
See Also
More About
• “Analog Devices ADALM1000 Examples” on page B-8
• “Digilent Analog Discovery Hardware Examples” on page B-9
• “Measurement Computing Hardware Examples” on page B-10
• “National Instruments Hardware Examples” on page B-11
B-13
18
18-2
Getting Started with NI Devices
This example shows how to get started with National Instruments devices from the command line.
Discover devices connected to your system using daqlist. To learn more about an individual device,
access the entry in the device table.
d = daqlist;
d(1, :)
ans =
1×5 table
d{1, "DeviceInfo"}
ans =
This module is in slot 1 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
Create a DataAcquisition
The daq command creates a DataAcquisition object. The DataAcquisition contains information
describing hardware, scan rate, and other properties associated with the acquisition.
dq = daq("ni")
dq =
Running: 0
Rate: 1000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
18-3
18 Data Acquisition Toolbox Examples
RateLimit: []
Show channels
Show properties and methods
ch = addinput(dq,"cDAQ1Mod1", "ai0","Voltage")
ch =
The read command starts the acquisition and returns the results as a timetable.
Plot Data
plot(data.Time, data.cDAQ1Mod1_ai0);
ylabel("Voltage (V)");
18-4
Getting Started with NI Devices
By default, run at a scan rate of 1000 scans per second. To acquire at a higher rate, change the Rate
property.
dq.Rate = 5000;
18-5
18 Data Acquisition Toolbox Examples
18-6
Getting Started with MCC Devices
This example shows how to get started with MCC devices from the command line.
Discover devices connected to your system using daqlist. To learn more about an individual device,
access the entry in the device table.
d = daqlist("mcc");
d(1, :)
ans =
1×4 table
Create a DataAcquisition
The daq function creates a DataAcquisition object. The DataAcquisition contains information
describing hardware, scan rate, and other properties associated with the acquisition.
dq = daq("mcc")
dq =
Running: 0
Rate: 1000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
The addinput function attaches an input channel to the DataAcquisition. You can add more than one
channel to a DataAcquisition. This example uses one input channel, Ai0, which is connected to a
function generator channel outputting a 10 Hz sine wave.
addinput(dq, "Board0", "Ai0", "Voltage");
dq
dq =
18-7
18 Data Acquisition Toolbox Examples
Running: 0
Rate: 1000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: [0.1000 100000]
Show channels
Show properties and methods
The read function starts the acquisition and returns the results as a timetable.
plot(data.Time, data.Board0_Ai0);
xlabel("Time (s)");
ylabel("Voltage (V)");
18-8
Getting Started with MCC Devices
By default, acquisitions run for one second at 1000 scans per second. To acquire at a different rate,
change the Rate property.
dq.Rate = 5000;
18-9
18 Data Acquisition Toolbox Examples
Discover NI Devices
This example shows how to discover National Instruments devices visible to MATLAB® and get
information about channel and measurement types available in those devices.
Use daqlist to display a list of devices available to your machine and MATLAB.
d = daqlist("ni")
d =
12×4 table
The daqlist command shows you the overview of devices available. To obtain more information
about a particular device, view the "DeviceInfo" table cell for it.
deviceInfo =
This module is in slot 1 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
18-10
Discover NI Devices
When the hardware configuration changes (for example, a new CompactDAQ module is plugged into
the chassis), use daqreset followed by daqlist to observe the changes.
18-11
18 Data Acquisition Toolbox Examples
This example shows how to discover devices visible to MATLAB and get information about channel
and measurement types available in those devices.
v = daqvendorlist
v =
1×4 table
d = daqlist("mcc")
d =
1×4 table
The daqlist command shows you the overview of devices available. You can find additional device
details by reviewing the DeviceInfo field of the table.
deviceInfo =
18-12
Discover MCC Devices
Use the Subsystems property to find all the subsystem information. To display all details about the
first subsystem including the channel, type:
deviceInfo.Subsystems
ans =
When you change your hardware configuration (for example, plug in a new USB device), first detect
the device in InstaCal. Then, use the daqreset command to refresh Data Acquisition toolbox before
using daqlist to discover the changes.
18-13
18 Data Acquisition Toolbox Examples
This example shows how to acquire data from a National Instruments device.
To discover a device that supports input measurements, access the device in the table returned by the
daqlist command. This example uses an NI 9201 module in a National Instruments® CompactDAQ
Chassis NI cDAQ-9178. This is an 8 channel analog input device and is module 4 in the chassis.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 4 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
Create a DataAcquisition, set the Rate property (the default is 1000 scans per second), and add
analog input channels using addinput.
dq = daq("ni");
dq.Rate = 8000;
18-14
Acquire Data Using NI Devices
Use read to acquire a single scan. The result is a table with two data columns because two input
channels are used to acquire the scan.
tabledata = read(dq)
tabledata =
1×2 timetable
Use read to acquire a single scan. The result is an array of size 1x2 because two input channels are
used to acquire the scan.
matrixdata =
1.0e-03 *
0.1270 0.9134
Use read to acquire multiple scans, blocking MATLAB execution until all the data requested is
acquired. The acquired data is returned as a timetable with width equal to the number of channels
and height equal to the number of scans.
plot(data.Time, data.Variables);
ylabel("Voltage (V)")
18-15
18 Data Acquisition Toolbox Examples
18-16
Acquire Data Using NI Devices
18-17
18 Data Acquisition Toolbox Examples
This example shows how to acquire analog input data using non-blocking commands. This allows you
to continue working in the MATLAB command window during the acquisition. This is called
background acquisition. Use foreground acquisition to cause MATLAB to wait for the entire
acquisition to complete before you can execute your next command.
Use daq to create a DataAcquisition object and addinput to add an input channel to it. This example
uses an NI 9205 module in National Instruments® CompactDAQ Chassis NI cDAQ-9178. This is
module 1 in the chassis.
dq = daq("ni");
addinput(dq, "cDAQ1Mod1", "ai0", "Voltage");
dq.Rate = 2000;
During a background acquisition, the DataAcquisition can handle acquired data in a specified way
using the ScansAvailableFcn property.
Set ScansAvailableFcnCount
dq.ScansAvailableFcnCount = 2000;
There are no other calculations to perform and the acquisition is set to run for the entire five seconds.
Use pause in a loop to monitor the number of scans acquired for the duration of the acquisition.
while dq.Running
pause(0.5)
fprintf("While loop: Scans acquired = %d\n", dq.NumScansAcquired)
end
18-18
Acquire Continuous and Background Data Using NI Devices
Acquire continuously until a specific condition is met. In this example, acquire until the signal equals
or exceeds 1 V.
Configure the DataAcquisition to acquire continuously. The listener detects the 1V event and calls
stop.
start(dq, "continuous");
Use pause in a loop to monitor the number of scans acquired for the duration of the acquisition. Note
that the status string displayed by the ScansAvailableFcn may appear before the last status string
displayed by the while loop.
while dq.Running
pause(0.5)
fprintf("While loop: Scans acquired = %d\n", dq.NumScansAcquired)
end
dq.ScansAvailableFcn = [];
18-19
18 Data Acquisition Toolbox Examples
function plotDataAvailable(src, ~)
[data, timestamps, ~] = read(src, src.ScansAvailableFcnCount, "OutputFormat", "Matrix");
plot(timestamps, data);
end
function stopWhenEqualsOrExceedsOneV(src, ~)
[data, timestamps, ~] = read(src, src.ScansAvailableFcnCount, "OutputFormat", "Matrix");
if any(data >= 1.0)
disp('Detected voltage exceeds 1V: stopping acquisition')
% stop continuous acquisitions explicitly
src.stop()
plot(timestamps, data)
else
disp('Continuing to acquire data')
end
end
18-20
Acquire Continuous and Background Data Using NI Devices
18-21
18 Data Acquisition Toolbox Examples
This example shows how to acquire data from multiple analog input channels with an MCC device.
Hardware Setup
This example uses a Measurement Computing USB-1608FS-Plus device to log data from analog input
channels 0 and 9, which are connected to the outputs of a function generator.
d = daqlist("mcc")
d =
1×4 table
The daqlist function shows you the overview of devices available. You can find additional device
details by reviewing the DeviceInfo field of the table.
deviceInfo =
The daq function creates a DataAcquisition object. The DataAcquisition contains information
describing hardware, scan rate, and other properties associated with the acquisition.
dq = daq("mcc")
18-22
Acquire Data from Multiple Channels using an MCC Device
dq =
Running: 0
Rate: 1000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
The read function starts the acquisition and returns the results as a timetable.
18-23
18 Data Acquisition Toolbox Examples
By default, acquisitions run for one second at 1000 scans per second. To acquire at a different rate,
change the Rate property.
dq.Rate = 10000;
[data, startTime] = read(dq, seconds(1));
plot(data.Time, data.Board0_Ai0, data.Time, data.Board0_Ai1);
xlabel('Time (s)');
ylabel('Voltage (V)');
18-24
Acquire Data from Multiple Channels using an MCC Device
18-25
18 Data Acquisition Toolbox Examples
This example shows how to acquire and display data from an accelerometer attached to a vehicle
driven under uneven road conditions.
To discover a device that supports accelerometers, access the device in the table returned by the
daqlist command. This example uses National Instruments® CompactDAQ Chassis NI cDAQ-9178
and module NI 9234 with ID cDAQ1Mod3.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 3 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
Create a DataAcquisition, and add an analog input channel with Accelerometer measurement type.
dq = daq("ni");
ch = addinput(dq, "cDAQ1Mod3", "ai0", "Accelerometer");
18-26
Acquire Data from an Accelerometer
dq.Rate = 4000;
You must set the Sensitivity value to the value specified in the accelerometer's data sheet. This
example uses a ceramic shear accelerometer model 352C22 from PCB Piezotronics with 9.22 mV per
gravity.
ch.Sensitivity = 0.00922;
ch
ch =
18-27
18 Data Acquisition Toolbox Examples
This example shows how to acquire bridge circuit voltage ratio data using a CompactDAQ module,
then compute and plot strain values. This example does not apply to USB devices such as the NI
USB-9219.
To discover a device that supports bridge sensor measurements, access the device in the array
returned by daqlist command. For this example use National Instruments® CompactDAQ Chassis
NI cDAQ-9178 and module NI 9219 with ID cDAQ1Mod7.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 7 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
Create a DataAcquisition and add an analog input channel with the Bridge measurement type. There
are two strain gauges connected to the NI 9219 in half bridge configuration.
18-28
Measure Strain Using an Analog Bridge Sensor
dq = daq("ni");
dq.Rate = 10;
ch = addinput(dq, "cDAQ1Mod7", "ai0", "Bridge");
You must set the bridge mode according to the bridge circuit configuration and the nominal
resistance to the value specified by the strain gauge datasheet. In this example, the strain gauges
used are the SGD-3/350-LY13 linear strain gauges from Omega®, with a nominal resistance of 350
ohms, and the bridge is configured as a half-bridge.
ch.BridgeMode = "Half";
ch.NominalBridgeResistance = 350;
Set ADCTimingMode
By default, the ADC timing mode ADCTimingMode of the channel is set to 'HighResolution'. Set
the ADCTimingMode to 'HighSpeed'.
ch.ADCTimingMode = "HighSpeed";
Acquire Data
This data is used to compute strain values using a conversion formula (as determined by your bridge
configuration).
strain = -2*Vr/GF
where GF is gauge factor provided in the sensor data sheet and Vr is the voltage ratio output as
measured by your bridge channel.
Assume negligible lead wire resistance in this case. For the strain gauge used in this example, GF =
2.13.
GF = 2.13;
strain = -2*data.cDAQ1Mod7_ai0/GF;
plot(data.Time, strain);
xlabel('Time (s)');
ylabel('Strain');
18-29
18 Data Acquisition Toolbox Examples
18-30
Acquire Temperature Data From a Thermocouple
This example shows how to read data from NI devices that support thermocouple measurements.
To discover a device that supports thermocouple measurements, access the device in the table
returned by the daqlist command. This example uses an NI 9213 device. This is a 16 channel
thermocouple module and is module 6 in the chassis.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 6 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
Create a DataAcquisition, change its scan Rate to four scans per second, and add an analog input
channel with Thermocouple measurement type.
18-31
18 Data Acquisition Toolbox Examples
dq = daq("ni");
dq.Rate = 4;
ch = addinput(dq, "cDAQ1Mod6", "ai0", "Thermocouple");
Set the thermocouple type to K and units to Kelvin (the thermocouple type should match the sensor
configuration).
ch.ThermocoupleType = 'K';
ch.Units = 'Kelvin';
ch
ch =
18-32
Acquire Temperature Data From a Thermocouple
18-33
18 Data Acquisition Toolbox Examples
This example shows how to acquire temperature data from a Resistive temperature device (RTD) and
display the readings. The device is attached inside a PC case to monitor the internal temperature
changes.
To discover a device that supports bridge sensor measurements, access the device in the table
returned by the daqlist command. This example uses an NI 9219 module in National Instruments®
CompactDAQ Chassis NI cDAQ-9178. This is a 24-Bit Universal Analog Input module and is module 7
in the chassis.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 7 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
Create a DataAcquisition, and add an analog input channel with RTD measurement type.
18-34
Acquire Temperature Data From an RTD
dq = daq("ni");
dq.Rate = 30;
ch = addinput(dq, "cDAQ1Mod7", "ai3", "RTD");
Refer to the sensor data sheet and match the values accordingly. In this example, an SA1-RTD series
sensor from Omega® is used. Set units to "Fahrenheit", RTD type to "Pt3851", configure the RTD
circuit as "FourWire", and set the resistance to 100 ohms.
ch.Units = "Fahrenheit";
ch.RTDType = "Pt3851";
ch.RTDConfiguration = "FourWire";
ch.R0 = 100;
Set ADCTimingMode
By default, the ADC timing mode ADCTimingMode of the channel is set to "HighResolution". Set
the ADCTimingMode to "HighSpeed".
ch.ADCTimingMode = "HighSpeed";
18-35
18 Data Acquisition Toolbox Examples
18-36
Acquire and Analyze Sound Pressure Data From an IEPE Microphone
This example shows how to acquire and display sound pressure data from a PCB® IEPE array
microphone, Model 130E20. The sensor is recording sound pressure generated by a tuning fork at
Middle C (261.626 Hz) frequency.
To discover a device that supports microphone measurements, access the device in the table returned
by the daqlist command. For this example, the microphone is connected on channel 0 of National
Instruments® device NI 9234 on CompactDAQ Chassis NI cDAQ-9178 with ID cDAQ1Mod3.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 3 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
18-37
18 Data Acquisition Toolbox Examples
dq = daq("ni");
ch = addinput(dq, "cDAQ1Mod3", "ai0", "Microphone");
Set the microphone channel Sensitivity property to the value specified in the sensor's data sheet.
For this sensor, the Sensitivity value is 0.037 Volts/Pascal. Examine the channel properties to see
the changes in the device configuration.
ch.Sensitivity = 0.037;
ch
ch =
Set the acquisition scan rate to 51200 scans per second, then use read to acquire four seconds of
data.
dq.Rate = 51200;
tt = read(dq, seconds(4));
t = tt.Time;
data = tt.cDAQ1Mod3_ai0;
Analyze Data
p = audioplayer(data, dq.Rate);
play(p);
plot(t, data);
ylabel('Sound Pressure (pascals)');
18-38
Acquire and Analyze Sound Pressure Data From an IEPE Microphone
Use fft and the following parameters to calculate the single-sided amplitude spectrum of the
incoming data:
len = height(tt);
nfft = 2^nextpow2(len);
y = fft(data,nfft)/len;
f = dq.Rate/2*linspace(0,1,nfft/2+1);
A = 2*abs(y(1:nfft/2+1));
plot(f,A);
xlim([0 1000]);
xlabel('Frequency (Hz)');
ylabel('Amplitude');
18-39
18 Data Acquisition Toolbox Examples
The plot shows a spike at 261.626 Hz. This matches the frequency of the tuning fork.
18-40
Acquire and Analyze Noisy Clock Signals
This example shows how to acquire clock signals and analyze transitions, pulses, and compute
metrics including rise time, fall time, slew rate, overshoot, undershoot, pulse width, and duty cycle.
This example uses Data Acquisition Toolbox in conjunction with the Signal Processing Toolbox.
Use Data Acquisition Toolbox to configure the acquisition. Use the statistics and measurement
functions in Signal Processing Toolbox to analyze the data signal.
Use daq to create a DataAcquisition and addinput to add a channel from the National Instruments®
NI-9205 with ID of 'cDAQ1Mod1'.
dq = daq("ni");
addinput(dq,"cDAQ1Mod1","ai0","Voltage");
dq.Rate = 250000;
plot(time, data)
xlabel('Time (s)')
ylabel('Voltage (V)')
18-41
18 Data Acquisition Toolbox Examples
Use statelevels with no output argument to visualize the state levels in a histogram.
statelevels(data)
ans =
0.0138 5.1848
18-42
Acquire and Analyze Noisy Clock Signals
The computed histogram is divided into two equal sized regions between the first and last bin. The
mode of each region of the histogram is returned as an estimated state level value in the command
window.
Use optional input arguments to specify the number of histogram bins, histogram bounds, and the
state level estimation method.
Use risetime with no output argument to visualize the rise time of positive edges.
risetime(data,time)
ans =
1.0e-04 *
0.5919
0.8344
0.7185
0.8970
0.6366
18-43
18 Data Acquisition Toolbox Examples
The default reference levels for computing rise time and fall time are set at 10% and 90% of the
waveform amplitude.
ans =
1.0e-04 *
0.4294
0.5727
0.5032
0.4762
18-44
Acquire and Analyze Noisy Clock Signals
Obtain measurements programmatically by calling functions with one or more output arguments. For
uniformly sampled data, you can provide a sample rate in place of the time vector. Use slewrate to
measure the slope of each positive or negative edge.
sr = slewrate(data(1:100), dq.Rate)
sr =
7.0840e+04
18-45
18 Data Acquisition Toolbox Examples
overshoot(data(95:270),dq.Rate)
legend('Location','NorthEast')
ans =
4.9451
2.5399
18-46
Acquire and Analyze Noisy Clock Signals
Overshoot can also occur just before an edge, at the end of the pre-transition aberration region. This
is called "preshoot" overshoot.
Undershoot can occur in the pre-aberration and post-aberration regions and is expressed as a
percentage of the difference between the state levels. Measure the undershoot with optional input
arguments specifying the region to measure aberrations.
undershoot(data(95:270),dq.Rate,'Region','Postshoot')
legend('Location','NorthEast')
ans =
3.8499
4.9451
18-47
18 Data Acquisition Toolbox Examples
18-48
Acquire and Analyze Noisy Clock Signals
This displays pulses of positive polarity. Select negative polarity to see the widths of negative polarity
pulses.
Use dutycycle to compute the ratio of the pulse width to the pulse period for each positive-polarity
or negative-polarity pulse. Duty cycles are expressed as a percentage of the pulse period.
d = dutycycle(data,time,'Polarity','negative')
d =
0.4979
0.5000
0.5000
Use pulseperiod to obtain the periods of each cycle of the waveform. Use this information to
compute other metrics such as the average frequency of the waveform or the total observed jitter.
pp = pulseperiod(data, time);
avgFreq = 1./mean(pp)
totalJitter = std(pp)
avgFreq =
1.2500e+03
18-49
18 Data Acquisition Toolbox Examples
totalJitter =
1.9866e-06
18-50
Generate Voltage Signals Using NI Devices
This example shows how to generate data using a National Instruments device.
To discover a device that supports analog outputs, access the device in the table returned by the
daqlist command. This example uses an NI 9263 module in National Instruments® CompactDAQ
Chassis NI cDAQ-9178. This is module 2 in the chassis.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 2 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
Create a DataAcquisition, set the generation scan rate by setting the Rate property (the default is
1000 scans per second), and add analog output channels using addoutput.
dq = daq("ni");
dq.Rate = 8000;
18-51
18 Data Acquisition Toolbox Examples
Use write to generate a single scan (2 V on each channel). The output scan data is a 1-by-N matrix
where N corresponds to the number of output channels.
output = 2;
write(dq,[output output]);
Generate two output signals (a 1 Hz sine wave and a 1 Hz ramp) and plot them. The plot depicts the
data generated on both channels for a device that supports simultaneous sampling.
n = dq.Rate;
outputSignal1 = sin(linspace(0,2*pi,n)');
outputSignal2 = linspace(-1,1,n)';
outputSignal = [outputSignal1 outputSignal2];
plot(1:n, outputSignal);
ylabel("Voltage (V)");
legend("Analog Output 0", "Analog Output 1");
Write Data
18-52
Generate Voltage Signals Using NI Devices
write(dq, outputSignal)
18-53
18 Data Acquisition Toolbox Examples
This example shows how to generate signals on an analog current output channel of an NI device.
To discover a device that outputs current, access the device in the table returned by the daqlist
command. This example uses an NI 9265 module in a National Instruments® CompactDAQ Chassis
NI cDAQ-9178. This is a 4-channel analog current output device and is module 8 in the chassis.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
This module is in slot 8 of the 'cDAQ-9178' chassis with the name 'cDAQ1'.
dq = daq("ni");
dq.Rate = 100;
18-54
Generate Signals on NI Devices That Output Current
The channels of the NI 9265 have a range of 0 to 20 mA. Produce a ramp from 0 to 20 mA on channel
1, and a constant 10 mA on channel 2. For each waveform, use enough points to generate 10 seconds
of output data at the specified scan rate.
n = 10 * dq.Rate;
data1 = linspace(20e-6, 20e-3, n)';
data2 = repmat(10e-3, n, 1);
data = [data1 data2];
plot(1:n, data)
grid on
xlabel('Data Points')
ylabel('A')
legend('data1','data2')
write(dq, data)
18-55
18 Data Acquisition Toolbox Examples
To reduce the duration of the output, increase the generation scan rate. For one second of output,
change the Rate to the number of samples in the scan.
dq.Rate = n;
write(dq, data)
18-56
Generate Continuous and Background Signals Using NI Devices
This example shows how to generate analog output data using non-blocking commands. This allows
you to continue working in the MATLAB command window during the generation. This is called
background generation. Use foreground generation to cause MATLAB to wait for the entire data
generation to complete before you can execute your next command.
Use daq to create a DataAcquisition. This example uses an NI 9263 module in National Instruments®
CompactDAQ Chassis NI cDAQ-9178. This is module 2 in the chassis. Output data on three channels
at a rate of 10000 scans per second.
dq = daq("ni");
dq.Rate = 10000;
addoutput(dq, "cDAQ1Mod2", 0:2, "Voltage");
Generate output signals by creating a pattern of data that is repeatedly written to the output device.
The data for each channel is column based and the output signals are synchronized to a common
clock.
Create 3 waveforms:
The above waveform contains sin(0) and sin(2*pi). To repeat the waveform coherently, omit the final
point.
data0(end) = [];
data1(end) = [];
data2(end) = [];
At a generation rate of 10000 scans per second, you can expect to observe data0 and data1 as 10
Hz sine waves and data2 as a 100 Hz sine wave.
subplot(3,1,1)
plot(data0)
title('data0')
grid on
subplot(3,1,2)
plot(data1)
title('data1')
grid on;
subplot(3,1,3)
plot(data2)
title('data2')
grid on;
18-57
18 Data Acquisition Toolbox Examples
Before starting a continuous generation, preload half a second of data. Use start to initiate the
generation and return control to the command line immediately, allowing you to do other operations
in MATLAB while the generation is running in the background.
preload(dq,repmat([data0, data1, data2], 5, 1));
start(dq, "repeatoutput")
Use pause in a loop to monitor the number of scans output by the hardware for the duration of the
generation.
t = tic;
while toc(t) < 1.0
pause(0.1)
fprintf("While loop: scans output by hardware = %d\n", dq.NumScansOutputByHardware)
end
18-58
Generate Continuous and Background Signals Using NI Devices
Background generation runs simultaneously with other operations in MATLAB. Explicitly call stop to
end the background generation.
stop(dq)
To dynamically generate the output data using a MATLAB function, assign the function to the
ScansRequiredFcn of the DataAcquisition. The code below is functionally equivalent to
'repeatoutput'
start(dq, "continuous")
18-59
18 Data Acquisition Toolbox Examples
This example shows how to acquire and generate data using two National Instruments modules
operating at the same time.
Create a DataAcquisition
dq = daq("ni")
dq =
Running: 0
Rate: 1000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
Set up Hardware
This example uses a compactDAQ chassis NI c9178 with NI 9205 (cDAQ1Mod1 - 4 analog input
channels) module and NI 9263 (cDAQ1Mod2 - 4 analog output channels) module. Use daqlist to
obtain more information about connected hardware.
The analog output channels are physically connected to the analog input channels so that the
acquired data is the same as the data generated from the analog output channel.
Use addinput to add an analog input voltage channel. Use addoutput to add an analog output
voltage channel.
output = cos(linspace(0,2*pi,1000)');
plot(output);
title("Output Data");
18-60
Simultaneously Acquire Data and Generate Signals
plot(data1.Time, data1.Variables);
ylabel("Voltage (V)")
title("Acquired Signal");
18-61
18 Data Acquisition Toolbox Examples
plot(data2.Time, data2.Variables);
ylabel("Voltage (V)")
title("Acquired Signal");
18-62
Simultaneously Acquire Data and Generate Signals
18-63
18 Data Acquisition Toolbox Examples
This example shows how to save data acquired in the background to a file.
Create a DataAcquisition and add two analog input channels with Voltage measurement type. For
this example use a National Instruments® X Series data acquisition device, NI PCIe-6363 card with
ID Dev1.
d = daqlist("ni")
d =
12×4 table
deviceInfo =
Digital IO supports:
39 channels ('port0/line0' - 'port2/line6')
'InputOnly','OutputOnly','Bidirectional' measurement types
18-64
Log Analog Input Data to a File Using NI Devices
dq = daq("ni");
addinput(dq, "Dev1", 0:1, "Voltage");
dq.Channels
ans =
Create the file log.bin and open it. The file identifier is used to write to the file.
fid1 = fopen("log.bin","w");
During a background acquisition, the DataAcquisition can be directed to handle acquired data in a
specified way using the ScansAvailableFcn property.
During normal operation, other MATLAB commands can execute during this acquisition. For this
example, use pause in a loop to monitor the number of scans acquired for the duration of the
acquisition.
while dq.Running
pause(0.5)
fprintf("While loop: Scans acquired = %d\n", dq.NumScansAcquired)
end
fclose(fid1);
18-65
18 Data Acquisition Toolbox Examples
fid2 = fopen('log.bin','r');
[data,count] = fread(fid2,[3,inf],'double');
fclose(fid2);
t = data(1,:);
ch = data(2:3,:);
plot(t, ch);
18-66
Log Analog Input Data to a File Using NI Devices
18-67
18 Data Acquisition Toolbox Examples
This example shows you how to acquire voltage data at a rate of 300 kHz. The input waveform is a
sine wave (10 Hz, 2 Vpp) provided by an external function generator.
ans =
1×4 table
"AD1" "Digilent Inc. Analog Discovery 2 Kit Rev. C" "Analog Discovery 2" [1×1 daq
dq =
Running: 0
Rate: 10000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
Add an analog input channel with device ID AD1 and channel ID 1. Set the measurement type to
Voltage.
ch_in = addinput(dq, "AD1", "1", "Voltage");
Set the acquisition rate to 300 kHz and the dynamic range of the incoming signal to -2.5 to 2.5 volts.
ch_in.Name = "AD1_1_in"
rate = 300e3;
dq.Rate = rate;
ch_in.Range = [-2.5 2.5];
ch_in =
18-68
Getting Started Acquiring Data with Digilent Analog Discovery
Acquire a single scan on-demand, displaying the data and trigger time.
singleReading =
timetable
Time AD1_1_in
_____ ________
0 sec -0.37211
startTime =
datetime
21-Nov-2019 16:56:50.631
plot(data.Time, data.AD1_1_in);
xlabel('Time (s)');
ylabel('Voltage (V)');
title(['Clocked Data Triggered on: ' datestr(startTime)]);
18-69
18 Data Acquisition Toolbox Examples
18-70
Getting Started Generating Data with Digilent Analog Discovery
This example shows you how to generate voltage data at a rate of 300 kHz.
Discovery Devices
daqlist("digilent")
ans =
1×4 table
"AD1" "Digilent Inc. Analog Discovery 2 Kit Rev. C" "Analog Discovery 2" [1×1 daq
dq = daq("digilent")
dq =
Running: 0
Rate: 10000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
Add an analog output channel with device ID AD1 and channel ID 1. Set the measurement type to
Voltage. By default, the voltage range of the output signal is -5.0 to +5.0 volts.
ch_out =
18-71
18 Data Acquisition Toolbox Examples
outVal = 2;
write(dq, outVal);
rate = 300e3;
dq.Rate = rate;
f = 10;
totalduration = 1;
n = totalduration * rate;
t = (1:n)/rate;
output = sin(2*pi*f*t)';
Generate Data
write(dq, output);
18-72
Acquiring and Generating Data at the Same Time with Digilent Analog Discovery
This example shows you how to synchronously generate and acquire voltage data at a rate of 300
kHz.
daqlist("digilent")
ans =
1×4 table
"AD1" "Digilent Inc. Analog Discovery 2 Kit Rev. C" "Analog Discovery 2" [1×1 daq
dq = daq("digilent")
dq =
Running: 0
Rate: 10000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
Add an analog output channel using the listed Digilent device with ID AD1, channel ID 1, and
measurement type Voltage.
18-73
18 Data Acquisition Toolbox Examples
ch_out =
Add an analog input channel with the same device and measurement type Voltage.
ch_in =
rate = 300e3;
dq.Rate = rate;
Generate a sine wave with amplitude 1 V on channel 1 and amplitude 2 V on channel 2 and acquire
timestamped data at the same rate.
18-74
Acquiring and Generating Data at the Same Time with Digilent Analog Discovery
18-75
18 Data Acquisition Toolbox Examples
Use function generator channels to generate a 1 kHz sinusoidal waveform, and record data at the
same time, using an analog input channel.
ans =
1×4 table
"AD1" "Digilent Inc. Analog Discovery 2 Kit Rev. C" "Analog Discovery 2" [1×1 daq
dq =
Running: 0
Rate: 10000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
Add a function generator channel with device ID AD1 and channel ID 1. Set the waveform type to
Sine.
ch_fgen = addoutput(dq, "AD1", "1", "Sine");
Set channel gain to 5 (sets the amplitude of the sinusoid to 5 V). Assign the gain to a variable.
ch_fgen.Name = "AD1_1_fgen"
gain = 5;
ch_fgen.Gain = gain;
ch_fgen =
18-76
Generate Standard Periodic Waveforms Using Digilent Analog Discovery
ch_fgen.Frequency = 1000;
Add an analog input channel with device ID AD1 and channel ID 1. Set the measurement type to
Voltage.
ch_in =
Acquire data at a higher scan rate than the highest frequency in the generated waveform.
Plot Data
period = 1/ch_fgen.Frequency;
plot(data.Time, data.AD1_1_in);
xlabel('Time in seconds');
ylabel('Voltage in volts');
title(['Period = ', num2str(period), ' seconds'])
xlim([seconds(0) seconds(5*period)]);
ylim([-gain gain]);
18-77
18 Data Acquisition Toolbox Examples
18-78
Generate Arbitrary Periodic Waveforms Using Digilent Analog Discovery
Use function generator channels to generate an arbitrary 1kHz waveform function, and record data
at the same time, using an analog input channel.
ans =
1×4 table
"AD1" "Digilent Inc. Analog Discovery 2 Kit Rev. C" "Analog Discovery 2" [1×1 daq
dq =
Running: 0
Rate: 10000
NumScansAvailable: 0
NumScansAcquired: 0
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
Add a function generator channel with device ID AD1 and channel ID 1. Set the waveform type to
Arbitrary. The voltage range of the output signal is -5.0 to +5.0 volts.
ch_fgen = addoutput(dq, "AD1", "1", "Arbitrary");
ch_fgen.Name = "AD1_1_fgen"
ch_fgen =
18-79
18 Data Acquisition Toolbox Examples
The function generator produces periodic outputs by repeatedly generating the contents of its buffer
(4096 points). A waveform is constructed to fill this buffer without repetition.
buffersize = 4096;
len = buffersize + 1;
f0 = 1;
f1 = 1 * f0;
f2 = 2 * f0;
f3 = 3 * f0;
waveform(end) = [];
Add an analog input channel with device ID AD1 and channel ID 1. Set the measurement type to
Voltage.
ch_in = addinput(dq, "AD1", "1", "Voltage");
ch_in.Name = "AD1_1_in"
ch_in =
Acquire data at a higher scan rate than the highest frequency in the generated waveform
(oversampling).
oversamplingratio = 50;
Fn = 2 * frequency;
Fs = oversamplingratio * Fn;
dq.Rate = Fs;
18-80
Generate Arbitrary Periodic Waveforms Using Digilent Analog Discovery
height = 750;
period = 1/frequency;
numperiods = k * period;
maxamplitude = 3*ch_fgen.Gain;
L = 2 * oversamplingratio * buffersize;
NFFT = 2^nextpow2(L);
Y = fft(data.AD1_1_in, NFFT)/L;
f0 = (Fs/2) * linspace(0, 1, NFFT/2 + 1);
Plot Waveforms
plotScaleFactor = 12;
plotRange = NFFT/2; % Plot is symmetric about NFFT
plotRange = floor(plotRange / plotScaleFactor);
Yplot = Y(1:plotRange);
fplot = f0(1:plotRange);
fig = figure;
18-81
18 Data Acquisition Toolbox Examples
18-82
Acquire Continuous Audio Data
This example shows how to set up a continuous audio acquisition using a microphone.
Create a DataAcquisition
Create a DataAcquisition with directsound as the vendor and add an audio input channel to it using
addinput.
dq = daq("directsound");
addinput(dq,"Audio0",1,"Audio");
hf = figure;
hp = plot(zeros(1000,1));
T = title('Discrete FFT Plot');
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
grid on;
Set ScansAvailableFcn
Update the figure with the FFT of the live input signal by setting the ScansAvailableFcn.
18-83
18 Data Acquisition Toolbox Examples
Start Acquisition
start(dq,"Duration",seconds(10));
figure(hf);
lengthOfData = length(data);
% next closest power of 2 to the length
nextPowerOfTwo = 2 ^ nextpow2(lengthOfData);
plotScaleFactor = 4;
% plot is symmetric about n/2
plotRange = nextPowerOfTwo / 2;
plotRange = floor(plotRange / plotScaleFactor);
h = yDFT(1:plotRange);
abs_h = abs(h);
% Frequency range
18-84
Acquire Continuous Audio Data
18-85
18 Data Acquisition Toolbox Examples
This example shows how to generate audio signals using a 5.1 channel sound system.
load handel;
Plot the data to identify five distinct segments. Each segment represents a "Hallelujah" in the chorus.
The segments are annotated as 1 to 5.
ly = length(y);
lspan = 1:ly;
t = lspan/Fs;
hf = figure;
plot(t,y./max(y))
axis tight;
title("Signal (Handel''s Hallelujah Chorus) vs Time");
xlabel("Time (s)");
ylabel("Amplitude");
markers = struct('xpos',[0.2,0.4,0.55,0.65,0.8],'string',num2str([1:5]'));
for i = 1:5,
annotation(hf,'textbox',[markers.xpos(i) 0.48 0.048 0.080],'String', markers.string(i),'Backg
end
18-86
Generate Audio Signals
This example uses a 5.1 channel sound system with device ID 'Audio2'.
1. Create a DataAcquisition with directsound as the vendor and add an audio output channel to it.
dd = daq("directsound");
nch = 6;
addoutput(dd, "Audio2", 1:nch, "Audio");
2. Update the generation scan rate to match the audio sampling rate.
dd.Rate = Fs;
3. Generate audio signals (Handel's "Hallelujah Chorus"). "Hallelujah" should be voiced five times,
one for each segment depicted in the figure on all channels of the speaker system.
write(dd, repmat(y,1,nch));
close(hf);
18-87
18 Data Acquisition Toolbox Examples
This example shows how to set up continuous audio generation using multiple audio channels. The
signal, a sample of Handel's "Hallelujah Chorus", is broken up into contiguous segments and played
back in two parts. The first part of the example plays each segment on a single speaker and a sub-
woofer. The second part plays each segment on a different set of speakers (a choir of voices).
Load variables:
load handel;
dq = daq("directsound")
Add Channels and Adjust Generation Scan Rate to Match the Audio Sampling Frequency
Add six audio output channels and set the generation scan rate to the audio sampling rate.
addoutput(dq,"Audio7",1:6,"Audio");
dq.Rate = Fs;
Visually identify audio segments that correspond to each "Hallelujah" in the chorus and select sample
numbers at which these segments start and stop. Each color in the plot corresponds to a different
segment of the chorus.
18-88
Generating Multichannel Audio
18-89
18 Data Acquisition Toolbox Examples
Set up a selection of speakers in a cell array named speakerselection to play five segments of
"Hallelujah" on six different speakers.
nspeakers = 6;
nspeakergroups = 5;
speakerselection = cell(1, nspeakergroups);
Each speaker selection specifies which speakers from the 5.1 channel speaker system play each audio
segment (these assignments may vary for your speaker system). For the first part of the example, use
single speakers paired with the sub-woofer (4).
• Speaker 1: Left-Front
• Speaker 2: Right-Front
• Speaker 3: Center
• Speaker 4: Sub-Woofer
• Speaker 5: Left-Rear
• Speaker 6: Right-Rear
[singleChannelOutputs] = ...
surroundSoundVoices(y, segmentEnd, nspeakers, nspeakergroups, speakerselection);
Write a sequence of single channel outputs and then pause before proceeding to the next section.
write(dq, singleChannelOutputs);
pause(3);
Each speaker selection specifies which speakers from the 5.1 channel speaker system play each audio
segment (these assignments may vary for your speaker system). For the second part of the example,
use groups of speakers. Note that the sub-woofer (4) is included in all speaker selections
18-90
Generating Multichannel Audio
• Speaker 1: Left-Front
• Speaker 2: Right-Front
• Speaker 3: Center
• Speaker 4: Sub-Woofer
• Speaker 5: Left-Rear
• Speaker 6: Right-Rear
[multiChannelOutput] = ...
surroundSoundVoices(y, segmentEnd, nspeakers, nspeakergroups, speakerselection);
write(dq, multiChannelOutput);
for i = 1:numSpeakerGroups
speakergroup = speakerGroups{i};
n = numel(speakergroup);
for j = 1:n
range = startOfSegment(i):segmentEnds(i);
multiChannelOutput(range, speakergroup(j)) = audioOut(range);
end
end
end
18-91
18 Data Acquisition Toolbox Examples
This example shows how to implement a triggered data capture based on a trigger condition defined
in software. Data Acquisition Toolbox provides functionality for hardware triggering a data
acquisition object, for example starting acquisition from a DAQ device based on an external digital
trigger signal (rising or falling edge). For some applications however, it is desirable to start capturing
or logging data based on the analog signal being measured, allowing for capturing only the signal of
interest out of a continuous stream of digitized measurement data (such as an audio recording when
the signal level passes a certain threshold).
A custom graphical user interface (UI) is used to display a live plot of the data acquired in continuous
mode, and allows you to input trigger parameters values for a custom trigger condition, which is
based on the acquired analog input signal level and slope. Captured data is displayed in the
interactive UI, and is saved to a MATLAB base workspace variable.
This example can be easily modified to instead use audio input channels with a DirectSound
supported audio device.
The code is structured as a single program file, with a main function and several local functions.
Hardware Setup
• A DAQ device (such as NI USB-6218) with analog input channels, supported by the
DataAcquisition interface in background acquisition mode.
• External signal connections to analog input channels. The data in this example represents
measured voltages from a series resistor-capacitor (RC) circuit: total voltage across RC (in this
example supplied by a function generator) is measured on channel AI0, and voltage across the
capacitor is measured on channel AI1.
Configure a data acquisition object with two analog input channels and set acquisition parameters.
Background continuous acquisition mode provides the acquired data by calling a user defined
18-92
Capture Data with Software-Analog Triggering
callback function (dataCapture) when ScansAvailable events occur. A custom graphical user interface
(UI) is used for live acquired data visualization and for interactive data capture based on user
specified trigger parameters.
function softwareAnalogTriggerCapture
%softwareAnalogTriggerCapture DAQ data capture using software-analog triggering
% softwareAnalogTriggerCapture launches a user interface for live DAQ data
% visualization and interactive data capture based on a software analog
% trigger condition.
% Specify the desired parameters for data capture and live plotting.
% The data capture parameters are grouped in a structure data type,
% as this makes it simpler to pass them as a function argument.
18-93
18 Data Acquisition Toolbox Examples
while s.Running
pause(0.5)
end
18-94
Capture Data with Software-Analog Triggering
The dataCapture user-defined callback function is being called repeatedly, each time a ScansAvailable
event occurs. With each callback function execution, the latest acquired data block and timestamps
are added to a persistent FIFO data buffer, a continuous acquired data plot is updated, latest data is
analyzed to check whether the trigger condition is met, and -- once capture is triggered and enough
data has been captured for the specified timespan -- captured data is saved in a base workspace
variable. The captured data is an N x M matrix corresponding to N acquired data scans, with the
timestamps as the first column, and the acquired data corresponding to each channel as columns
2:M.
18-95
18 Data Acquisition Toolbox Examples
% Update UI status
hGui.StatusText.String = 'Waiting for trigger';
% Update captured data plot (one line for each acquisition channel)
for ii = 1:numel(hGui.CapturePlot)
set(hGui.CapturePlot(ii), 'XData', captureData(:, 1), ...
'YData', captureData(:, 1+ii))
end
18-96
Capture Data with Software-Analog Triggering
elseif ~captureRequested
% State: "Capture not requested"
% Capture toggle button is not pressed, set trigger flag and update UI
trigActive = false;
hGui.StatusText.String = '';
end
drawnow
end
Create a user interface programmatically, by creating a figure, one plot for live acquired data, one
plot for captured data, buttons for starting capture and stopping acquisition, and text fields for
entering trigger configuration parameters and status update.
For simplicity, the figure and all user interface components have a fixed size and position defined in
pixels. For high DPI displays the position values might have to be adjusted for optimum dimensions
and layout. Another option for creating a custom UI is to use App Designer.
function hGui = createDataCaptureUI(s)
%createDataCaptureUI Create a graphical user interface for data capture.
% hGui = createDataCaptureUI(s) returns a structure of graphics
% components handles (hGui) and creates a graphical user interface, by
% programmatically creating a figure and adding required graphics
% components for visualization of data acquired from a data acquisition
% object (s).
18-97
18 Data Acquisition Toolbox Examples
% Create the captured data plot axes (one line per acquisition channel)
hGui.Axes2 = axes('Units', 'Pixels', 'Position', [207 99 488 196]);
hGui.CapturePlot = plot(NaN, NaN(1, numel(s.Channels)));
xlabel('Time (s)');
ylabel('Voltage (V)');
title('Captured data');
hGui.Axes2.Toolbar.Visible = 'off';
disableDefaultInteractivity(hGui.Axes2);
% Create an editable text field for the captured data variable name
hGui.VarName = uicontrol('style', 'edit', 'string', 'mydata',...
'units', 'pixels', 'position', [87 159 57 26]);
% Create an editable text field for the trigger channel
hGui.TrigChannel = uicontrol('style', 'edit', 'string', '1',...
'units', 'pixels', 'position', [89 258 56 24]);
% Create an editable text field for the trigger signal level
hGui.TrigLevel = uicontrol('style', 'edit', 'string', '1.0',...
'units', 'pixels', 'position', [89 231 56 24]);
% Create an editable text field for the trigger signal slope
hGui.TrigSlope = uicontrol('style', 'edit', 'string', '200.0',...
'units', 'pixels', 'position', [89 204 56 24]);
% Create text labels
hGui.txtTrigParam = uicontrol('Style', 'text', 'String', 'Trigger parameters', ...
'Position', [39 290 114 18], 'BackgroundColor', uiBackgroundColor);
hGui.txtTrigChannel = uicontrol('Style', 'text', 'String', 'Channel', ...
'Position', [37 261 43 15], 'HorizontalAlignment', 'right', ...
'BackgroundColor', uiBackgroundColor);
hGui.txtTrigLevel = uicontrol('Style', 'text', 'String', 'Level (V)', ...
'Position', [35 231 48 19], 'HorizontalAlignment', 'right', ...
'BackgroundColor', uiBackgroundColor);
hGui.txtTrigSlope = uicontrol('Style', 'text', 'String', 'Slope (V/s)', ...
'Position', [17 206 66 17], 'HorizontalAlignment', 'right', ...
18-98
Capture Data with Software-Analog Triggering
'BackgroundColor', uiBackgroundColor);
hGui.txtVarName = uicontrol('Style', 'text', 'String', 'Variable name', ...
'Position', [35 152 44 34], 'BackgroundColor', uiBackgroundColor);
end
function endDAQ(~, ~, s)
if isvalid(s)
if s.Running
stop(s);
end
end
end
In this example, the trigger condition is defined by the signal level on the trigger channel and the
corresponding slope. Depending on the application and actual data being acquired, data filtering or
more complex trigger conditions can be implemented.
18-99
18 Data Acquisition Toolbox Examples
% If first data block acquired, slope for first data point is not defined
if isempty(prevData)
trigCondition2 = [false; trigCondition2];
end
trigDetected = any(trigCondition);
trigMoment = [];
if trigDetected
% Find time moment when trigger condition has been met
trigTimeStamps = latestData(trigCondition, 1);
trigMoment = trigTimeStamps(1);
end
end
18-100
Count Pulses on a Digital Signal Using NI Devices
This example shows how to determine the rate of rotation of an Anaheim Automation motor controller
by counting the number of rising edges in the signal. The controller returns hall effect pulses (square
waves) that serve as frequency feedback for motor rotation speeds.
Use daq to create a DataAcquisition and addinput to add a counter input channel with EdgeCount
measurement type. For this example, use CompactDAQ chassis NI c9178 and module NI 9402 with ID
cDAQ1Mod5.
dq = daq("ni");
ch = addinput(dq,"cDAQ1Mod5", "ctr0", "EdgeCount");
ch
ch =
To connect the input signal to the correct terminal, examine the Terminal property of the channel.
The terminal is determined by the hardware.
ch.Terminal
ans =
'PFI0'
To determine if the counter is operational, input a single scan, pause while the motor rotates, then
read the counter again.
read(dq)
ans =
timetable
Time cDAQ1Mod5_ctr0
_____ ______________
0 sec 3
18-101
18 Data Acquisition Toolbox Examples
pause(0.1);
read(dq)
ans =
timetable
Time cDAQ1Mod5_ctr0
_____ ______________
0 sec 14
pause(0.1);
read(dq)
ans =
timetable
Time cDAQ1Mod5_ctr0
_____ ______________
0 sec 27
Count the number of pulses by resetting the counter to zero, pause for one second, and read the
counter. The hall effects are oriented every 120 degrees and generate three square wave pulses for
every rotation.
resetcounters(dq);
pause(1);
read(dq, "OutputFormat", "Matrix")/3
ans =
33.6667
The hardware clock is highly accurate. Use the hardware clock to acquire multiple counter
measurements. NI counter devices require an external clock. By adding an analog input channel for a
module on the same chassis, the DataAcquisition shares an internal clock with both modules.
dq = daq("ni");
addinput(dq,"cDAQ1Mod1", "ai0", "Voltage");
addinput(dq,"cDAQ1Mod5", "ctr0", "EdgeCount");
data = read(dq, seconds(0.25));
plot(data.Time, data.Variables);
18-102
Count Pulses on a Digital Signal Using NI Devices
18-103
18 Data Acquisition Toolbox Examples
This example shows how to measure frequency to determine rate of flow of fluid using a flow sensor.
The sensor generates a digital signal with frequency that correlates to the rate of flow of fluid.
Use daq to create a DataAcquisition and addinput to add a counter input channel with Frequency
measurement type. For this example, use CompactDAQ chassis NI c9178 and module NI 9402 with ID
cDAQ1Mod5.
dq = daq("ni");
ch = addinput(dq,"cDAQ1Mod5", "ctr0", "Frequency");
ch
ch =
To connect the input signal to the correct terminal, examine the Terminal property of the channel.
The terminal is determined by the hardware.
ch.Terminal
ans =
'PFI1'
Measure Frequency
To determine if the counter is operational, input a single scan while the motor is rotating.
read(dq)
ans =
timetable
Time cDAQ1Mod5_ctr0
_____ ______________
0 sec 100
18-104
Measure Frequency Using NI Devices
Use the hardware clock to acquire multiple counter measurements over time. NI counter devices
require an external clock. By adding an analog input channel for a module on the same chassis, the
session shares an internal clock with both modules.
dq = daq("ni");
dq.Rate = 1;
addinput(dq,"cDAQ1Mod1", "ai0", "Voltage");
addinput(dq,"cDAQ1Mod5", "ctr0", "Frequency");
18-105
18 Data Acquisition Toolbox Examples
This example shows how to measure the width of an active high pulse. A sensor is used to measure
distance from a point: the width of the pulse is correlated with the measured distance.
Create a DataAcquisition, and add a counter input channel with PulseWidth measurement type. For
this example, use CompactDAQ chassis NI c9178 and module NI 9402 with ID cDAQ1Mod5.
dq = daq("ni");
ch = addinput(dq, "cDAQ1Mod5", "ctr0", "PulseWidth");
To connect the input signal to the correct terminal, examine the Terminal property of the channel.
The terminal is determined by the hardware.
ch.Terminal
ans =
'PFI1'
Measure Distance
To determine if the counter is operational, acquire a single scan. The sensor generates a high pulse of
width 0.0010 seconds corresponding a distance of one meter.
ans =
Use the hardware clock to acquire multiple counter measurements over time. NI counter devices
require an external clock. By adding an analog input channel for a module on the same chassis, the
internal clock is shared with both modules.
dq = daq("ni");
addinput(dq, "cDAQ1Mod1", "ai0", "Voltage");
addinput(dq, "cDAQ1Mod5", "ctr0", "PulseWidth");
dq.Rate = 1;
data = read(dq, seconds(10));
plot(data.Time, 1000*data.cDAQ1Mod5_ctr0);
18-106
Measure Pulse Width Using NI Devices
18-107
18 Data Acquisition Toolbox Examples
This example shows how to generate a pulse width modulated signal to drive a stepper motor.
Use daq to create a DataAcquisition. Use addoutput to add a counter output channel with
PulseGeneration measurement type, and addinput to add an analog input channel to monitor the
pulse generated by the counter output channel. For this example, use CompactDAQ chassis NI c9178
and module NI 9402 with ID cDAQ1Mod5 for the pulse generation and NI 9205 with ID cDAQ1Mod1
for the voltage input.
dq = daq("ni");
addinput(dq,"cDAQ1Mod1", "ai0", "Voltage");
ctr = addoutput(dq,"cDAQ1Mod5", "ctr0", "PulseGeneration");
dq.Channels
ans =
To connect the output signal to the correct terminal, examine the Terminal property of the counter
channel. The terminal is determined by the hardware.
ctr.Terminal
ans =
'PFI0'
Use counter output channel 0 to generate a fixed pulse width modulated signal on terminal PFI0.
Trigger the motor after 0.5 seconds, with a 75% duty cycle.
ctr.Frequency = 10;
ctr.InitialDelay = 0.5;
ctr.DutyCycle = 0.75;
% StartForeground returns data for input channels only. The data variable
% will contain one column of data.
start(dq, "Duration", seconds(1));
while dq.Running
pause(0.1);
end
18-108
Generate Pulse Width Modulated Signals Using NI Devices
18-109
18 Data Acquisition Toolbox Examples
This example shows how to acquire angular position data using an incremental rotary encoder and a
multifunction data acquisition (DAQ) device with the Data Acquisition Toolbox quadrature encoder
measurement functionality.
An incremental rotary encoder is typically mounted on the shaft of a mechanical system, such as a
wind turbine or a robotic arm, to provide motion or position information. The encoder outputs two
quadrature signals, which provide information on the relative change in position and the direction of
rotation. The counter subsystem of the DAQ device uses the signals output by the encoder to
calculate the change in position, and keep track of the most recent position value. In MATLAB, an
input channel with a Position measurement type is used to read the position values.
This example uses an optical shaft encoder (US Digital H6-2500-IE-S) and a multifunction DAQ device
(NI USB-6255) with counter channels which have quadrature encoder capability.
Create a data acquisition object and add an input channel with Position measurement type.
s = daq('ni');
ch1 = addinput(s, 'Dev1', 'ctr0', 'Position');
Configure Hardware
A rotary quadrature encoder outputs two quadrature signals, A and B, which provide information on
the relative change in position and the direction of rotation. Optionally, some models also output an
index or reference signal, Z, which is active once per revolution. You can use the Z signal to reset the
counter position to a known reference value.
Connect A, B, and Z signal outputs from the encoder device to the proper DAQ input terminals
specified by the DAQ device datasheet (PFI8, PFI10, and PFI9 for NI USB-6255). The correct
terminals depend on the device model and the counter channel used, and can be listed by reading the
following properties:
ch1.TerminalA
ans =
'PFI8'
ch1.TerminalB
ans =
'PFI10'
ch1.TerminalZ
ans =
18-110
Measure Angular Position with an Incremental Rotary Encoder
'PFI9'
Configure quadrature cycle encoding type (X1, X2, or X4). This corresponds to the number of counts
(counter value increments or decrements) output by the encoder for each quadrature cycle (1, 2, or
4.), as specified in the encoder datasheet.
ch1.EncoderType = 'X1';
The DAQ device counter hardware keeps track of the relative position changes signaled by the
encoder. Use read to read an updated position from the counter input channel.
encoderPosition = read(s, 1, 'OutputFormat', 'Matrix')
encoderPosition =
This example uses an optical encoder model with a resolution of 2500 quadrature cycles per shaft
revolution, as specified in the encoder datasheet.
Convert counter values to angular position (in degrees) using the encoder resolution and the
encoding type ('X1' in this case).
encoderCPR = 2500;
encoderPositionDeg = encoderPosition * 360/encoderCPR
encoderPositionDeg =
For applications where high time-resolution is required the data acquisition must be hardware-timed
(clocked). As proof of concept, this example characterizes the motion of a swinging pendulum by
measuring its angular position vs. time.
To acquire hardware-timed data from a counter input channel, NI DAQ devices require the use of an
external clock or the use of a clock from another subsystem.
Add an analog input channel to the data acquisition object to automatically share this system's scan
clock.
addinput(s, 'Dev1', 'ai0', 'Voltage');
18-111
18 Data Acquisition Toolbox Examples
By default, counter position readings are unsigned integer values. The counter channels of the DAQ
device used in this example are 32-bit, so any counter value read will be in the range 0 to 2^32-1.
Depending on the application, you may want to obtain signed position values (positive or negative) as
decrementing the counter value past zero is a discontinuous wraparound to 2^32-1.
For 32-bit counter channels, use 2^31 as the threshold counter value for conversion to signed
position values. The result is valid if the actual position value is in the range -2^31+1 to 2^31.
counterNBits = 32;
signedThreshold = 2^(counterNBits-1);
signedData = positionData(:,1);
signedData(signedData > signedThreshold) = signedData(signedData > signedThreshold) - 2^counterNB
Plot the signed angular position data acquired for the oscillatory motion of a pendulum.
figure
plot(timestamps, positionDataDeg);
xlabel('Time (s)');
ylabel('Angular position (deg.)');
Use the Z Signal to Reference the Relative Position to a Known Absolute Position
The A and B quadrature signals output by incremental rotary encoders provide only relative position
information (direction of motion and changes in position). The optional reference signal Z is a single
18-112
Measure Angular Position with an Incremental Rotary Encoder
pulse output once per encoder shaft revolution at a predefined absolute location. Referencing the
relative position value to the known absolute position reference allows an incremental rotary encoder
to function as a pseudo-absolute position encoder. This is useful in accurate positioning applications
(such as industrial automation, robotics, solar tracking, radar antenna or telescope positioning).
For incremental rotary encoders that provide a Z index signal output, the counter position value can
be configured to be reset automatically to the known reference value.
Specify the absolute reference position value ZResetValue to which the counter value will be reset.
ch1.ZResetValue = 0;
Acquire and plot a set of hardware-timed counter position data to show how you can use the encoder
Z index signal to automatically reset the counter value to a known reference value.
[positionData2, timestamps2] = read(s, daqDuration, 'OutputFormat', 'matrix');
figure
plot(timestamps2, positionData2(:,1));
xlabel('Time (s)');
ylabel('Counter value for quadrature encoder (counts)');
18-113
18 Data Acquisition Toolbox Examples
The acquired position data corresponds to a rotary encoder shaft that is rotating continuously. Notice
that before the first time the counter value is reset the position value is not referenced to an absolute
position, whereas the other counter reset events occur when the counter value is 2500 (the encoder
CPR value).
18-114
Control Stepper Motor Using Digital Outputs
This example shows how to control a stepper motor using digital output ports.
Use daqlist to discover devices. This example uses a National Instruments® ELVIS II with ID Dev2.
d = daqlist
d =
12×5 table
d{10, "DeviceInfo"}
ans =
Digital IO supports:
39 channels ('port0/line0' - 'port2/line6')
'InputOnly','OutputOnly','Bidirectional' measurement types
18-115
18 Data Acquisition Toolbox Examples
This example uses a Portescap 20M020D1U motor (5 V, 18 degree unipolar stepper). The TTL signals
produced by the digital I/O system are amplified by a Texas Instruments ULN2003AIN (high voltage,
high current Darlington transistor array), as shown in this schematic:
Create a DataAcquisition and add 4 digital channels on port 0, lines 0-3. Set the measurement type to
OutputOnly. These are connected to the 4 control lines for the stepper motor.
dq = daq("ni");
addoutput(dq,"Dev2","port0/line0:3","Digital")
Warning: Added channel does not support clocked sampling: clocked operations are
disabled. Only on-demand operations are allowed.
Refer to the Portescap motor wiring diagram describing the sequence of 4-bit patterns. Send this
pattern sequentially to the motor to produce counterclockwise motion. Each step turns the motor 18
18-116
Control Stepper Motor Using Digital Outputs
degrees. Each cycle of 4 steps turns the motor 72 degrees. Repeat this cycle five times to rotate the
motor 360 degrees.
step1 = [1 0 1 0];
step2 = [1 0 0 1];
step3 = [0 1 0 1];
step4 = [0 1 1 0];
Rotate Motor
Use write to output the sequence to turn the motor 72 degrees counterclockwise.
write(dq,step1);
write(dq,step2);
write(dq,step3);
write(dq,step4);
To turn the motor 72 degrees clockwise, reverse the order of the steps.
write(dq,step4);
write(dq,step3);
write(dq,step2);
write(dq,step1);
After you use the motor, turn off all the lines to allow the motor to rotate freely.
write(dq,[0 0 0 0]);
18-117
18 Data Acquisition Toolbox Examples
Communicate with instruments and devices at the protocol layer as well as the physical layer. Use the
I2C feature of Instrument Control Toolbox to communicate with a TMP102 temperature sensor, and
simultaneously analyze the physical layer I2C bus communications using the clocked digital IO
feature of Data Acquisition Toolbox.
• Any supported National Instruments™ DAQ device with clocked DIO channels can be used (e.g.,
NI Elvis II)
• TotalPhase Aardvark I2C/SPI Host Adaptor
• TMP102 Digital Temperature Sensor with two-wire serial interface
The TMP102 requires a 3.3 V supply. Use a linear LDO (LP2950-33) to generate the 3.3 V supply from
the DAQ device's 5 V supply line.
Connect to a TMP102 Sensor Using I2C Host Adaptor and Read Temperature Data
Wire up the sensor and verify communication to it using the I2C object from Instrument Control
Toolbox.
18-118
Communicate with I2C Devices and Analyze Bus Signals Using Digital IO
Acquire the Corresponding I2C Physical Layer Signals Using a DAQ Device
Use oversampled clocked digital channels from the NI Elvis (Dev4) to acquire and analyze the
physical layer communications on the I2C bus.
Acquire SDA data on port 0, line 0 of your DAQ device. Acquire SCL data on port 0, line 1 of your
DAQ device.
dd = daq("ni");
addinput(dd,"Dev4","port0\line0","Digital"); % sda
addinput(dd,"Dev4","port0\line1","Digital"); % scl
Digital subsystems on NI DAQ devices do not have their own clock; they must share a clock with the
analog subsystem or import a clock from an external subsystem. Generate a 50% duty cycle clock at 1
MHz using a PulseGeneration counter output, and set the input scan rate to match.
pgChan = addoutput(dd,"Dev4","ctr1"),"PulseGeneration");
dd.Rate = 1e6;
pgChan.Frequency = dd.Rate;
The clock is generated on the 'pgChan.Terminal' pin, allowing synchronization with other devices and
viewing the clock on an oscilloscope. The counter output pulse signal is imported as a clock signal.
disp(pgChan.Terminal);
addclock(dd,"ScanClock","External",["Dev4/" pgChan.Terminal]);
PFI13
Acquire data in the background from the SDA and SCL digital lines.
start(dd, "continuous");
fopen(tmp102);
data8 = fread(tmp102, 2, "uint8");
% One LSB equals 0.0625 deg. C
temperature = (double(bitshift(int16(data8(1)), 4)) +...
18-119
18 Data Acquisition Toolbox Examples
Warning: Triggers and Clocks will not affect counter output channels.
Plot the raw data to see the acquired signals. Notice that lines are held high during idle periods. The
next section shows how to find the start/stop condition bits and use them to isolate areas of interest
in the I2C communication.
figure("Name", "Raw Data");
subplot(2,1,1);
plot(myData(:,1));
ylim([-0.2, 1.2]);
ax = gca;
ax.YTick = [0,1];
ax.YTickLabel = {'Low','High'};
title("Serial Data (SDA)");
subplot(2,1,2);
plot(myData(:,2));
ylim([-0.2, 1.2]);
ax = gca;
ax.YTick = [0,1];
ax.YTickLabel = {'Low','High'};
title("Serial Clock (SCL)");
18-120
Communicate with I2C Devices and Analyze Bus Signals Using Digital IO
Extract I2C physical layer signals on the SDA and SCL lines.
sda = myData(:,1)';
scl = myData(:,2)';
Through inspection, observe that idle periods have SCL high for longer than 100 us. Since scan rate
= 1MS/s, each sample represents 1 us. idlePeriodIndices indicate periods periods of activity
within the I2C communication.
idlePeriodIndices = find(sclFlipPeriods>100);
Zoom into the first period of activity on the I2C bus. For ease of viewing, include 30 samples of idle
activity to the front and end of each plot.
18-121
18 Data Acquisition Toolbox Examples
As a simple example analyze start and stop condition metrics, and I2C bit rate calculation.
• Start condition duration is defined as the time it takes for SCL to go low after SDA goes low.
• Stop condition duration is defined as the time it takes for SDA to go high after SCL goes high.
• Bit rate is calculated by taking the inverse of the time between 2 rising clock edges.
sclLowIndex = sclFlipIndexes(idlePeriodIndices(1));
sdaLowIndex = find(sda(1:sclLowIndex)==1, 1, "last") + 1; % +1, flip is next value after last hig
startConditionDuration = (sclLowIndex - sdaLowIndex) * 1/s.Rate;
sda: 1 0 0 0 0 0 0
scl: 1 1 1 1 1 1 0
Start condition duration: 5.000000e-06 sec.
18-122
Communicate with I2C Devices and Analyze Bus Signals Using Digital IO
sda: 0 0 0 0 0 0 1
scl: 0 1 1 1 1 1 1
Stop condition duration: 5.000000e-06 sec.
Bit Rate: Inverse of time between 2 rising edges on the SCL line
startConditionIndex = idlePeriodIndices(1);
firstRisingClockIndex = startConditionIndex + 2;
secondRisingClockIndex = firstRisingClockIndex + 2;
clockPeriodInSamples = sclFlipIndexes(secondRisingClockIndex) - sclFlipIndexes(firstRisingClockIn
clockPeriodInSeconds = clockPeriodInSamples * 1/s.Rate;
bitRate = 1/clockPeriodInSeconds;
fprintf('DAQ calculated bit rate = %d; Actual I2C object bit rate = %dKHz\n', ...
bitRate,...
tmp102.BitRate);
DAQ calculated bit rate = 1.000000e+05; Actual I2C object bit rate = 100KHz
The sclFlipIndexes vector was created using XOR and hence contains both rising and falling
edges. Start with a rising edge and use a step of two to skip falling edges.
18-123
18 Data Acquisition Toolbox Examples
data = bitStream(startBit:endBit);
fprintf('Decoded Data%d: %s(0x%s) %d(%s)\n', ...
iData+1,...
sprintf('%d', data),...
binaryVectorToHex(data),...
bitStream(ackBit),...
ACK_NACK{bitStream(ackBit)+1});
end
Verify That the Decoded Data Using DAQ Matches the Data Read Using ICT
Two uint8 bytes were read, using fread, from the I2C bus into variable data8. The hex conversion
of these values should match the results of the bus decode shown above.
18-124
Synchronize NI PCI Devices Using RTSI
This example shows how to acquire synchronized data from two PCI devices. A sine wave is
connected to channel 0 of NI PCI-6251 and to channel 0 of NI PCIe-6363. Synchronized operation is
verified by demonstrating zero phase lag between the acquired signals.
Create a DataAcquisition and add analog input voltage input channels from NI PCI-6251 and NI
PCIe-6363 devices.
dd = daq("ni");
addinput(dd,"Dev3","ai0","Voltage");
addinput(dd,"Dev4","ai0","Voltage");
[data,time] = read(dd,seconds(1),"OutputFormat","Matrix");
plot(time, data)
There is a small phase lag between the two channel inputs. The DataAcquisition starts the two
channels close together, but the devices do not share any clock and trigger information and therefore
are not fully synchronized.
18-125
18 Data Acquisition Toolbox Examples
Connect PCI devices using a RTSI® (Real-Time System Integration) cable and register it in
Measurement & Automation Explorer®. To synchronize the acquisition, share a scan clock and start
trigger between the two devices.
The device that provides the control and timing signals is called the source device, and the device
that receives these signals is called destination device. In this example, Dev3 is the source device and
Dev4 is the destination device.
The RTSI cable creates a physical connection between the RTSI0 terminal on Dev3 and RTSI0
terminal on Dev4. Use this connection to share the start trigger between the source and destination
devices.
Use addtrigger to add a digital start trigger from 'RTSI0/PFI3' (source) to 'RTSI0/Dev4'
(destination).
addtrigger(dd,"Digital","StartTrigger","Dev3/RTSI0","Dev4/RTSI0");
Use addclock to share a scan clock using the RTSI1 terminal connection.
addclock(dd,"ScanClock","Dev3/RTSI1","Dev4/RTSI1");
[data,time] = read(dd,seconds(1));
plot(time,data)
18-126
Synchronize NI PCI Devices Using RTSI
The two sine waves are overlapping with zero phase lag, confirming that the devices are fully
synchronized.
18-127
18 Data Acquisition Toolbox Examples
This example shows how to set up and start a multi-trigger acquisition on an external event. In this
instance, the device is configured to start acquiring data on a rising edge signal.
Create a DataAcquisition object, and add an analog input channel with the Voltage measurement
type, using an NI PCIe 6363, with ID Dev4.
dq = daq("ni");
addinput(dq,"Dev4","ai0","Voltage");
Configure the device to acquire data on the external trigger. A trigger that starts an acquisition is
called a Start Trigger. In this example, the switch is wired to terminal PFI0 on device Dev4.
Represent this physical connection (between the switch and terminal PFI0) as a start trigger.
A trigger has a trigger type (Digital). The allowed value for the Digital trigger type is
StartTrigger.
A trigger has a source and a destination. In this example, the source is the switch (choose
'External' as the source). The destination is the PFI0 terminal on Dev4 ('PFI0/Dev4'). Use
addtrigger to add this trigger on the DataAcquisition.
addtrigger(dq,"Digital","StartTrigger","External","Dev4/PFI0");
dq.DigitalTriggers
ans =
Source: "External"
Destination: 'Dev4/PFI0'
Type: 'StartTrigger'
Condition: 'RisingEdge'
By default the DataAcquisition waits for 10 seconds for the rising edge digital trigger. Increase the
timeout to 30 seconds using DigitalTriggerTimeout property.
dq.DigitalTriggerTimeout = 30;
You can configure a DataAcquisition to receive multiple triggers, when it should respond to multiple
events. In this example, two external trigger signals are expected, enabling the device Dev4 to start
acquiring scans on receipt of the second trigger.
dq.NumDigitalTriggersPerRun = 2;
18-128
Start a Multi-Trigger Acquisition on an External Event
Use read to acquire scans on receipt of each configured digital start trigger. The specific sequence of
events is:
Observe the discontinuity based on the time between the two trigger starts.
18-129
18 Data Acquisition Toolbox Examples
This example shows how to use the Analog Input block to acquire live analog data from a data
acquisition device into Simulink. The acquired data is processed in Simulink and uses the Analog
Output block to output data to a data acquisition device. It shows how a Simulink model can
communicate with different subsystems in the same model. In this case, the data acquisition device
used is from National Instruments®.
Note: This example requires MATLAB®, Data Acquisition Toolbox, and Simulink to open and run the
model.
The input signal is acquired from a National Instruments data acquisition device (USB-6211). Signal
is acquired from channel ai0 at the rate of 8000 samples/second. The Analog Input block is
configured to do synchronous acquisition, which does blocking read from the device and at each
timestep it acquires a chunk of 1600 samples from the hardware.
Note: Each column in the output of Analog Input block corresponds to data from an analog input
channel. To correctly interpret the data, in the downstream processing/visualization blocks, you need
to use 'Columns as Channels (frame-based)' as Input Processing method.
18-130
Perform Live Acquisition, Signal Processing, and Generation
Signal Processing
The acquired data is processed using a discrete filter. The discrete filter uses pre-computed
coefficients to implement a bandpass filter with a bandwidth of 50Hz around 100Hz and an
attenuation of 60dB elsewhere, for input signals sampled at 8kHz. To design digital filters, to select
specific implementation structures, use blocks from the "Filtering" library in DSP System Toolbox.
The capture data has three major frequency components: sine waves at 100Hz, 500Hz and 1000Hz.
After the discrete filter, you would see a clear 100Hz sine wave in the output. A plot of the input and
the filtered signals are shown below.
The processed data is output to a single channel of a National Instruments device (PCI-6211) at a rate
of 8000 samples/second.
Even though a National Instruments device was used for this example, this model can be easily
updated to connect to other supported data acquisition devices. This provides you the flexibility to
reuse the same Simulink model with different data acquisition hardware.
18-131
18 Data Acquisition Toolbox Examples
This example shows how to use the Analog Input block to acquire live signals from a data acquisition
device into Simulink. The block uses a National Instruments(R) USB-6211 as the input device. The
Simulink model uses a spectrum estimator to output a power spectrum estimate of a time-domain
input using Welch's method of averaged modified periodograms.
Note: This example requires MATLAB®, Simulink, Data Acquisition Toolbox and DSP System
Toolbox™ to open and run the model.
The input signal is a real-time analog signal sampled at 10000 samples per second. The Analog Input
block is configured to do asynchronous acquisition, which buffers the data from the analog channels
and streams the buffered data to Simulink. Each timestep, the Analog Input block outputs a chunk of
1024 samples. Each chunk of data is processed by a Spectrum Estimator to calculate the power
spectrum. You can adjust the settings in the Spectrum Estimator such as different window functions.
In this example the captured signal contains three major frequency components: sine waves at 50Hz,
250Hz, and 500Hz. The time domain signal, frequency domain signal from Spectrum Analyzer, and
the one-side power spectrum estimate by spectrum estimator are shown below.
18-132
Perform Spectral Analysis on Live Data
18-133
18 Data Acquisition Toolbox Examples
18-134
Perform Spectral Analysis on Live Data
Even though a National Instruments device was used for this example, this model can be easily
updated to connect to other supported data acquisition devices. This provides you the flexibility to
reuse the same Simulink model with different data acquisition hardware.
18-135
18 Data Acquisition Toolbox Examples
This example shows how to acquire data from two different DAQ devices running at different
sampling rates. The example uses two National Instruments CompactDAQ analog input modules
(9201 and 9211) that have different acquisition rate limits. The 9211 module is used for temperature
measurements and acquires at a slower rate (10 Hz) than the 9201 module, which is used to measure
voltage (100 Hz). Since all channels in a data acquisition object must acquire at the same rate, to
acquire from two modules at multiple rates you need to use two data acquisition objects. To make
both DAQ devices start simultaneously, you can use a hardware digital triggering configuration.
Hardware Setup
Create two data acquisition objects, each with one analog input channel from a 9211 module or 9201
module. The data acquisition objects acquire data at rates of 10 Hz and 100 Hz, respectively.
% Specify a common acquisition duration for both devices, in seconds
daqDuration = seconds(3);
% Create and configure DataAcquisition object and channels for cDAQ 9211 module
d1 = daq('ni');
addinput(d1, 'cDAQ1Mod1', 'ai0', 'Thermocouple');
d1.Channels(1).ThermocoupleType = 'K';
d1.Rate = 10;
Warning: The Rate property was reduced to 14.2857 due to changes in the channel
configuration.
% Create and configure DataAcquisition object and channels for cDAQ 9201 module
d2 = daq('ni');
addinput(d2, 'cDAQ1Mod2', 'ai0', 'Voltage');
d2.Rate = 100;
To synchronize the acquisition start you can use hardware triggering and a source/destination
approach. One of the data acquisition objects (source) is started manually and triggers the acquisition
start of the other data acquisition object (destination).
Note: If you have a CompactDAQ chassis model (such as NI 9174) which does not have PFI triggering
terminals, you can use an additional digital I/O module (such as NI 9402) to provide the PFI terminals
for the trigger connections.
% Configure the source data acquisition object to export a triggering
% signal on the PFI0 terminal of cDAQ1 chassis
addtrigger(d1, 'Digital', 'StartTrigger', 'cDAQ1/PFI0', 'External');
18-136
Acquire Data from Two Devices at Different Rates
The destination data acquisition object must start first and be ready for an external trigger before the
source data acquisition object starts.
For each data acquisition object, the acquired measurement data and timestamps were stored in
memory. Read all acquired data from memory in the default timetable format.
Because the acquired data from the two devices have different scales and units, create a chart with
two y-axes.
figure
yyaxis left
plot(data1.Time, data1.Variables, '-x')
ylabel('Temperature (deg. C)')
ylim([0 50])
yyaxis right
plot(data2.Time, data2.Variables, '-o')
ylabel('Voltage (V)')
xlabel('Time (s)')
18-137
18 Data Acquisition Toolbox Examples
Clean Up
clear d1 d2
18-138
Characterize an LED with ADALM1000
This example shows how to use MATLAB to connect to an Analog Devices ADALM1000 source-
measurement unit, configure it, and make current and voltage measurements to characterize an LED.
daqlist
ans=1×5 table
VendorID DeviceID Description Model DeviceInfo
________ ________ _______________________________ ___________ ___________________
ADIDaq = daq("adi");
The ADALM1000 device is capable of sourcing voltage and measuring current simultaneously on the
same channel. Set up the device in this mode.
Add an analog output channel with device ID SMU1 and channel ID A, and set its measurement type
to voltage.
addoutput(ADIDaq,'smu1','a','Voltage');
Add an analog input channel with device ID SMU1 and channel ID A, and set its measurement type to
current.
addinput(ADIDaq,'smu1','a','Current');
ADIDaq.Channels
ans=1×2 object
Index Type Device Channel Measurement Type Range Name
_____ ____ ______ _______ _____________________ __________________ ________
Connect an LED in series with a 330-Ω resistor between the ADALM1000 channel A and ground.
Alternately apply 5 V and 0 V.
18-139
18 Data Acquisition Toolbox Examples
write(ADIDaq,0);
pause(0.2);
end
To understand the LED's I-V characteristics, sweep a range of voltage values from 0 V to 5 V, and
measure the current for each value. The aggregate of all measurements provides data to graph the
current across the LED over a range of voltages.
v = linspace(0,5,250)';
i = readwrite(ADIDaq,v,"OutputFormat","Matrix");
Plot the Characteristic Curve of the LED and Estimate a Mathematical Model
When you have the measured data, you can visualize it. You can also calculate a mathematical model
that approximates the behavior of the LED within the range of the measurements.
Fit the data using a fifth-order polynomial and overlay the acquired data with the model of the LED
approximated by a fifth-order polynomial.
approxPoly = polyfit(v,i,5);
plot(v,polyval(approxPoly,v),'-k','Linewidth',1);
18-140
Characterize an LED with ADALM1000
Based on the fifth-order polynomial approximation, you can find a first-order approximation that
represents the linearly increasing portion of the curve. The voltage at which the LED turns on is
approximately where this line intersects the voltage axis.
Find the line that passes through the linear portion of the signal.
normErr = -1;
errThreshold = 0.001;
numPointsForLine = numel(v) - 10;
while (numPointsForLine > 0) && (normErr < errThreshold)
approximation = polyval(approxPoly,v(numPointsForLine:end));
[linearPoly, errorStruct] = polyfit(v(numPointsForLine:end),approximation, 1);
numPointsForLine = numPointsForLine - 5;
normErr = errorStruct.normr;
end
Evaluate the linear polynomial over the range of measurements. The value where this intersects the
horizontal line representing any leakage current is the voltage at which the LED turns on.
LEDThreshold = 1.2;
leakageCurrent = mean(i(v<LEDThreshold));
linearIV = polyval(linearPoly,v);
minIndex = sum(linearIV<leakageCurrent);
18-141
18 Data Acquisition Toolbox Examples
plot(v(minIndex-1:end),polyval(linearPoly,v(minIndex-1:end)),'Magenta','Linewidth',2,'LineStyle',
plot(v(minIndex),leakageCurrent,'o','Linewidth',2,'MarkerSize',20,'MarkerEdgeColor','Red')
title(sprintf('Calculated Voltage at Which LED Turns On: %1.2fV',v(minIndex)));
write(ADIDaq,0);
close
clear ADIDaq
18-142
Estimate the Transfer Function of a Circuit with ADALM1000
This example shows how to use MATLAB to connect to an ADALM1000 source-measurement unit,
configure it to generate an arbitrary signal, make live measurements, and use the measurements to
calculate the transfer function of the connected circuit.
Introduction
In this example you have an R-C circuit consisting of a 1 kΩ resistor in series with a 0.1 μF capacitor.
The R-C circuit is attached to the ADALM1000 device with Channel A of the device providing the
voltage stimulus consisting of a chirp signal. The output of Channel A is connected to the resistor, and
the ground is connected to the capacitor. Channel B of the device is used to measure the voltage
across the capacitor. The following circuit diagram shows the measurement setup.
You can use the stimulus and the measured waveforms to estimate the transfer function of the R-C
circuit, and compare the measured response to the theoretical response of the R-C circuit.
daqlist("adi")
ans=1×4 table
DeviceID Description Model DeviceInfo
________ _______________________________ ___________ ________________________
ADIDaq = daq("adi")
ADIDaq =
DataAcquisition using Analog Devices Inc. hardware:
Running: 0
Rate: 100000
NumScansAvailable: 0
NumScansAcquired: 0
18-143
18 Data Acquisition Toolbox Examples
NumScansQueued: 0
NumScansOutputByHardware: 0
RateLimit: []
Show channels
Show properties and methods
The ADALM1000 device is capable of sourcing and measuring voltage simultaneously on separate
channels. Set up the device in this mode.
To source voltage, add an analog output channel with device ID SMU1 and channel ID A, and set its
measurement type to Voltage.
addoutput(ADIDaq,'smu1','a','Voltage');
To measure voltage, add an analog input channel with device ID SMU1 and channel ID B, and set its
measurement type to Voltage.
addinput(ADIDaq,'smu1','b','Voltage');
ADIDaq.Channels
ans=1×2 object
Index Type Device Channel Measurement Type Range Name
_____ ____ ______ _______ _____________________ _________________ ________
Use a chirp waveform of 1 volt amplitude, ranging in frequency from 20 Hz to 20 kHz for stimulating
the circuit. The chirp occurs in a period of 1 second.
Fs = ADIDaq.Rate;
T = 0:1/Fs:1;
ExcitationSignal = chirp(T,20,1,20e3,'linear');
Add a DC offset of 2 V to ensure that the output voltage of the device is always above 0 V.
Offset = 2;
ExcitationSignal = ExcitationSignal + Offset;
figure(1)
plot(T, ExcitationSignal,'Blue')
xlim([0 0.15])
xlabel('Time (s)')
ylabel('Magnitude (V)')
title('Time domain plot of stimulus signal')
18-144
Estimate the Transfer Function of a Circuit with ADALM1000
figure(2)
spectrogram(ExcitationSignal,1024,1000,1024,Fs,'yaxis')
title('Frequency domain view of stimulus signal')
18-145
18 Data Acquisition Toolbox Examples
Generate device output and measure measure the voltage across the capacitor at the same time on
the other channel.
MeasuredTable = readwrite(ADIDaq,ExcitationSignal');
MeasuredSignal = MeasuredTable{:,1};
figure(1)
hold on;
plot(T,MeasuredSignal,'Red');
xlim([0 0.15])
ylim([1 3])
title('Time domain plot of stimulus and measured signal')
legend('Excitation Signal','Measured Signal')
18-146
Estimate the Transfer Function of a Circuit with ADALM1000
figure(3)
spectrogram(MeasuredSignal,1024,1000,1024,Fs,'yaxis')
title('Frequency domain view of the the measured signal')
18-147
18 Data Acquisition Toolbox Examples
Compare the measured signal and the stimulus signal to calculate the transfer function of the R-C
circuit, and plot the magnitude response.
figure(4);
semilogy(Freq,TFMagTheory,Freq,Mag);
xlim([0 20e3])
xlabel('Frequency (Hz)')
ylim([0.05 1.1])
ylabel('Magnitude')
grid on
legend('Theoretical frequency response','Measured frequency response')
title({'Magnitude response of the theoretical'; 'and estimated transfer functions'});
18-148
Estimate the Transfer Function of a Circuit with ADALM1000
clear ADIDaq
close all
18-149
18 Data Acquisition Toolbox Examples
This example shows how to create an analog-triggered data acquisition app by using Data Acquisition
Toolbox™ and App Designer.
Data Acquisition Toolbox provides functionality for acquiring measurement data from a DAQ device or
audio sound card. For certain applications, an analog-triggered acquisition that starts capturing or
logging data based on a condition in the analog signal being measured is recommended. Software-
analog triggered acquisition enables you to capture only a segment of interest out of a continuous
stream of measurement data. For example, you can capture an audio recording when the signal level
passes a certain threshold.
By default, the app will open in design mode in App Designer. To run the app click the Run button or
execute the app from the command line:
18-150
Create an App for Analog Triggered Data Acquisition
AnalogTriggerApp
Requirements
The analog trigger capture is specified by the trigger level, trigger condition, trigger delay, and
capture duration which are defined as in the figure below. A negative trigger delay means pre-trigger
data will be captured.
When creating an app that has complex logic, consider the various states that correspond to the
operating modes of the app. For this app, the app logic is implemented in MATLAB code and the
following app states are used:
18-151
18 Data Acquisition Toolbox Examples
• DeviceSelection
• Configuration
• Acquisition (Buffering, ReadyForCapture, Capture, LookingForTrigger, CapturingData,
CaptureComplete)
You can use a Stateflow chart to visualize, organize, and control the app states as illustrated in the
"Analog Trigger App by Using Stateflow Charts" example.
18-152
Analog Triggered Data Acquisition Using Stateflow Charts
This example shows how to create an analog-triggered data acquisition app by using Stateflow®,
Data Acquisition Toolbox™, and App Designer.
Data Acquisition Toolbox provides functionality for acquiring measurement data from a DAQ device or
audio soundcard. For certain applications, an analog-triggered acquisition that starts capturing or
logging data based on a condition in the analog signal being measured is recommended. Software-
analog triggered acquisition enables you to capture only a segment of interest out of a continuous
stream of measurement data. For example, you can capture an audio recording when the signal level
passes a certain threshold.
This example app, created by using App Designer and Stateflow, shows how to implement these
operations:
By default, the app opens in design mode in App Designer. To run the app click the Run button or
execute the app from the command line:
18-153
18 Data Acquisition Toolbox Examples
AnalogTriggerAppStateflow
Requirements
When creating an app that has complex logic, consider the various states that correspond to the
operating modes of the app. You can use a Stateflow chart to visualize and organize these app states.
Use transitions between states to implement the control logic of your app. For example, the file
AnalogTriggerAppLogic.sfx defines the Stateflow chart that controls the logic for this app. The
chart can transition between states based on an action in the app UI or on a data-driven condition.
For example, if you click the Start button, the chart transitions from the Configuration state to the
Acquisition state. If the value of the signal crosses the specified trigger level, the chart transitions
from the LookingForTrigger state to the CapturingData state.
18-154
Analog Triggered Data Acquisition Using Stateflow Charts
To establish a bidirectional connection between the MATLAB app and the Stateflow chart, in the
startupFcn function of your app, create a chart object and store its handle in an app property.
app.Chart = AnalogTriggerAppLogic(app=app);
The app uses this handle to trigger state transitions in the chart. For example, when you click Start,
the StartButtonPushed app callback function calls the acquisitionStart input event for the
chart. This event triggers the transition from the Configuration state to the Acquisition state.
To evaluate transition conditions that are not events in the chart, the app calls the step function for
the chart object. For example, while acquiring data from the device, the dataAvailable_Callback
18-155
18 Data Acquisition Toolbox Examples
app function periodically calls the step function. When the trigger condition is detected, the chart
transitions from the LookingForTrigger State to the CapturingData state.
In the Stateflow chart, store the app object handle as chart local data. To share public properties and
call public functions of the app, the Stateflow chart can use this handle in state actions, transition
conditions, or transition actions.
18-156
Create an App for Live Data Acquisition
This example shows how to create an app which acquires data from a DAQ device or sound card,
displays a live data view, and logs data to a MAT-file.
By default, the app will open in design mode in App Designer. To run the app click Run or execute the
app from the command line:
LiveDataAcquisition
Requirements
18-157
18 Data Acquisition Toolbox Examples
18-158
Acquire Data Using NI FieldDAQ Device
To discover a device that supports input measurements, access the device in the table returned by the
daqlist command. This example uses a NI FD-11603 device. This device has two banks, each with 4
channels. Channel 0 of Bank 1 is connected to a frequency generator that produces a 1 kHz sine wave
(1 Vpp centered around 0.5V).
d = daqlist("ni")
d=10×4 table
DeviceID Description Model DeviceI
_______________________ ___________________________________ __________ _____________
Create a DataAcquisition, set the Rate property (the default is 1000 scans per second), and add
analog input channels using addinput.
dq = daq("ni");
dq.Rate = 20000;
addinput(dq,"FD11603-1D3BB09-Bank1","ai0","Voltage");
Warning: Added channel does not support on-demand operations: only clocked operations are allowed
Use read to acquire multiple scans, blocking MATLAB execution until all the data requested is
acquired. The acquired data is returned as a timetable with width equal to the number of channels
and height equal to the number of scans.
t = data.Time;
v = data.Variables;
n = 200;
plot(t(1:n), v(1:n));
ylabel("Voltage (V)")
18-159
18 Data Acquisition Toolbox Examples
18-160
Acquire Data Using NI FieldDAQ Device
18-161
18 Data Acquisition Toolbox Examples
This example shows how to create an echometer sonar using audio data acquisition and signal
processing, which can measure distance by determining the time of flight of a sound pulse reflected
off of a surface.
This example employs an approach for post synchronization of audio output and input data
timestamps, which is required for applications where the input signal is in response to the output
and/or when output/input timing correlation is relevant. Example applications include an acoustic
characterization setup or stimulus-response experiments. The relative output/input lag is determined
and corrected using correlation functions in Signal Processing Toolbox.
Requirements
Hardware Setup
• Focusrite Scarlett 2i2 audio interface device, or another device / sound card with two output and
two input audio channels
• Audio interface device DirectSound drivers provided by the vendor, or using default Windows
device drivers if available
• One powered speaker and one microphone compatible with the audio interface device
• Audio patch cables and connector adaptors
Typical DirectSound audio interface devices supported by Data Acquisition Toolbox do not support
hardware synchronization between the output and input channels. Pairs of audio input or output
channels are synchronized by the audio device, however the output and input channels can have a
non-negligible relative start lag.
To synchronize the output and input data timestamps in post-processing, the following setup can be
used:
• Connect one of the output channels (output 1 or left channel of stereo plug) to one of the input
channels (input 1 or left channel) to generate and acquire a synchronization signal in a loopback
configuration.
• The other output (output 2 or right channel) and input channel (input 2 or right channel) are used
to output an excitation/stimulus signal, and respectively acquire a measurement/response signal.
• Read data from both audio input channels, with one of the channels being used for reading the
synchronization signal, and the other channel for reading the actual response signal.
• With this setup, you read data from both audio input channels, and simultaneously write data to
both audio output channels.
Echometer Sonar
As a demonstration of this approach, you can use an audio device, a powered speaker, and a
microphone to put together an echometer sonar setup. A pulse echometer measures the distance to
18-162
Create an Echometer Using Audio Measurements
an object by emitting a short sound pulse, measuring the reflected pulse echo, and determining the
time of flight by comparing the original output pulse signal with the measured input response signal.
The speaker and microphone are placed next to each other and oriented toward a wall off of which
the sound pulse reflects, as in the diagram below.
A pulse signal typically used for sonar applications is a short duration frequency sweep, or a chirp.
Because the sharp amplitude edges at the beginning and end of a flat chirp signal can cause
measurement artifacts, the pulse is attenuated/shaped by an envelope function. Options include
Hanning, Gaussian, Kaiser, etc. Frequency range, pulse width or duration, pulse envelope/shape
depend on the intended application. In this example the measurements are taken with a 3 ms
duration pulse with a 1-5 kHz linear frequency chirp, and a Hanning window. The synthesized signal
is shown in the figure below. The original chirp signal is shown on the left and the shaped pulse is
shown on the right. The Hanning window is shown as a dotted line.
Make sure to use a signal frequency range that can be properly generated by the speaker, picked up
by the microphone, and sampled by the audio interface device. The sampling rate used for the audio
device measurements is 192 kHz.
18-163
18 Data Acquisition Toolbox Examples
f1 = 5E+3;
% Time vector
t = (0:1/Fs:T)';
nexttile
plot(t,yc)
hold on
plot(t,w,'--')
xlabel("Time (s)")
ylabel("Amplitude")
title("Original chirp signal and Hanning envelope")
nexttile
plot(t,y)
xlabel("Time (s)")
title("Shaped pulse")
18-164
Create an Echometer Using Audio Measurements
Data Acquisition
Use two separate DataAcquisition objects, one for the audio output channels and one for the
audio input channels. Since there is no automatic synchronization possible between the audio input
and output channel pairs even if a common DataAcquisition object is used for all channels, this
approach allows for more control over the data acquisition operations.
do = daq("directsound");
addoutput(do,"Audio4","1","Audio");
addoutput(do,"Audio4","2","Audio");
do.Rate = Fs;
di = daq("directsound");
addinput(di,"Audio1","1","Audio");
addinput(di,"Audio1","2","Audio");
di.Rate = Fs;
Since the pulse duration is relatively short, pad the ending of the pulse signal with zero values (200
ms duration) to ensure that the pulse is generated correctly.
yout = [y; zeros(Fs*200E-3,1)];
18-165
18 Data Acquisition Toolbox Examples
Start the input first as a continuous background acquisition, then generate the same signal on both
audio output channels. One of the channels is used as a synchronization signal.
start(di,"continuous")
write(do,[yout yout])
stop(di)
Read the acquired data into the workspace. By default, the read function returns a timetable.
data = read(di,"all");
Plot the acquired data. Signals Audio1_1 and Audio1_2 correspond to the audio input channels 1 and
2. Input channel 1 was used to record the synchronization signal generated by output channel 1 in a
loopback configuration. Input channel 2 was used to record the actual response signal picked by the
microphone. Two pulses are observed in the response signal, followed by other secondary echoes
which depend on the room acoustics. Also notice the large relative start lag time between the input
and output channels.
figure
stackedplot(data)
18-166
Create an Echometer Using Audio Measurements
Find the lag and align the output and input signal timestamps by discarding the points before the
detected synchronization signal.
t0 = 0.3058
alignedData = data(lag+1:end,:);
alignedData.Time = alignedData.Time-alignedData.Time(1);
figure
s = stackedplot(alignedData);
xlim(seconds([0 0.025]))
s.AxesProperties(1).YLimits = [-0.55 0.55];
Visually validate the quality of the time alignment, by comparing the synthetic pulse data with the
measured loopback signal.
18-167
18 Data Acquisition Toolbox Examples
figure
plot(seconds(t),y,alignedData.Time(1:numel(t)),alignedData.Audio1_1(1:numel(t)))
ylabel("Amplitude")
xlabel("Time (s)")
legend(["Pulse signal to output","Measured loopback signal"],"Location","bestoutside")
You can use the xcorr cross-correlation function to determine and visualize similarities between the
original pulse signal and the measured response signal.
[xCorr,lags] = xcorr(alignedData.Audio1_2,y);
figure
plot(lags/Fs,xCorr)
xlabel('Lags (s)')
ylabel('Cross-correlation')
axis tight
18-168
Create an Echometer Using Audio Measurements
The cross-correlation plot indicates several similarities, with two larger peaks and other smaller
peaks from reverberations.
Find timestamp and total propagation distance corresponding to the first two observed correlated
pulses in the measured signal. The first observed pulse corresponds to the direct propagation path
from the speaker to the microphone. The second observed pulse is the echo pulse reflected by the
wall. The function finddelay returns the lag for which the normalized cross-correlation has the
highest value, and in this case it corresponds to the first pulse in the response signal.
t1 = finddelay(y,alignedData.Audio1_2)/Fs
t1 = 0.0011
You can calculate the propagation time of the echo pulse as the starting timestamp of the second
pulse in the response signal by using finddelay in the signal region after the first pulse.
t2 = t1 + T + finddelay(y,alignedData(timerange(seconds(t1+T),"inf"),:).Audio1_2)/Fs
t2 = 0.0122
% Plot the response signal and highlight the first two detected pulses
figure
18-169
18 Data Acquisition Toolbox Examples
plot(alignedData.Time,alignedData.Audio1_2)
xlim(seconds([0 t2+2*T]))
hold on
firstPulse = alignedData(timerange(seconds(t1),seconds(t1+T)),:);
plot(firstPulse.Time,firstPulse.Audio1_2)
echoPulse = alignedData(timerange(seconds(t2),seconds(t2+T)),:);
plot(echoPulse.Time,echoPulse.Audio1_2)
ylabel("Amplitude")
xlabel("Time (s)")
d2 = 2.1006
18-170
Create an Echometer Using Audio Measurements
The distance (2.10 m) measured by the echometer sonar setup (half of the total path) is very close to
the actual distance (2.06 m) between the speaker/microphone setup and the wall reflecting the echo
pulse.
18-171
18 Data Acquisition Toolbox Examples
This example shows how to read data from a TDMS-file into MATLAB® for analysis.
The example TDMS-file contains measurement data of a sine wave amplitude and phase. The
measurements are in two channels, in the same channel group.
Use the tdmsinfo function to obtain channel group and channel names in the TDMS-file.
fileName = "SineWave.tdms";
info = tdmsinfo(fileName);
info.ChannelList
ans=2×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName Cha
__________________ ________________ _______________________ _________________ ___
Use the tdmsreadprop function to view data properties from the file.
tdmsreadprop(fileName)
ans=1×7 table
name description datetime author title
__________ ___________ _____________________________ _______ ____________________
ans=1×19 table
name description unit_string datatype displaytype monotony
_________________ ___________ ___________ ___________ ___________ ____________
To read data into a timetable, derive the start time and time step, typically contained in the channel
properties.
timeStep = tdmsreadprop(fileName, ChannelGroupName=group, ChannelName=channel, PropertyNames="wf_
timeStep=table
wf_increment
18-172
Get Started Reading a TDMS-File
____________
0.001
startTime=table
wf_start_time
_____________________________
1903-12-31 19:00:00.000000000
Using the start time and time step as arguments to the tdmsread function, read the data into
MATLAB as a cell array of timetables. View some of the data from first channel group.
ans=8×2 timetable
Time Amplitude sweep Phase sweep
_____________________________ _______________ ___________
1903-12-31 19:00:00.000000000 0 0
1903-12-31 19:00:00.001000000 0 0.063418
1903-12-31 19:00:00.002000000 0 0.12658
1903-12-31 19:00:00.003000000 0 0.18923
1903-12-31 19:00:00.004000000 0 0.25112
1903-12-31 19:00:00.005000000 0 0.312
1903-12-31 19:00:00.006000000 0 0.37163
1903-12-31 19:00:00.007000000 0 0.42975
Use a stacked plot to visualize the relationship between the data of different channels.
stackedplot(ttData);
18-173
18 Data Acquisition Toolbox Examples
18-174
Read Multiple TDMS-Files into MATLAB
This example shows how to use a TDMS datastore to read data from multiple TDMS-files into
MATLAB® for analysis.
The multiple TDMS-files of this example contain measurement data of a sine wave amplitude and
phase, based on a trigger.
The tdmsDatastore function creates a datastore object, which allows you to treat all the TDMS-files
in a folder as one dataset.
folderName = fullfile(pwd,"Trigger");
ds = tdmsDatastore(folderName);
ds.ChannelList
ans=2×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName Cha
__________________ ________________ _______________________ _________________ ___
All the TDMS-files in the datastore must have the same channel groups and channels. The
NumSamples in the channel list is that of the first file in the datastore.
The readall function retrieves all the data from the datastore into MATLAB. Read and plot the data
from the first channel group.
data = readall(ds);
stackedplot(data{1})
18-175
18 Data Acquisition Toolbox Examples
You can also analyze data in the datastore one file at a time. Redefine the TDMS datastore with a read
size of "file".
ds = tdmsDatastore(folderName, readSize="file");
Iterate through the datastore, reading data from each TDMS-file. The read function uses the set read
size. For each file, find its maximum and minimum values in the Amplitude sweep channel, and
compare it to the cumulative maximum and minimum.
maxAmplitude = 0;
minAmplitude = 0;
while(hasdata(ds))
data = read(ds);
maxAmplitude = max(maxAmplitude, max(data{1}.("Amplitude sweep")));
minAmplitude = min(minAmplitude, min(data{1}.("Amplitude sweep")));
end
After the entire dataset is read, view the cumulative maximum and minimum amplitudes.
maxAmplitude
maxAmplitude = 6.9998
minAmplitude
18-176
Read Multiple TDMS-Files into MATLAB
minAmplitude = -6.9982
18-177
18 Data Acquisition Toolbox Examples
This example shows how to use a TDMS datastore to read data from a large TDMS-file into
MATLAB® for analysis.
The example TDMS-file contains measurement data of a sine wave amplitude and phase. It also
contains a channel group with sporadic events triggered at random times. The example file itself is
not large, but is used to show the techniques for handling a large file.
You can use a TDMS datastore object to read a large TDMS-file into MATLAB by iteratively reading
available chunks of data. The size of the data in each iteration might depend on a time interval of
interest, an absolute number of samples, or other group definition.
Given the name of the TDMS-file, use the tdmsDatastore function to create a TDMS datastore
object for a specified read size and channel group.
fileName = "SineWaveWithEvents.tdms";
readSize = 1000;
ds = tdmsDatastore(fileName, ReadSize=readSize, SelectedChannelGroup="Measured Data");
Examine the data store channel list to identify the channel group and channel names of interest.
ds.ChannelList
ans=4×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName Cha
__________________ ________________ _______________________ _________________ ___
Loop through the file to read 1000 samples at a time, until the end of the file. The datastore read size
and selected channel group were defined when the datastore ds was created above with the
tdmsDatastore function. The read function is constrained by these parameters. Use the hasdata
function if you do not know the number of iterations required.
while(hasdata(ds))
data = read(ds);
% This loop overwrites the last iteration data,
% so any analysis of individual data or cumulative
% reduction operations must happen inside the loop.
end
You can visualize the last 1000 samples of data using a stacked plot on the first channel group.
stackedplot(data{1});
18-178
Read a Large TDMS-File into MATLAB
Read and display the channel group containing the event data. This requires redefining the datastore
object with tdmsDatastore function for that channel group. Assuming it is not a large set of data,
you can use the readall function to retrieve it all at once.
ds = tdmsDatastore(fileName, SelectedChannelGroup="Events");
data = readall(ds);
data{1}
ans=5×2 table
Time Description
_____________________________ _____________
18-179
18 Data Acquisition Toolbox Examples
For this example, the file weather.mat contains a regional weather report from 3 December 1998 to
30 Nov 2000.
Load the data to be written to a TDMS-file, and define the TDMS-file, channel group, and channel
names. Later you can add some custom attributes, such as title and units, to the TDMS-file.
load("weather.mat");
fileName = "weather.tdms";
group = "ChannelGroup1";
channel = "T_min";
whos
Use the tdmswrite function to write the table of weather data to a TDMS-file from MATLAB.
tdmswrite(fileName, weather)
info = tdmsinfo(fileName)
info =
TdmsInfo with properties:
info.ChannelList
ans=38×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName
__________________ ________________ _______________________ ________________________
18-180
Get Started Writing a TDMS-File
Use tdmsread to examine the data written into the new file.
rData = tdmsread(fileName);
stackedplot(rData)
tdmsreadprop(fileName)
18-181
18 Data Acquisition Toolbox Examples
ans=1×5 table
name description title author timestamp
______________ ___________ ________________ ______ _____________________________
tdmsreadprop(fileName, ChannelGroupName=group)
ans=1×2 table
name description
_______________ ___________
"ChannelGroup1" ""
ans=1×3 table
name description unit_string
_______ ___________ ___________
To update the file properties, channel group properties, or channel properties of an existing TDMS
file, use tdmswriteprop.
ans=1×5 table
name description title author timestamp
______________ ___________ ________________ ______ _____________________________
Also add a custom file property called timestamp, and set its value to the current date and time.
ans=1×5 table
name description title author timestamp
______________ ___________ ________________ ______ _____________________________
18-182
Get Started Writing a TDMS-File
Finally, update the units of a channel, which is specified by the default property unit_string.
ans=1×3 table
name description unit_string
_______ ___________ ___________
18-183
18 Data Acquisition Toolbox Examples
This example shows how to write timetable data in various time channel layouts from MATLAB® to a
TDMS-file.
For this example, you have measurents of revolution and electrical current of a circular saw in a
scenario where it stops on detecting contact with skin.
fileNameTCNone = "sawstopper_none.tdms";
fileNameTCSingle = "sawstopper_single.tdms";
channelGroup = "Circular Saw Data";
On specifying TimeChannel as "none", the start time and time step are added as properties of the
channel. This time channel layout can be used only with a timetable that is regular in time, that is,
with uniform time steps.
tdmswrite(fileNameTCNone, circular_saw_data, ChannelGroupName=channelGroup, TimeChannel="none");
info = tdmsinfo(fileNameTCNone);
info.ChannelList
ans=2×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName
__________________ ___________________ _______________________ _____________________
The channel names in the TDMS-file map to the original timetable variable names.
Use the tdmsreadprop function to inspect the start time (wf_start_time) and time step
(wf_increment) of the data.
channel = info.ChannelList.ChannelName{1};
prop = tdmsreadprop(fileNameTCNone, ChannelGroupName=channelGroup, ChannelName=channel)
prop=1×7 table
name description unit_string wf_start_time wf_st
_____________________ ___________ ___________ _____________________________ _____
Read the data from the TDMS-file and visually analyze the data using a stacked plot.
stackedplot(tdmsread(fileNameTCNone, TimeStep=seconds(prop.wf_increment)));
18-184
Write Timetable Data to TDMS-file
By default, the time channel layout is TimeChannel="single", which means a time channel is
created that contains a timestamp for every sample. Typically this time channel layout is useful when
writing measurments that are irregular in time.
Inspect the contents of the file. See that a time channel called "Time" is created, which is derived
from the time column of the original timetable.
info = tdmsinfo(fileNameTCSingle);
info.ChannelList
ans=3×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName
__________________ ___________________ _______________________ _____________________
Read the data from the TDMS-file, and visually analyze the data using a stacked plot with the time
channel as the x-axis.
18-185
18 Data Acquisition Toolbox Examples
18-186
Write Metadata to TDMS-File
This example shows how to write file properties, channel group properties, and channel properties to
a TDMS-file.
For this example, you have measurents of revolution and electrical current of a circular saw in a
scenario where it stops on detecting contact with skin. You can write these measurement to a new
TDMS-file, update the default properties, and add custom properties to the file, channel group, and
channels.
Set Up Workspace
Read the data into the workspace and define the TDMS-file channel group names.
load("sawstopper.mat")
fileName = "sawstopper.tdms";
channelGroup = "SawData";
channelRev = "Revolutions (1/min)";
channelCurrent = "Current (A)";
Create the TDMS-file, and then read and view its data.
18-187
18 Data Acquisition Toolbox Examples
tdmsreadprop(fileName)
ans=1×5 table
name description title author timestamp
_________________ ___________ __________________ ______ _________________________
Update the title property using tdmswriteprop, and add a new custom timestamp property set
with the current datetime.
ans=1×5 table
name description title author timestamp
_________________ ___________ __________________ ______ _________________________
tdmsreadprop(fileName, ChannelGroupName=channelGroup)
ans=1×3 table
name description scenario
_________ ___________________________ _____________________________________
Update the channel group property description. Then add a custom property scenario to the
channel group.
ans=1×3 table
name description scenario
_________ ___________________________ _____________________________________
Similarly, you can update the channel properties such unit_string by specifying the channel group
name and channel name.
18-188
Write Metadata to TDMS-File
ans=1×8 table
name description unit_string wf_
_____________________ ______________________________________ ___________ ___________
ans=1×8 table
name description unit_string wf_
_____________________ ______________________________________ ___________ ___________
You can also specify arrays of property names and values. If the property values have different data
types, use a cell array.
ans=1×7 table
name description unit_string wf_start_time
_____________ _____________________________ ___________ ____________________________
ans=1×7 table
name description unit_string wf_start_time
_____________ _____________________________ ___________ ____________________________
info = tdmsinfo(fileName);
info.ChannelList
ans=2×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName
__________________ ________________ ___________________________ ____________________
18-189
18 Data Acquisition Toolbox Examples
This example shows how to merge multiple TDMS-files by appending their data into a single TDMS-
file.
In this example you have vibration data of a rotating shaft recorded into a collection of TDMS-files.
The goal is to read each file and merge its data into an aggregate TDMS-file for analysis. You can
merge the data either by creating separate channel groups or by appending the data to a single
channel group. This example shows both approaches.
fileMultipleChannelGroup = "RotatingShaftAnalysis_MultipleChannelGroup.tdms";
fileSingleChannelGroup = "RotatingShaftAnalysis_SingleChannelGroup.tdms";
Create a datastore with which you can iteratively read the collection of TDMS files in the folder
RotatingShaftAnalysis, one file at a time.
ds = tdmsDatastore("RotatingShaftAnalysis", ReadSize="file");
You can write data to an existing TDMS-file by adding new channel groups. By default, the
tdmswrite function creates auto incrementing channel group names.
while(hasdata(ds))
data = read(ds); %read one file.
tdmswrite(fileMultipleChannelGroup, data);
end
On inspecting the contents of the written file you see there are 3 channel groups that map to 3 files in
the folder.
info = tdmsinfo(fileMultipleChannelGroup);
info.ChannelList
ans=9×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName ChannelDe
__________________ ________________ _______________________ ___________ _________
You can append the data from all the TDMS-files to a single channel group. By specifying a particular
channel group name, the data is append to that channel group.
18-190
Merge Multiple TDMS-Files
The channel names map to the table variable names, therefore the data is appended to all the
channels in the channel group. If there is a table variable that does not already exist as channel, a
new channel gets added to the channel group.
reset(ds);
while(hasdata(ds))
tdmswrite(fileSingleChannelGroup, read(ds), ChannelGroupName="Dataset")
end
On inspecting the contents of the file, the NumSamples property of ChannelList increased to 3 ×
20000, indicating that the data is appended to the file.
info = tdmsinfo(fileSingleChannelGroup);
info.ChannelList
ans=3×8 table
ChannelGroupNumber ChannelGroupName ChannelGroupDescription ChannelName ChannelDe
__________________ ________________ _______________________ ___________ _________
18-191
18 Data Acquisition Toolbox Examples
This example shows how to access a TDMS datastore using tall tables in MATLAB®.
For this example, you have measurent vibration measurements of a rotating shaft recorded across
multiple TDMS-files. Your goals is to extract portions of the files using tall tables and visually analyze
them.
Identify the location of the TDMS datastore files. Create a tall table from the TDMS datastore with an
applied transform. The tdmsDatastore function can be applied to either a set of multiple files, or a
single large file. Here a transform is used to convert the returned datastore type from a cell array to
a table.
folder = "RotatingShaftAnalysis";
mapreducer(0); % Sets the global execution environment to be the local MATLAB session.
tData = tall( transform(tdmsDatastore(folder), ...
@(cellData)table2timetable(cellData{1}, TimeStep=milliseconds(0.1))) );
You can extract the first or last N rows using head or tail, respectively.
You can also apply relational operators or colon expressions to filter the data. The ? characters
indicate that evaluation is deferred until you call gather.
filteredPulse =
? ? ? ?
? ? ? ?
? ? ? ?
: : : :
: : : :
tDataInRange = tData(5000:10000,:)
tDataInRange =
18-192
Analyze TDMS-Files Using Tall Tables
? ? ? ?
? ? ? ?
? ? ? ?
: : : :
: : : :
All table operations can be applied to tall table. One such operation is height, to get the total
number of rows in the collection.
tRows = height(tData);
Finally, evaluate the computations using gather, which triggers execution of the operations that
were delayed earlier. You can use gather to pass all the variables of interest in a single function call.
[tHead, tTail, filteredPulse, tDataInRange, tRows] = gather(tHead, tTail, filteredPulse, tDataInR
tHead=1000×3 timetable
Time Pulse Sensor_X Sensor_Y
__________ __________ ________ ________
tTail=1000×3 timetable
Time Pulse Sensor_X Sensor_Y
__________ __________ ________ ________
18-193
18 Data Acquisition Toolbox Examples
filteredPulse=27×3 timetable
Time Pulse Sensor_X Sensor_Y
__________ ______ ________ ________
tDataInRange=5001×3 timetable
Time Pulse Sensor_X Sensor_Y
__________ ___________ ________ ________
18-194
Analyze TDMS-Files Using Tall Tables
tRows = 60000
You can call the summary function to trigger immediate evaluatation of all the table variables.
summary(tData);
RowTimes:
18-195
18 Data Acquisition Toolbox Examples
Min 0 sec
Max 1.9999 sec
Variables:
Min -0.69755
Max 3.4114
Min -0.212
Max 0.50583
Min 0.18122
Max 0.94865
To learn more about tall tables, see “Tall Arrays”. Note: tdmsDatastore is not enabled to work with
Parallel Computing Toolbox.
18-196