1. Data Acquisition Toolbox 2.7
Getting Started
Getting Started with the Data Acquisition Toolbox
Introduction to Analog Input
Introduction to Analog Output
Introduction to Digital Input and Output
Logging Data to Disk
Application Examples
Generation of Audio Using the Sound Card
Acquiring Data with a Sound Card
Measuring a Noise Floor Using Custom Trigger Conditions
Deployment of a Soundcard Audio Analysis Application
2. Advanced Usage Demos
Accessing Analog Input Channels
Using Analog Input Triggers
Counting Complex Events Using Analog Input Data
Accessing Analog Output Channels
Using Analog Output Triggers
Accessing Digital Lines
Managing Large Data Sets by Logging to Disk
3. The MathWorks - Demos - Introduction to the Data Acquisition Toolbox http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 5 19/09/2005 12:26
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Getting Started with the Data Acquisition Toolbox
In this demo, we will determine:
What hardware and adaptors are installed on your machine
What Data Acquisition Toolbox objects you can create
How you can find information and help on a data acquisition object.
A hardware adaptor is the interface that allows you to pass information between the data acquisition engine and the hardware driver.
The Data Acquisition Toolbox provides adaptors for:
Advantech ('advantech')
HP/Agilent Technologies/VXITech ('hpe1432')
Keithley hardware ('keithley')
Measurement Computing, Corp. ('mcc')
National Instruments ('nidaq')
parallel ports ('parallel')
sound cards ('winsound')
You can display information related to your hardware and to MATLAB with the DAQHWINFO command.
daqhwinfo
% The returned information includes a list of installed
% hardware adaptors on your machine.
daqinadapt = ans.InstalledAdaptors;
ans =
ToolboxName: 'Data Acquisition Toolbox'
ToolboxVersion: '2.7 (R14SP3)'
MATLABVersion: '7.1 (R14SP3)'
InstalledAdaptors: {2x1 cell}
If you need to install an adaptor or move an existing adaptor, then it must be manually registered. A hardware adaptor is manually
registered with the command:
daqregister('adaptorname')
where 'adaptorname' is one of the supported hardware adaptors such as 'winsound', 'nidaq', 'mcc', etc.
daqregister('winsound')
ans =
'mwwinsound.dll' successfully registered.
Now that we know what adaptors are installed on your computer, you can display specific information related to an adaptor by passing
the adaptor name to DAQHWINFO. This information includes:
The hardware adaptor DLL filename and its version
The hardware driver description and its version
MATLAB commands for creating a data acquisition object using the specified adaptor name
The commands for creating a winsound data acquisition object are listed below. You can create both an analog input object and an
analog output object for the winsound adaptor (The third returned value is empty because soundcards do not support digital I/O)
daqhwinfo('winsound')
ans.ObjectConstructorName{:}
ans =
AdaptorDllName: [1x83 char]
AdaptorDllVersion: '2.7 (R14SP3)'
AdaptorName: 'winsound'
BoardNames: {'Emu10Kx Audio [B800]'}
InstalledBoardIds: {'0'}
ObjectConstructorName: {1x3 cell}
4. The MathWorks - Demos - Introduction to the Data Acquisition Toolbox http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 5 19/09/2005 12:26
ans =
analoginput('winsound',0)
ans =
analogoutput('winsound',0)
ans =
''
Now that we know the command for creating an analog input object for the winsound adaptor, let's create it.
ai = analoginput('winsound', 0)
Display Summary of Analog Input (AI) Object Using 'Emu10Kx Audio [B800]'.
Acquisition Parameters: 8000 samples per second on each channel.
8000 samples per trigger on each channel.
1 sec. of data to be logged upon START.
Log data to 'Memory' on trigger.
Trigger Parameters: 1 'Immediate' trigger(s) on START.
Engine status: Waiting for START.
0 samples acquired since starting.
0 samples available for GETDATA.
AI object contains no channels.
By default, the sound card uses 0 as the device id so it does not need to be specified. The following command illustrates this by
creating an analog output object for the winsound adaptor.
ao = analogoutput('winsound')
Display Summary of Analog Output (AO) Object Using 'Emu10Kx Audio [B800]'.
Output Parameters: 8000 samples per second on each channel.
Trigger Parameters: 1 'Immediate' trigger on START.
Engine status: Waiting for START.
0 total sec. of data currently queued for START.
0 samples currently queued by PUTDATA.
0 samples sent to output device since START.
AO object contains no channels.
You can find specific information pertaining to the created analog input object or analog output object by passing the object to
DAQHWINFO. This information includes:
The number of channels that you can add to the object
The range of sample rates
The native data type
The polarity
daqhwinfo(ai)
ans =
AdaptorName: 'winsound'
Bits: 16
Coupling: {'AC Coupled'}
DeviceName: 'Emu10Kx Audio [B800]'
DifferentialIDs: []
Gains: []
ID: '0'
InputRanges: [-1 1]
MaxSampleRate: 44100
5. The MathWorks - Demos - Introduction to the Data Acquisition Toolbox http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 5 19/09/2005 12:26
MinSampleRate: 8000
NativeDataType: 'int16'
Polarity: {'Bipolar'}
SampleType: 'SimultaneousSample'
SingleEndedIDs: [1 2]
SubsystemType: 'AnalogInput'
TotalChannels: 2
VendorDriverDescription: [1x25 char]
VendorDriverVersion: '5.10'
And for the analog output object:
daqhwinfo(ao)
ans =
AdaptorName: 'winsound'
Bits: 16
ChannelIDs: [1 2]
Coupling: {'AC Coupled'}
DeviceName: 'Emu10Kx Audio [B800]'
ID: '0'
MaxSampleRate: 44100
MinSampleRate: 8000
NativeDataType: 'int16'
OutputRanges: [-1 1]
Polarity: {'Bipolar'}
SampleType: 'SimultaneousSample'
SubsystemType: 'AnalogOutput'
TotalChannels: 2
VendorDriverDescription: [1x25 char]
VendorDriverVersion: '5.10'
By configuring property values for your data acquisition objects, you can control the behavior of your data acquisition application.
The Data Acquisition Toolbox device objects (analog input objects, analog output, and digital I/O objects) contain two kinds of
properties:
1) Base properties
2) Device-specific properties
Base properties apply to all supported hardware subsystems of a given type (analog input, analog output, digital I/O). For example, all
analog input objects have a SampleRate property regardless of the hardware vendor. In addition to the base properties, there may be
a set of device-specific properties that is determined by the hardware you are using.
When PROPINFO is called with an object as the input argument, a structure is returned. The field names of the structure are the
property names. The field values are a structure containing the property information. This information includes:
The property data type
Constraints on the property values
The default property value
Whether the property is read-only
Whether you can modify the property while the object is running.
An indication of whether the property is device-specific
For example, you can obtain information on the SampleRate property with the command listed below. The information returned
indicates that the SampleRate property:
Must be a double between the values 8000 and 44100
Has a default value of 8000
Is not read-only
Cannot be modified while the analog input object is running
Is a base property available to all analog input objects
aiInfo = propinfo(ai);
aiInfo.SampleRate
ans =
Type: 'double'
Constraint: 'bounded'
ConstraintValue: [8000 44100]
DefaultValue: 8000
ReadOnly: 'whileRunning'
DeviceSpecific: 0
6. The MathWorks - Demos - Introduction to the Data Acquisition Toolbox http://www.mathworks.com/products/daq/demos.html?file=/products...
4 de 5 19/09/2005 12:26
Alternatively, you can pass a property name to the PROPINFO command. In this case, information for the specified property is
returned.
aoOut = propinfo(ao, 'SampleRate')
aoOut =
Type: 'double'
Constraint: 'bounded'
ConstraintValue: [8000 44100]
DefaultValue: 8000
ReadOnly: 'whileRunning'
DeviceSpecific: 0
The information returned indicates that the OutOfDataMode property:
Has a default value of 'Hold'
Is not read-only
Cannot be modified while the analog output object is running
Is a base property available to all analog output objects
Must be set to one of the following strings:
aoOut.ConstraintValue
ans =
8000 44100
A more detailed property description is given with the DAQHELP command. The "See also" section that follows the description contains
related properties and functions.
The related properties are displayed using mixed lower and upper case letters. The related functions are displayed using letters all in
upper case.
daqhelp SampleRate
SAMPLERATE double
SampleRate specifies the per-channel rate at which data is digitized.
SampleRate specifies the per-channel rate (in samples/second) that the a
nalog
input (AI) or analog output (AO) subsystem digitizes data.
AI and AO subsystems have a finite (though often large) number of valid
sampling rates. If you specify a sampling rate that does not match one o
f
the valid values, the data acquisition engine automatically selects
the nearest available sampling rate.
Since SampleRate can be set to a value that differs from the one specifi
ed, you
should return the actual sampling rate using the GET function or the dev
ice
object display summary. Alternatively, you can use the SETVERIFY functio
n
which sets the SampleRate value and then returns the actual value that i
s set.
To find out the range of sampling rates supported by your board, use the
PROPINFO function.
The value of SampleRate cannot be modified while the object is running.
See also PROPINFO, SETVERIFY.
daqhelp StartFcn
STARTFCN string, function_handle, or cell array
StartFcn specifies the M-file function to execute just before the device
object and hardware device start executing.
8. The MathWorks - Demos - Introduction to Analog Input http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 2 19/09/2005 12:29
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Introduction to Analog Input Objects
In this example you will acquire data from the sound card on your computer. To get started, you first need to verify that your
environment is set up so that you can record data with your sound card. If you are unsure about this, refer to Appendix A of the Data
Acquisition Toolbox User's Guide.
To acquire data from your sound card, you need a data source, a data sensor, and a data sink. In this demonstration:
The data source - is the sound input to the sound card. This sound can come from a variety of sources including your voice, your
hands clapping, or a CD in your computer.
The sensor - is a microphone on your computer and
The sink - is a channel associated with an analog input object.
Now let's create an analog input object and add a single channel to it.
ai = analoginput('winsound');
addchannel(ai, 1);
Now, let's set up the analog input object so that we acquire 5 seconds of data at 8000 Hz as soon as the object is started.
ai.SampleRate = 8000;
ai.SamplesPerTrigger = 40000;
ai.TriggerType = 'Immediate';
With the analog input object set up, let's start it and then get the data that it collects. If your sound card is set up to collect data from
the microphone, then you should whistle or clap you hands just after you continue to the next demo screen. This will introduce
something other than random noise into the data you are collecting.
start(ai)
[d,t] = getdata(ai);
Now that you're done collecting data, plot it.
plot(t,d);
zoom on
Previously, you used the GETDATA function to collect 5 seconds of data. The only problem is that GETDATA is a "blocking" function.
This means that it will wait until all 5 seconds of data have been collected. For many applications, this is not what you want. The
solution to this is to use the PEEKDATA function. For this example, let's configure an unlimited number of triggers and use PEEKDATA
to see what is happening.
ai.TriggerRepeat = inf;
start(ai);
pause(0.3);
pd1 = peekdata(ai,8000);
pause(0.3);
pd2 = peekdata(ai,8000);
pause(0.3);
pd3 = peekdata(ai,8000);
Warning: The number of samples requested is not available.
The number of samples returned will be reduced.
10. The MathWorks - Demos - Introduction to Analog Output http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 2 19/09/2005 12:35
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Introduction to Analog Output
In this example, you will output data to the sound card on your computer. To get started, you first need to verify that your
environment is set up so that you can send data to your sound card. If you are unsure about this, refer to Appendix A of the Data
Acquisition Toolbox User's Guide.
In this demostration, a sine wave with two different frequencies will be output to the sound card.
To begin, let's create an analog output object associated with the winsound device. Two channels will be added to the analog output
object, ao. This will allow the winsound device to run in stereo mode.
ao = analogoutput('winsound');
addchannel(ao, [1 2]);
Let's configure the analog output object to output the data at 8000 Hz.
set(ao, 'SampleRate', 8000);
Now, let's create the data to output to the sound card - a sine wave at two different frequencies.
t = linspace(0,2*pi,16000);
y = sin(500*t);
y1 = sin(800*t);
OUTPUTTING DATA. Outputting data involves functions that queue the data in the data acquisition engine, and functions that execute
the analog output object.
QUEUING DATA. For data to be output, you must first queue it in the data acquisition engine with the PUTDATA command.
putdata(ao, data);
data is an m-by-n matrix where m is the number of samples to be output and n is the number of output channels.
putdata(ao, [y' y']);
putdata(ao, [y1' y1']);
The analog output object and the data acquisition engine are started with the START command. Starting the output object means that
the hardware device and the data acquisition engine are both running. Running does not necessarily mean that the data is being
output. For data to be output, a trigger must occur.
Let's configure the analog output object to trigger immediately after a START command is issued.
set(ao, 'TriggerType', 'Immediate');
Remember that you can always type the name of the object to get a summary of its current configuration.
ao
Display Summary of Analog Output (AO) Object Using 'Emu10Kx Audio [B800]'.
Output Parameters: 8000 samples per second on each channel.
Trigger Parameters: 1 'Immediate' trigger on START.
Engine status: Waiting for START.
4 total sec. of data currently queued for START.
32000 samples currently queued by PUTDATA.
0 samples sent to output device since START.
AO object contains channel(s):
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [-1 1] 'Volts'
2 'Right' 2 [-1 1] [-1 1] 'Volts'
The analog output object is started, and wait up to 5 seconds for the output to complete.
start(ao);
wait(ao,5);
You can repeatedly output the queued data by using the RepeatOutput property. If RepeatOutput is greater than 0, then all data
12. The MathWorks - Demos - Introduction to Digital Input and Output http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 2 19/09/2005 12:36
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Introduction to Digital Input and Output
In this demo, digital input/output interactions will be explored. This demo will use National Instruments hardware. The information
obtained for this demonstration has been pre-recorded so if you do not have a National Instruments card, you can still see how the
digital input/output interactions are handled by the Data Acquisition Toolbox.
To begin, let's create a digital I/O object associated with National Instruments hardware having a device id of 1. Four output lines will
be added to the digital I/O object from port 0. This configuration will allow you to write values to these lines.
>> dio = digitalio('nidaq', 1);
>> addline(dio, 0:3, 0, 'Out')
Index: LineName: HwLine: Port: Direction:
1 '' 0 0 'Out'
2 '' 1 0 'Out'
3 '' 2 0 'Out'
4 '' 3 0 'Out'
You can write values to the digital I/O lines as either a decimal value or as a binvec value. A binvec value is a binary vector, which is
written with the least significant bit as the leftmost vector element and the most significant bit as the rightmost vector element. For
example, the decimal value 23 is written in binvec notation as
[1 1 1 0 1]
The binvec value is converted to a decimal value as follows
1*2^0 + 1*2^1 + 1*2^2 + 0*2^3 + 1*2^4
The toolbox provides you with two convenience functions for converting between decimal values and binvec values.
You can convert a decimal value to a binvec value with the DEC2BINVEC function.
>> binvec = dec2binvec(196)
binvec =
0 0 1 0 0 0 1 1
You can convert a binvec value to a decimal value with the BINVEC2DEC command.
>> decimal = binvec2dec([1 0 1 0 1 1])
decimal =
53
You can use the PUTVALUE command to write values to the digital I/O object's lines. You can write to a line configured with a direction
of 'Out'. An error will occur if you write to a line configured with a direction of 'In'.
For example, to write the binvec value [ 0 1 0 0 ] to the digital I/O object, dio
>> putvalue(dio, [0 1 0 0]);
Similarly, you can write to a subset of lines as follows
>> putvalue(dio.Line([ 1 3 ]), [ 1 1 ]);
The lines not written to will remain at their current values (in this example, lines with index 2 and index 4 remain at [1 0],
respectively).
It is important to note that if a decimal value is written to a digital I/O object, and the value is too large to be represented by the
object, then an error is returned. Otherwise the word is padded with zeros.
In this example, the digital I/O object contains four lines. Therefore, the largest decimal value allowed is 15 or
(1*2^0 + 1*2^1 + 1*2^2 + 1*2^3).
If the decimal value 5 is written to the digital I/O object, only a three element binvec vector is needed to represent the decimal value.
The remaining line will have a value of 0 written to it. Therefore, the following two commands are equivalent.
>> putvalue(dio, 5);
>> putvalue(dio, [1 0 1 0]);
However, the following command will return an error.
14. The MathWorks - Demos - Logging Data to Disk http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 4 19/09/2005 12:39
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Logging Data to Disk
In this example, you will learn about logging data to a file and reading the data back into the MATLAB workspace.
To get started, an analog input object containing two channels is created.
ai = analoginput('winsound');
ch = addchannel(ai, [1 2]);
Note there are four properties that control how data is logged to disk:
Logging -- type daqhelp Logging for more info
LogFileName -- type daqhelp LogFileName for more info
LoggingMode -- type daqhelp LoggingMode for more info
LogToDiskMode -- type daqhelp LogToDiskMode for more info
With the following settings, data will be logged to the a temporary file and to memory. If another start occurs, the new data will
overwrite the old data in the file.
ai.LogFileName = tempname();
ai.LogToDiskMode = 'overwrite';
ai.LoggingMode = 'Disk&Memory';
Let's configure the analog input object to trigger five times. Each trigger will collect 1000 data samples using a sample rate of 10,000
samples per second.
ai.TriggerType = 'Immediate';
ai.TriggerRepeat = 4;
ai.SamplesPerTrigger = 1000;
ai.SampleRate = 10000;
Since the TriggerType is 'Immediate', the Logging property will be immediately set to 'On' after the analog input object is started with
the START command. Therefore, the data will be immediately sent to the log file upon starting. Then, we'll wait for up to 2 seconds for
the acquisition to complete.
start(ai);
ai.logging
wait(ai,2);
ans =
On
The DAQREAD command is used to read the .daq file. With the following syntax, all the samples logged to disk will be read into the
variable data. data will be an m-by-n matrix where m is the number of samples logged and n is the number of channels. However, if
multiple triggers are logged, the data between triggers are separated by NaNs. In this case, m will be increased by the number of
triggers. The time vector will contain the relative times that each data sample was logged relative to the first trigger.
[data, time] = daqread(ai.LogFileName);
% Now the data can be displayed:
plot(time,data);
15. The MathWorks - Demos - Logging Data to Disk http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 4 19/09/2005 12:39
It is possible to limit the amount of data being read by DAQREAD by using one of the following properties:
Samples Specify the range of samples
Triggers Specify the range of triggers
Time Specify the range of time in seconds
Channels Specify the channel indices
For example the following command will read all samples between the 1000th data sample and the 2000th data sample.
[data,time] = daqread(ai.LogFileName, 'Samples', [1000 2000]);
% The subset of data is now plotted.
plot(time,data);
Similarly, you can restrict the number of Channels read by specifying the 'Channels' property. For example, to read samples 500 to
1000 of the second channel, you would assign the following values to the 'Samples' and 'Channels' properties.
[data,time] = daqread(ai.LogFileName, 'Samples', [500 1000], 'Channels', 2);
% The subset of data is now plotted.
plot(time,data);
You can select the format of the data and time output variables using the following properties where the default value is given in curly
16. The MathWorks - Demos - Logging Data to Disk http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 4 19/09/2005 12:39
braces {}.
DataFormat {double} | native
TimeFormat {vector} | matrix
For example, to read in all the data in native format for the 1st channel only, you would assign the following values to the 'Channels'
and 'DataFormat' properties.
[data,time] = daqread(ai.LogFileName, 'Channels', 1, 'DataFormat', 'native')
;
% The subset of data is now plotted.
plot(time,data);
You can also use the DAQREAD command to read in information related to the object used to log the data and hardware information.
daqinfo = daqread(ai.LogFileName, 'info');
To obtain the object information:
daqinfo.ObjInfo
ans =
BitsPerSample: 16
BufferingConfig: [1024 5]
BufferingMode: 'Auto'
Channel: [1x2 struct]
ChannelSkew: 0
ChannelSkewMode: 'None'
ClockSource: 'Internal'
EventLog: [1x7 struct]
InitialTriggerTime: [2005 8 31 17 16 0.9470]
InputType: 'AC-Coupled'
LogFileName: 'C:Temptp160074.daq'
Logging: 'Off'
LoggingMode: 'Disk&Memory'
LogToDiskMode: 'Overwrite'
ManualTriggerHwOn: 'Start'
Name: 'winsound0-AI'
Running: 'Off'
SampleRate: 11025
SamplesAcquired: 5000
SamplesAvailable: 5000
SamplesPerTrigger: 1000
StandardSampleRates: 'On'
Tag: ''
Timeout: 1
TimerPeriod: 0.1000
TriggerChannel: []
TriggerCondition: 'None'
TriggerConditionValue: 0
TriggerDelay: 0
TriggerDelayUnits: 'Seconds'
TriggerRepeat: 4
TriggersExecuted: 5
TriggerType: 'Immediate'
Type: 'Analog Input'
18. The MathWorks - Demos - Generation of Audio Using the Sound Card http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 2 19/09/2005 12:42
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Generation of Audio Using the Sound Card
In this demo, the data from HANDEL.MAT will be output to the sound card using a data acquisition analog output object. As the data is
being output, the data will be displayed in the axes window.
To begin, an analog output object associated with the winsound device is created. Two channels are then added to the analog output
object, ao. This will allow the winsound device to run in stereo mode.
ao = analogoutput('winsound', 0);
addchannel(ao, [1 2]);
HANDEL.MAT contains two variables:
y - the data that will be output to the sound card
Fs - the sample rate at which the data was originally sampled.
The data and sample rate are loaded from HANDEL.MAT into the MATLAB workspace.
load handel
The analog output object is configured to use the loaded sample rate. For soundcards, we'll turn off the StandardSampleRate
property, in order to allow optimal playback.
set(ao, 'StandardSampleRates','Off')
set(ao, 'SampleRate', Fs);
Fs
Fs =
8192
For the loaded data to be output, it must first be queued in the data acquisition engine with the PUTDATA command. The data being
queued in the data acquisition engine must consist of a column of data for each channel of the analog output object.
data = [y y];
putdata(ao, data);
The analog output object and the data acquisition engine are started with the START command. Starting the output object means that
the hardware device and the data acquisition engine are both running. Running does not necessarily mean that the data is being
output. For data to be output, a trigger must occur. By default, an immediate trigger occurs as soon as the object is started.
A plot is drawn while the sound plays for added effects.
startindex = 1;
increment = 500;
%set(gcf, 'DoubleBuffer', 'on');
start(ao);
while isrunning(ao) % do the plot
while (ao.SamplesOutput < startindex + increment -1), end
try
x = ao.SamplesOutput;
plot(y(x:x+increment-1));
set(gca, 'YLim', [-0.8 0.8], 'XLim',[1 increment])
drawnow;
startindex = startindex+increment;
end
end
20. The MathWorks - Data Acquisition Toolbox 2.7 - Demos http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 2 19/09/2005 12:43
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Acquiring Data with a Sound Card
A typical data acquisition session consists of these four steps:
1. Initialization: Creating a device object.
2. Configuration: Adding channels and controlling acquisition behavior with properties.
3. Execution: Starting the device object and acquiring or sending data.
4. Termination: Deleting the device object.
To verify that the fundamental frequency for the tuning fork is 440Hz, a tone is acquired and then analyzed
in MATLAB. This is the setup for the example described below.
For this example, we will verify that the fundamental (lowest) frequency of a tuning fork is 440 Hz. To do
this, we will use a microphone and a sound card to collect sound level data. Next, we will perform an FFT on
the acquired data to find the frequency components of the tuning fork.
We begin by acquiring two seconds of sound level data on one sound card channel. Since the tuning fork
vibrates at a nominal frequency of 440 Hz, the sound card sampling rate can be set to its lowest sampling
rate of 8000 Hz.
After we have set the tuning fork vibrating and placed it near the microphone, we will trigger the
acquisition. The complete data acquisition session for the sound card is shown below.
Initialization
The first step is to create the analog input object (AI) for the sound card.
AI = analoginput('winsound');
Configuration
Next, we add a single channel to AI, and set the sample rate to 8000 Hz with an acquisition duration of 2
seconds:
addchannel(AI, 1);
Fs = 8000; % Sample Rate is 8000 Hz
set (AI, 'SampleRate', Fs)
duration = 2; % 2 second acquisition
set(AI, 'SamplesPerTrigger', duration*Fs);
Execution
Now, we are ready to start the acquisition. The default trigger behavior is to start collecting data as soon as
the start command is issued. Before doing so, you should strike the tuning fork to begin supplying a tone to
the microphone (whistling will work as well).
start(AI);
22. The MathWorks - Demos - Measuring a Noise Floor Using Custom Tr... http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 3 19/09/2005 12:44
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Measuring a Noise Floor Using Custom Trigger Conditions
This demo shows how to find and acquire a period of at least 2 seconds of relative quiet that occurs between two signals. This would
be useful for applications that need to measure a noise floor and calculate a signal-to-noise ratio.
For this example we will show how to initiate a software trigger when using a custom set of conditions that is more complex than the
standard values provided by the TriggerCondition property of Data Acquisition Toolbox objects.
Contents
Create the Analog Input Object
Define Trigger Condition Information
Configure the Timer Callback
Configure the Trigger Properties
Configure the Amount of Data to Acquire
Start Acquisition
Clean Up
The Timer Callback Function
Create the Analog Input Object
Before acquiring any data, we must create an analog input object and specify the channels from which to acquire data.
When executing the following code, you may need to modify it to match your acquisition hardware.
% Create the analog input object and specify the
% channel that data should be collected from.
ai = analoginput('winsound');
addchannel(ai, 1);
Define Trigger Condition Information
We must initialize a MATLAB structure with the information needed to determine when the custom trigger condition has been met. We
look for
A signal
At least 2 seconds of quiet
% Signal is defined as greater than 0.15 volts.
extraData.signalVoltage = 0.15;
extraData.signalFound = false;
% Quiet is defined as less than 0.04 volts.
extraData.quietVoltage = 0.04;
extraData.secondsOfQuietNeeded = 2;
extraData.secondsOfQuietFound = 0;
extraData.quietFound = false;
We store this information in the UserData property so that it can be accessed and modified by the timer callback.
set(ai, 'UserData', extraData);
Configure the Timer Callback
We use the TimerFcn and TimerPeriod properties to call an M-file function at regular intervals while the acquisition is running. We use
this timer callback function to examine the incoming data to see if the trigger condition has been met.
NOTE: The timer callback function is shown at the end of this demonstration.
% Make timer period 1/10 of our quiet period.
timerPeriod = extraData.secondsOfQuietNeeded/10;
set(ai, 'TimerFcn', @TimerCallback);
set(ai, 'TimerPeriod', timerPeriod);
Configure the Trigger Properties
We use a manual trigger and configure the object to acquire the data during the quiet period.
By setting the TriggerType property to 'manual', data logging will not begin until the trigger function is executed. The timer
callback will execute the trigger when the correct conditions have been met.
In addition, we set the TriggerDelay property to a negative value to indicate that we want to log the quiet period data that occurred
before the trigger was executed.
set(ai, 'TriggerType', 'manual');
23. The MathWorks - Demos - Measuring a Noise Floor Using Custom Tr... http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 3 19/09/2005 12:44
set(ai, 'TriggerDelay', -extraData.secondsOfQuietNeeded);
set(ai, 'TriggerDelayUnits', 'seconds');
Configure the Amount of Data to Acquire
We set the SamplesPerTrigger property to indicate the maximum amount of data that the acquisition should log. However, the timer
callback will stop the acquisition sooner, if it detects a second signal after the quiet period.
sampleRate = get(ai, 'SampleRate');
set(ai, 'SamplesPerTrigger', 10 * extraData.secondsOfQuietNeeded * sampleRat
e);
Start Acquisition
Now, we start the acquisition. After calling the start function, the object will be running, but no data logging will occur until the
trigger function is executed. As the timer callback executes and evaluates the data, messages will be displayed indicating what has
been detected.
start(ai);
try
% Wait for trigger to occur and the acquisition to end.
% Set the timeout to a sufficiently large value.
wait(ai, 60 * extraData.secondsOfQuietNeeded);
% If the acquisition ended successfully, plot the available data.
samplesAvailable = get(ai,'SamplesAvailable');
[data, time] = getdata(ai, samplesAvailable);
plot(time,data);
catch
% If the wait timed out, we end up here.
% Display a message and stop the acquisition.
disp(sprintf('Could not find quiet period of %d seconds.', ...
extraData.secondsOfQuietNeeded));
stop(ai);
end
Warning: The number of samples requested is not available.
The number of samples returned will be reduced.
First signal found. Waiting for quiet period of 2 seconds.
Quiet period found. Logging started.
Second signal found. Acquisition stopped.
Clean Up
When finished, we delete the object and clear the variable from the workspace to free system resources.
delete(ai);
clear ai;
The Timer Callback Function
We use the timer callback function to examine the incoming data to see if our trigger condition has been met. When our trigger
condition has been met, the trigger function is called to start logging.
type TimerCallback;
%%
% The Data Acquisition Toolbox calls the timer callback function with the
% object and event.
function TimerCallback(ai,event)
%%
26. The MathWorks - Demos - Accessing Analog Input Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 5 19/09/2005 12:46
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Accessing Analog Input Channels
In this example, you will learn about creating, accessing, and configuring analog input channels.
To get started, an analog input object, ai, is created for the winsound device.
ai = analoginput('winsound');
ai
Display Summary of Analog Input (AI) Object Using 'Emu10Kx Audio [B800]'.
Acquisition Parameters: 8000 samples per second on each channel.
8000 samples per trigger on each channel.
1 sec. of data to be logged upon START.
Log data to 'Memory' on trigger.
Trigger Parameters: 1 'Immediate' trigger(s) on START.
Engine status: Waiting for START.
0 samples acquired since starting.
0 samples available for GETDATA.
AI object contains no channels.
You can add a channel to an analog input object with the ADDCHANNEL command. ADDCHANNEL needs at least two input arguments.
The first input argument specifies which analog input object the channel is being added to. The second argument is the id of the
hardware channels you are adding to the analog input object. For the sound card, you can add up to two channels. If one channel is
added, sound is recorded and played in mono. If two channels are added, sound is recorded and played in stereo.
addchannel(ai, 1)
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Mono' 1 [-1 1] [-1 1] [-1 1]
'Volts'
There are three methods for accessing a channel. In the first method, the channel is accessed through the analog input object's
Channel property. For example, using the dot notation, all the analog input object's channels will be assigned to the variable ch1.
ch1 = ai.Channel;
Or, using the GET notation
ch1 = get(ai, 'Channel');
ch1
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Mono' 1 [-1 1] [-1 1] [-1 1]
'Volts'
In the second method, the channel is accessed at creation time by assigning an output variable to ADDCHANNEL. The third input
argument to ADDCHANNEL assigns the name Chan2 to the added channel.
addchannel(ai, 2, 'Chan2')
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
2 'Chan2' 2 [-1 1] [-1 1] [-1 1]
'Volts'
In the third method, the channel is accessed through its ChannelName property value. This method is referred to as Named
Referencing. The second channel added to the analog input object was assigned the ChannelName 'Chan2'. Therefore, you can access
the second channel with the command:
ch2 = ai.Chan2;
ch2
27. The MathWorks - Demos - Accessing Analog Input Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 5 19/09/2005 12:46
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
2 'Chan2' 2 [-1 1] [-1 1] [-1 1]
'Volts'
Channels that have the same parent (or are associated with the same analog input object) can be concatenated into either row or
column vectors. An error will occur if you try to concatentate channels into a matrix.
ch = [ch1 ch2];
s = size(ch);
s
s =
1 2
Or
ch = [ch1; ch2];
s1 = size(ch);
s1
s1 =
2 1
You can access specific channels by specifying the index of the channel in the analog input object's channel array.
ch1 = ai.Channel(1); % To obtain the first channel
ch2 = ai.Channel(2); % To obtain the second channel
ch1
ch2
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [-1 1] [-1 1] 'Volts'
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
2 'Chan2' 2 [-1 1] [-1 1] [-1 1]
'Volts'
Or, if a 1-by-5 channel array is created, it is possible to access the first, third, and fourth channels as follows:
charray = [ch1 ch2 ch1 ch1 ch2];
temp = charray([1 3 4]);
charray
temp
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Left' 1 [-1 1] [-1 1] [-1 1]
'Volts'
2 'Chan2' 2 [-1 1] [-1 1] [-1 1]
'Volts'
1 'Left' 1 [-1 1] [-1 1] [-1 1]
'Volts'
1 'Left' 1 [-1 1] [-1 1] [-1 1]
'Volts'
2 'Chan2' 2 [-1 1] [-1 1] [-1 1]
'Volts'
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Left' 1 [-1 1] [-1 1] [-1 1]
'Volts'
1 'Left' 1 [-1 1] [-1 1] [-1 1]
'Volts'
1 'Left' 1 [-1 1] [-1 1] [-1 1]
28. The MathWorks - Demos - Accessing Analog Input Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 5 19/09/2005 12:46
'Volts'
You can obtain information regarding the channel with the GET command. When passing only the channel to GET, a list of all
properties and their current values are displayed. The common properties are listed first. If any device-specific channel properties
exist, they will be listed second.
get(ch1)
ChannelName = Left
HwChannel = 1
Index = 1
InputRange = [-1 1]
NativeOffset = 1.5259e-005
NativeScaling = 3.0518e-005
Parent = [1x1 analoginput]
SensorRange = [-1 1]
Type = Channel
Units = Volts
UnitsRange = [-1 1]
If an output variable is supplied to the GET command, a structure is returned where the structure field names are the channel's
property names, and the structure field values are the channel's property values.
h = get(ch2);
h
h =
ChannelName: 'Chan2'
HwChannel: 2
Index: 2
InputRange: [-1 1]
NativeOffset: 1.5259e-005
NativeScaling: 3.0518e-005
Parent: [1x1 analoginput]
SensorRange: [-1 1]
Type: 'Channel'
Units: 'Volts'
UnitsRange: [-1 1]
You can obtain information pertaining to a specific property by specifying the property name as the second input argument to GET
(e.g. ch1).
If the channel array is not 1-by-1, a cell array of property values is returned (e.g. ch).
get(ch1, 'Units')
get(ch, 'Units')
ans =
Volts
ans =
'Volts'
'Volts'
You can obtain information pertaining to multiple properties by specifying a cell array of property names as the second input argument
to GET (e.g. ch2).
If the channel array is not singular, and a cell array of property names is passed to GET, then a matrix of property values is returned
(e.g. ch).
The returned property values matrix relate to each object and property name as follows:
get(ch2, {'ChannelName','HwChannel','Units'})
get(ch, {'ChannelName','HwChannel','Units'})
ans =
'Chan2' [2] 'Volts'
29. The MathWorks - Demos - Accessing Analog Input Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
4 de 5 19/09/2005 12:46
ans =
'Left' [1] 'Volts'
'Chan2' [2] 'Volts'
Note that you can also use the dot notation to obtain information about each channel.
ch1.Units
ai.Channel(2).ChannelName
And you can also obtain channel information through named referencing.
ai.Chan2.InputRange
You can assign values to different channel properties with the SET command. If only the channel is passed to SET, a list of settable
properties and their possible values are returned. Similar to the GET display, the common properties are listed first. If any
device-specific channel properties exist, they will be listed second.
set(ch1)
If you supply an output variable to SET, a structure is returned where the structure field names are the channel's property names and
the structure field values are the possible property values for the channel property.
h = set(ch1);
h
h =
ChannelName: {}
HwChannel: {}
InputRange: {}
SensorRange: {}
Units: {}
UnitsRange: {}
You can obtain information on possible property values for a specific property by specifying the property name as the second input
argument to SET.
set(ch1, 'Units');
Or, you can assign the result to an output variable.
unit = set(ch1, 'Units');
You can assign values to a specific property as follows
set(ch1, 'SensorRange', [-2 2]);
ch
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Left' 1 [-1 1] [-2 2] [-1 1]
'Volts'
2 'Chan2' 2 [-1 1] [-1 1] [-1 1]
'Volts'
You can assign the same property values to multiple channels with one call to SET.
set(ch, 'SensorRange', [-3 3]);
ch
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Left' 1 [-1 1] [-3 3] [-1 1]
'Volts'
2 'Chan2' 2 [-1 1] [-3 3] [-1 1]
'Volts'
You can assign different property values to multiple channels by specifying a cell array of property values in the SET command.
set(ch, {'SensorRange'}, {[-2 2];[-1 1]});
ch
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Left' 1 [-1 1] [-2 2] [-1 1]
31. The MathWorks - Demos - Using Analog Input Triggers http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 5 19/09/2005 12:47
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Using Analog Input Triggers
In this demo, we are going to explore the properties related to triggering and acquire 3000 samples of data using an immediate,
manual, and software triggers.
TRIGGERS. A trigger is defined as an event that initiates the logging of data to memory and/or a disk file. The logging status is
indicated by the Logging property. When a trigger occurs, the Logging property is set to On. The destination for logged data is
indicated by the LoggingMode property. You can log data to memory or a disk file. By default, the data is logged to memory.
An analog input object can log data using an immediate trigger, a manual trigger, or a software trigger. The trigger type is indicated
by the TriggerType property. An immediate trigger is the default trigger type.
IMMEDIATE TRIGGERS. An immediate trigger begins logging data immediately after the START command is issued.
First, let's create the analog input object ai and add two channels to it. This will allow the winsound device to run in stereo mode. The
analog input object will be configured to acquire 8000 samples per second.
ai = analoginput('winsound');
addchannel(ai, [1 2]);
set(ai, 'SampleRate', 8000);
The number of data samples that the trigger will acquire is indicated by the SamplesPerTrigger property. The analog input object will
be configured to acquire 3000 samples per trigger. The ai object is also configured to acquire data immediately.
set(ai, 'SamplesPerTrigger', 3000);
set(ai, 'TriggerType', 'immediate');
As soon as the analog input object is started, the trigger will occur. When the trigger executes, the number of samples specified by
the SamplesPerTrigger property is acquired for each channel and stored in the data acquisition engine.
start(ai);
You can retrieve the data from the data acquisition engine with the GETDATA function.
The size of data will be the number of samples per trigger by the number of channels.
[data,time] = getdata(ai);
size(data)
%
ans =
3000 2
The data can be plotted against time with the trigger occurring at time = 0. As you can see, it took 0.375 seconds to acquire the data.
This time is calculated by taking the ratio SamplesPerTrigger/SampleRate.
plot(time,data);
zoom on;
title('Immediate Trigger');
xlabel('Relative time in seconds.');
ylabel('Data in volts');
32. The MathWorks - Demos - Using Analog Input Triggers http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 5 19/09/2005 12:47
REPEATING TRIGGERS. You can configure triggers to occur repeated times. Trigger repeats are controlled by the TriggerRepeat
property. When the TriggerRepeat property is set to its default value of 0, the trigger will occur once when the trigger condition is
met. If the TriggerRepeat property is set to a positive integer, then the trigger is repeated the specified number of times when the
trigger condition is met. If TriggerRepeat is set to Inf, then the trigger repeats continuously when the trigger condition is met and the
data acquisition can be stopped only with the STOP command.
With an immediate trigger, each trigger will occur immediately after the previous trigger has finished executing.
Let's configure the analog input object, ai, to acquire 3000 samples with two immediate triggers.
And start the analog input object.
set(ai, 'TriggerType', 'immediate');
set(ai, 'SamplesPerTrigger', 1500);
set(ai, 'TriggerRepeat', 1);
start(ai);
You can retrieve the data from the data acquisition engine with the GETDATA function.
The first command extracts the first 1500 samples from the data acquisition engine.
The second command extracts the second 1500 samples from the data acquisition engine.
[data1,time1] = getdata(ai);
[data2,time2] = getdata(ai);
You can plot the data against time with the first trigger occuring at time = 0.
plot(time1,data1, 'Color', 'red');
hold on
plot(time2,data2, 'Color', 'blue');
zoom on
title('Immediate Triggers - Using TriggerRepeat=1');
xlabel('Relative time in seconds.');
ylabel('Data in volts');
hold off
MANUAL TRIGGERS. A manual trigger begins logging data after you manually issue the TRIGGER command.
Let's configure the analog input object, ai, to acquire 3000 samples at 8000 samples per second with one manual trigger.
33. The MathWorks - Demos - Using Analog Input Triggers http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 5 19/09/2005 12:47
And then start the analog input object with the START command.
set(ai, 'SamplesPerTrigger', 3000);
set(ai, 'SampleRate', 8000);
set(ai, 'TriggerType', 'manual');
set(ai, 'TriggerRepeat', 0);
start(ai);
The data acquisition engine will be running as soon as the START command is issued. However, the data samples will not be stored in
the data acquisition engine until the TRIGGER command is issued. Therefore, the number of samples available from the data
acquisition engine will be zero.
get(ai, 'Running')
get(ai, 'SamplesAvailable')
ans =
On
ans =
0
Now let's execute the manual trigger.
trigger(ai)
You can retrieve the 3000 data samples stored in the data acquisition engine with the GETDATA command.
The data can be plotted against time. As you can see, it took 0.375 seconds to acquire the data. This time is calculated by taking the
ratio SamplesPerTrigger/SampleRate.
[data,time] = getdata(ai);
plot(time,data);
zoom on;
title('Manual Trigger');
xlabel('Relative time in seconds.');
ylabel('Data in volts');
TRIGGER DELAYS. Trigger delays allow you to control exactly when data is logged after a trigger executes. You can log data either
before a trigger executes or after a trigger executes. Trigger delays are specified with the TriggerDelay property.
Logging data before a trigger occurs is called pretriggering, while logging data after a trigger occurs is called postriggering. A
pretrigger is specified by a negative TriggerDelay property value, while a postrigger is specified with a positive TriggerDelay property
value.
You can delay triggers either in seconds or samples using the TriggerDelayUnits property.
Let's configure the analog input object to acquire a total of 3000 samples. 1000 samples will be acquired before the manual trigger
occurs and 2000 samples will be acquired after the manual trigger occurs.
set(ai, 'TriggerType', 'manual');
set(ai, 'SamplesPerTrigger', 3000);
set(ai, 'TriggerDelay', -1000);
set(ai, 'TriggerDelayUnits', 'samples');
34. The MathWorks - Demos - Using Analog Input Triggers http://www.mathworks.com/products/daq/demos.html?file=/products...
4 de 5 19/09/2005 12:47
The analog input object is started and the data acquisition engine will start running.
start(ai);
status = get(ai, 'Running')
status =
On
The toolbox needs an opportunity to acquire the pretrigger data. We'll pause here for 1.5 seconds to allow data to accumulate in the
pretriggering buffer
pause(1.5);
Let's trigger the analog input object now, and then wait for up to two seconds for the acquisition to complete.
trigger(ai);
wait(ai,2)
You can retrieve the 3000 data samples stored in the data acquisition engine with the GETDATA command.
The data can be plotted against time with the trigger occurring at time = 0. Therefore, the pretriggered data will be plotted with a
negative time value and the data acquired after the trigger will be plotted with a positive time value.
[data,time] = getdata(ai);
plot(time,data);
zoom on;
title('Immediate Triggers');
xlabel('Relative time in seconds.');
ylabel('Data in volts');
SOFTWARE TRIGGERS. A software trigger begins logging data when a signal satsifying the specified condition is detected on one of the
specified channels.
The channel used as the trigger source is defined by the TriggerChannel property. The condition that must be satisfied for a trigger to
occur is specified by the TriggerCondition property. You can set this property to one of the following values:
Rising - The signal must be above the specified value and rising.
Falling - The signal must be below the specified value and falling.
Leaving - The signal must be leaving the specified range of values.
Entering - The signal must be entering the specified range of values.
The specified value or range that the trigger condition must meet is indicated by the TriggerConditionValue property.
Let's configure the analog input object, ai, to acquire 3000 samples at 8000 samples per second with one software trigger. The trigger
will occur when a signal on the first channel has a rising edge and passes through 0.013 volts.
set(ai, 'TriggerType', 'software');
set(ai, 'TriggerRepeat', 0);
set(ai, 'TriggerCondition', 'rising');
set(ai, 'TriggerConditionValue', 0.013);
set(ai, 'TriggerChannel', ai.channel(1));
To capture one second worth of data before the trigger occurs The data acquisition engine will wait for 2 seconds for this condition to
be met before stopping.
Also start the analog input object.
set(ai, 'TriggerDelay', -1);
36. The MathWorks - Demos - Counting Complex Events Using Analog I... http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 4 19/09/2005 12:48
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Counting Complex Events Using Analog Input Data
Although many data acquisition devices have counters built into them, sometimes the built-in counters are not sufficient. For example,
your signal might be too noisy to be reliably counted using a standard counter, or your signal might not conform to the voltage
requirements of the counter.
This demo shows you how to use an analog input channel from a data acquisition device to acquire the signal and then postprocess it
in MATLAB to count the number of pulses. The demo uses an analog input channel from a Measurement Computing PMD-1208LS, but
almost any supported data acquisition device will work with minimal changes to the code.
The hardware for this demo is a mechanical push button switch that is switching a 5-volt signal on and off. It is difficult to count the
number of times that a mechanical push button has been pressed because of bouncing. When a switch is closed it sometimes
momentarily opens before closing again. While there are circuits that can minimize the bouncing effect, it is not always practical to use
one. MATLAB can easily be used to debounce a switch.
Contents
Create the Analog Input Object
Configure the Analog Input Object
Acquire and View the Data
Find the Pulse Edges
Find the Duration of Each Pulse
Eliminate the Bounces
Count the Pulses
Clean Up
Summary
Create the Analog Input Object
Before acquiring any data, you must create an analog input object and specify the channels from which to acquire data.
% Create the analog input object. The arguments to the ANALOGINPUT command
% might need to be changed for your particular hardware.
ai = analoginput('mcc', 0);
% Specify the channel that data should be collected from.
ch = addchannel(ai, 0);
Configure the Analog Input Object
Now that you have created the analog input object, it must be configured for this particular acquisition. For this acquisition, configure
the hardware with:
The SampleRate property set to 1000 samples per second
The SamplesPerTrigger property set to 5000 samples
% Set the sample rate.
set(ai, 'SampleRate', 1000);
% Change the number of samples to acquire.
set(ai, 'SamplesPerTrigger', 5000);
disp(ai)
Display Summary of Analog Input (AI) Object Using 'PMD-1208LS'.
Acquisition Parameters: 1000 samples per second on each channel.
5000 samples per trigger on each channel.
5 sec. of data to be logged upon START.
Log data to 'Memory' on trigger.
Trigger Parameters: 1 'Immediate' trigger(s) on START.
Engine status: Waiting for START.
0 samples acquired since starting.
0 samples available for GETDATA.
AI object contains channel(s):
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 '' 0 [-20 20] [-20 20] [-20 20]
'Volts'
37. The MathWorks - Demos - Counting Complex Events Using Analog I... http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 4 19/09/2005 12:48
Acquire and View the Data
To acquire the data, you issue the start command to the analog input object. You can then use the wait command to wait for the
acquisition to be completed, and the getdata command to return the data to MATLAB. The getdata command can return the time
that each sample was taken, in addition to the actual sample. When you start the acquisition, all parameters are verified by the
hardware and possibly updated based upon the capabilities of the hardware in the current configuration.
% Start the acquisition.
start(ai)
% Wait for the acquisition to finish. Wait a few extra seconds to account
% for any overhead in starting the acquisition.
wait(ai, 10);
% Get the data.
[data time] = getdata(ai);
% Plot the data.
plot(time, data)
Warning: SampleRate changed at start.
Find the Pulse Edges
Finding the edges of the pulses is easy in MATLAB. You simply set a threshold and then look for consecutive samples that are on
opposite sides of the threshold. The easiest way to do this to create a duplicate vector of data that is offset from the original data by
one sample. Because the pulse time is important, you need to find the rising and falling edges of each pulse. The output of this step is
a plot where the unwanted bounces are shown with overlapping x's and o's.
% Set the threshold to 3.5 V.
threshold = 3.5;
% Create the offset data. Need to append a NaN to the final sample since
% both vectors need to have the same length.
offsetData = [data(2:end); NaN];
% Find the rising edge.
risingEdge = find(data < threshold & offsetData > threshold);
% Find the falling edge.
fallingEdge = find(data > threshold & offsetData < threshold);
% Show the rising edges with red x's.
hold on
plot(time(risingEdge), threshold, 'rx');
% Show the falling edges with green o's.
plot(time(fallingEdge), threshold, 'go');
hold off
38. The MathWorks - Demos - Counting Complex Events Using Analog I... http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 4 19/09/2005 12:48
Find the Duration of Each Pulse
A switch bounce is represented by a very short duration pulse. To find the duration of each pulse, you need to combine the rising edge
and falling edge times into a single vector. The difference of any two consecutive times shows the duration of a pulse.
% Construct a vector to hold all of the times.
pulseIndices = zeros(length(risingEdge) * 2, 1);
% Store the rising edge times.
pulseIndices(1:2:end) = risingEdge;
% Store the falling edge times.
pulseIndices(2:2:end) = fallingEdge;
% Compute the pulse durations.
pulseTimes = diff(time(pulseIndices))
pulseTimes =
0.0719
0.1976
0.0399
0.1557
0.0190
0.4631
0.0549
0.1188
0.0379
0.5230
0.0669
0.1028
0.0579
0.1677
0.0489
0.0010
0.0110
0.0998
0.0709
0.1178
0.0818
0.1188
0.0719
0.0100
0.0020
0.1257
0.0519
0.1248
0.0709
0.1257
0.0629
Eliminate the Bounces
By analyzing the pulse durations, you can determine the length of pulses that should be ignored. For this demo, pulses shorter that 50
ms are removed.
% Create a variable for the processed data.
processedData = data;
40. The MathWorks - Demos - Accessing Analog Output Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 4 19/09/2005 12:49
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Accessing Analog Output Channels
There are three methods for accessing a channel. In the first method, the channel is accessed through the analog output object's
Channel property. For example, using the dot notation, all the analog output object's channels will be assigned to the variable ch1.
Or, using the get notation.
ch1 = ao.Channel; % dot notation
ch1 = get(ao, 'Channel'); % get notation
ch1
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Mono' 1 [-1 1] [-1 1] 'Volts'
In the second method, the channel is accessed at creation time by assigning an output variable to ADDCHANNEL.
The third input argument to ADDCHANNEL assigns the name Chan2 to the channel created.
ch2 = addchannel(ao, 2, 'Chan2');
ch2
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
2 'Chan2' 2 [-1 1] [-1 1] 'Volts'
In the third method, the channel is accessed through its ChannelName property value. This method is referred to as named
referencing. The second channel added to the analog output object was assigned the ChannelName 'Chan2'. Therefore, the second
channel can be accessed with the command:
ch2 = ao.Chan2;
ch2
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
2 'Chan2' 2 [-1 1] [-1 1] 'Volts'
Channels that have the same parent (or are associated with the same analog output object) can be concatenated into either row or
column vectors. Note an error will occur if you try to concatentate channels into a matrix.
cha = [ch1 ch2]; % row concatenation
ch = [ch1; ch2]; % column concatenation
size(cha)
size(ch)
ans =
1 2
ans =
2 1
You can access specific channels by specifying the index of the channel in the analog output object's channel array.
ch1 = ao.Channel(1); % To obtain the first channel
ch2 = ao.Channel(2); % To obtain the second channel
ch1
ch2
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [-1 1] 'Volts'
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
2 'Chan2' 2 [-1 1] [-1 1] 'Volts'
41. The MathWorks - Demos - Accessing Analog Output Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 4 19/09/2005 12:49
Or, if a 1-by-5 channel array is created, it is possible to access the first, third, and fourth channels as follows:
charray = [ch1 ch2 ch1 ch1 ch2]
temp = charray([1 3 4])
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [-1 1] 'Volts'
2 'Chan2' 2 [-1 1] [-1 1] 'Volts'
1 'Left' 1 [-1 1] [-1 1] 'Volts'
1 'Left' 1 [-1 1] [-1 1] 'Volts'
2 'Chan2' 2 [-1 1] [-1 1] 'Volts'
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [-1 1] 'Volts'
1 'Left' 1 [-1 1] [-1 1] 'Volts'
1 'Left' 1 [-1 1] [-1 1] 'Volts'
You can obtain information regarding the channel with the GET command. When passing only the channel to GET, a list of all
properties and their current values are displayed. The common properties are listed first. If any device-specific channel properties
exist, they will be listed second.
get(ch1)
ChannelName = Left
DefaultChannelValue = 0
HwChannel = 1
Index = 1
NativeOffset = -0.5
NativeScaling = 32767.5
OutputRange = [-1 1]
Parent = [1x1 analogoutput]
Type = Channel
Units = Volts
UnitsRange = [-1 1]
If an output variable is supplied to the GET command, a structure is returned where the structure field names are the channel's
property names and the structure field values are the channel's property values.
h = get(ch2)
h =
ChannelName: 'Chan2'
DefaultChannelValue: 0
HwChannel: 2
Index: 2
NativeOffset: -0.5000
NativeScaling: 3.2768e+004
OutputRange: [-1 1]
Parent: [1x1 analogoutput]
Type: 'Channel'
Units: 'Volts'
UnitsRange: [-1 1]
You can obtain information pertaining to a specific property by specifying the property name as the second input argument to GET.
get(ch1, 'Units')
ans =
Volts
If the channel array is not 1-by-1, a cell array of property values is returned.
get(ch, 'Units')
ans =
'Volts'
'Volts'
You can obtain information pertaining to multiple properties by specifying a cell array of property names as the second input argument
42. The MathWorks - Demos - Accessing Analog Output Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 4 19/09/2005 12:49
to GET.
get(ch2, {'ChannelName','HwChannel','Units'})
ans =
'Chan2' [2] 'Volts'
If the channel array is not singular and a cell array of property names is passed to GET, then a matrix of property values is returned.
The returned property values matrix relate to each object and property name as follows:
get(ch, {'ChannelName','HwChannel','Units'})
ans =
'Left' [1] 'Volts'
'Chan2' [2] 'Volts'
You can also use the dot notation to obtain information about each channel. For example, ch1.Units; or
ao.Channel(2).ChannelName;
You can also obtain channel information through named referencing. For example: ao.Chan2.OutputRange
You can assign values to different channel properties with the SET command. If only the channel is passed to SET, a list of settable
properties and their possible values are returned. Similar to the GET display, the common properties are listed first. If any device
specific channel properties exist, they will be listed second.
set(ch1)
ChannelName
DefaultChannelValue
HwChannel
OutputRange
Units
UnitsRange
If you supply an output variable to SET, a structure is returned where the structure field names are the channel's property names and
the structure field values are the possible property values for the channel property.
h = set(ch1)
h =
ChannelName: {}
DefaultChannelValue: {}
HwChannel: {}
OutputRange: {}
Units: {}
UnitsRange: {}
You can obtain information on possible property values for a specific property by specifying the property name as the second input
argument to SET. For example, set(ch1, 'Units') or unit = set(ch1, 'Units') to assign the result to an output variable.
You can assign values to a specific property as follows:
set(ch1, 'UnitsRange', [0 100]);
ch
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [0 100] 'Volts'
2 'Chan2' 2 [-1 1] [-1 1] 'Volts'
You can assign the same property values to multiple channels with one call to SET.
set(ch, 'UnitsRange', [-50 50]);
ch
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [-50 50] 'Volts'
2 'Chan2' 2 [-1 1] [-50 50] 'Volts'
You can assign different property values to multiple channels by specifying a cell array of property values in the SET command.
44. The MathWorks - Demos - Using Analog Output Triggers http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 2 19/09/2005 12:51
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Using Analog Output Triggers
In this demo, we are going to explore the properties related to triggering, and output data using an immediate and manual trigger.
An immediate trigger automatically occurs just after the START command is issued.
To demonstrate let's create the analog output object ao and add two channels to it. This will allow the winsound device to run in
stereo mode. The analog output object will be configured to output 8000 samples per second.
Note: The ao object is configured to output data immediately.
ao = analogoutput('winsound');
addchannel(ao, [1 2]);
set(ao, 'SampleRate', 8000);
set(ao, 'TriggerType', 'Immediate');
Now Let's define the data to output, which is nothing more than a sine wave with a frequency of 500 Hz.
y = sin(500*(0:(2*pi/8000):2*pi))';
Outputting data involves functions that queue the data in the data acquisition engine and functions that execute the analog output
object.
For data to be output, you must first queue it in the data acquisition engine with the PUTDATA command.
putdata(ao, data);
data is an m-by-n matrix where m is the number of samples to be output and n is the number of output channels.
putdata(ao, [y y]);
As soon as the analog output object is started, the trigger will occur. When the trigger executes, the data queued in the data
acquisition engine will be output to the sound card. 8000 samples are being output at 8000 samples per second.
It should take approximately one second to output the data.
start(ao); tic, while isrunning(ao) end; toc
Elapsed time is 1.010682 seconds.
You can configure the analog output object to output the queued data repeatedly with the RepeatOutput property. If RepeatOutput is
greater than 0, then all data queued before the START command is issued will be requeued the specified number of times.
Let's configure the analog output object, ao, to output the queued data three times.
set(ao, 'RepeatOutput', 2);
putdata(ao, [y y]);
Once the analog output object is started. It should take three seconds to output the data.
start(ao); tic, while isrunning(ao) end; toc
Elapsed time is 3.009971 seconds.
A manual trigger begins outputting data after you manually issue the TRIGGER command.
Let's configure the analog output object, ao, to output data at 8000 samples per second with one manual trigger.
set(ao, 'SampleRate', 8000);
set(ao, 'TriggerType', 'manual');
set(ao, 'RepeatOutput', 0);
putdata(ao, [y y]);
The analog output object is started with the START command.
The data acquisition engine will be running as soon as the START command is issued.
However, the data samples will not be output to the sound card until the TRIGGER command is issued. Therefore, the number of
samples output from the data acquisition engine will be zero.
start(ao);
get(ao, 'Running')
get(ao, 'SamplesOutput')
46. The MathWorks - Demos - Accessing Digital Lines http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 4 19/09/2005 12:52
Productos y servicios Industrias Educación Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Accessing Digital Lines
In this demo, you will learn about creating, accessing, and configuring digital I/O lines. This demo will use National Instruments
hardware. The information obtained for this demonstration has been pre-recorded. Therefore, if you do not have a National
Instruments card, you can still learn about digital I/O lines.
To get started, a digital I/O object, dio, associated with National Instrument hardware is created.
>> dio = digitalio('nidaq', 1);
You can add a line to a digital I/O object with the ADDLINE command. ADDLINE needs at least three input arguments. The first input
argument specifies which digital I/O object the line is being added to. The second argument is the id of the hardware line you are
adding to the digital I/O object. The third input argument specifies the direction of the line. The direction can be either 'In' in which
case the line is read from, or 'Out' in which case the line is written to.
>> addline(dio, 0, 'In');
There are three methods for accessing a line. In the first method, the line is accessed through the digital I/O object's Line property.
For example, using the dot notation, all the digital I/O object's lines will be assigned to the variable line1.
>> line1 = dio.Line
Index: LineName: HwLine: Port: Direction:
1 '' 0 0 'In'
Or, using the get notation
>> line1 = get(dio, 'Line')
Index: LineName: HwLine: Port: Direction:
1 '' 0 0 'In'
In the second method, the line is accessed at creation time by assigning an output variable to ADDLINE.
The fourth input argument to ADDLINE assigns the name Line2 to the line created.
>> line2 = addline(dio, 1, 'Out', 'Line2')
Index: LineName: HwLine: Port: Direction:
2 'Line2' 1 0 'Out'
In the third method, the line is accessed through its LineName property value. This method is referred to as named referencing. The
second line added to the digital I/O object was assigned the LineName 'Line2'. Therefore, the second line can be accessed with the
command
>> line2 = dio.Line2
Index: LineName: HwLine: Port: Direction:
2 'Line2' 1 0 'Out'
Lines that have the same parent (or are associated with the same digital I/O object) can be concatenated into either row or column
vectors. An error will occur if you try to concatentate lines into a matrix.
>> daqline = [line1 line2];
>> size(daqline)
ans =
1 2
Or
>> daqline = [line1;line2];
>> size(daqline)
ans =
2 1
You can access specific lines by specifying the index of the line in the digital I/O object's line array. To obtain the first line:
>> line1 = dio.Line(1)
Index: LineName: HwLine: Port: Direction:
1 '' 0 0 'In'
47. The MathWorks - Demos - Accessing Digital Lines http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 4 19/09/2005 12:52
To obtain the second line
>> line2 = dio.Line(2)
Index: LineName: HwLine: Port: Direction:
2 'Line2' 1 0 'Out'
Or, if a 1-by-5 line array is created, it is possible to access the first, third, and fourth lines as follows
>> linearray = [line1 line2 line1 line1 line2]
Index: LineName: HwLine: Port: Direction:
1 '' 0 0 'In'
2 'Line2' 1 0 'Out'
1 '' 0 0 'In'
1 '' 0 0 'In'
2 'Line2' 1 0 'Out'
>> temp = linearray([1 3 4])
Index: LineName: HwLine: Port: Direction:
1 '' 0 0 'In'
1 '' 0 0 'In'
1 '' 0 0 'In'
You can obtain information regarding the line with the GET command. When passing only the line to GET, a list of all properties and
their current values are displayed. The common properties are listed first. If any device-specific line properties exist, they will be listed
second.
>> get(line1)
Direction = In
HwLine = 0
Index = 1
LineName =
Parent = [1x1 digitalio]
Port = 0
If an output variable is supplied to the GET command, a structure is returned where the structure field names are the line's property
names and the structure field values are the line's property values.
>> h = get(line2)
h =
Direction: 'Out'
HwLine: 1
Index: 2
LineName: 'Line2'
Parent: [1x1 digitalio]
Port: 0
You can obtain information pertaining to a specific property by specifying the property name as the second input argument to GET.
>> get(line1, 'Direction')
ans =
In
If the line array is not 1-by-1, a cell array of property values is returned.
>> get(daqline, 'Direction')
ans =
'In'
'Out'
You can obtain information pertaining to multiple properties by specifying a cell array of property names as the second input argument
to GET.
>> get(line2, {'LineName','HwLine','Direction'})
ans =
'Line2' [1] 'Out'
If the line array is not singular and a cell array of property names is passed to GET, then a matrix of property values is returned.
>> get(daqline, {'LineName','HwLine','Direction'})
ans =
48. The MathWorks - Demos - Accessing Digital Lines http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 4 19/09/2005 12:52
'' [0] 'In'
'Line2' [1] 'Out'
The returned property values matrix relate to each object and property name as follows
LineName HwLine Direction
line1 '' [0] 'In'
line2 'Line2' [1] 'Out'
You can use the dot notation to obtain information from each line.
>> line1.Direction
ans =
In
>> dio.Line(2).LineName
ans =
Line2
You can also obtain line information through named referencing.
>> dio.Line2.Direction
ans =
Out
You can assign values to different line properties with the SET command. If only the line is passed to SET, a list of settable properties
and their possible values are returned. Similar to the GET display, the common properties are listed first. If any device-specific line
properties exist, they will be listed second.
>> set(line1)
Direction: [ {In} | Out ]
HwLine
LineName
If you supply an output variable to SET, a structure is returned where the structure field names are the line's property names and the
structure field values are the possible property values for the line property.
>> h=set(line1)
h =
Direction: {2x1 cell}
HwLine: {}
LineName: {}
You can obtain information on possible property values for a specific property by specifying the property name as the second input
argument to SET.
>> set(line1, 'Direction')
[ {In} | Out ]
Or, you can assign the result to an output variable.
>> direction = set(line1, 'Direction')
direction =
'In'
'Out'
You can assign values to a specific property as follows
>> set(line1, 'LineName', 'Line1');
>> daqline
Index: LineName: HwLine: Port: Direction:
1 'Line1' 0 0 'In'
2 'Line2' 1 0 'Out'
You can assign the same property values to multiple lines with one call to SET.
>> set(daqline, 'Direction', 'Out');
>> daqline
Index: LineName: HwLine: Port: Direction:
1 'Line1' 0 0 'Out'