You are on page 1of 52

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


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





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 Educacin 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}
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
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
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.
The MathWorks - Demos - Introduction to the Data Acquisition Toolbox http://www.mathworks.com/products/daq/demos.html?file=/products...
5 de 5 19/09/2005 12:26
A start event is generated immediately after the START command is issued
.
This event executes the M-file specified for StartFcn.
When the StartFcn M-file has finished executing, Running is automaticall
y
set to On and the device object and hardware device begin executing.
Start event information is stored in the EventLog property.
See also EventLog, Running.
DAQHELP can also be used to display Data Acquisition Toolbox function help. This can be useful in accessing a function's help since
MATLAB requires that an object's classname be used for commands with multiple instances.
By using DAQHELP, you do not have to know an object's classname to get the correct help.
daqhelp delete
DELETE Remove data acquisition objects from the engine.

DELETE(OBJ) removes object, OBJ, from the data acquisition engine.
If any channels or lines are associated with OBJ, they are also
deleted. OBJ can be either a device array or a channel/line.

If OBJ is the last object accessing the identified hardware, the
associated hardware driver and driver specific adaptor are closed
and unloaded.

Using CLEAR removes OBJ from the workspace only.

DELETE should be used at the end of a data acquisition session.

If OBJ is running, DELETE(OBJ) will delete OBJ and a warning
will be issued. If OBJ is running and logging/sending, DELETE(OBJ)
will not delete OBJ and an error will be returned.

If multiple references to a data acquisition object exist in the
workspace, deleting one reference will invalidate the remaining
references. These remaining references should be cleared from
the workspace.

Example:
ai = analoginput('winsound');
aiCopy = ai;
delete(ai)
When finished, we delete the object and clear the variable from the workspace to free system resources.
delete(ai);
delete(ao);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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.
The MathWorks - Demos - Introduction to Analog Input http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 2 19/09/2005 12:29
Warning: The number of samples requested is not available.
The number of samples returned will be reduced.
Warning: The number of samples requested is not available.
The number of samples returned will be reduced.
Notice that the PEEKDATA function didn't block and that it returns only data that is available. We asked for 8000 samples but did not
necessarily get that many.
whos pd1 pd2 pd3
Name Size Bytes Class
pd1 2048x1 16384 double array
pd2 4608x1 36864 double array
pd3 7168x1 57344 double array
Grand total is 13824 elements using 110592 bytes
This completes the introduction to analog input objects. Since the analog input object is no longer needed, you should:
First stop the analog input object from running using the STOP command. Lastly, delete it with the DELETE command to free memory
and other physical resources.
stop(ai);
delete(ai);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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
The MathWorks - Demos - Introduction to Analog Output http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 2 19/09/2005 12:35
queued before START is issued will be repeated the specified number of times.
Let's configure the analog output object to send the data to the sound card two times (or repeated once).
set(ao, 'RepeatOutput', 1);
putdata(ao, [y' y']);
putdata(ao, [y1' y1']);
The analog output object is started, and wait up to 9 seconds for the output to complete.
start(ao);
wait(ao,9);
This completes the introduction to analog output objects. Since the analog output object is no longer needed, you should delete it with
the DELETE command to free memory and other physical resources.
delete(ao);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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.
The MathWorks - Demos - Introduction to Digital Input and Output http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 2 19/09/2005 12:36
>> putvalue(dio, 42);
??? Error using ==> digitalio/putvalue
The specified DATA value is too large to be represented by OBJ.
The error occurs because the decimal value 42 is equivalent to the binvec value [ 0 1 0 1 0 1 ]. The binvec value contains six
elements, but there are only four lines contained by the digital I/O object.
You can read the values of the digital I/O lines with the GETVALUE command. GETVALUE always returns a binvec value. You can read
from a line configured with a direction of either 'In' or 'Out'.
>> value = getvalue(dio)
value =
1
0
1
0
You can convert the binvec value to a decimal value with the BINVEC2DEC command.
>> value = binvec2dec(getvalue(dio))
value =
5
Similarly, you can read a subset of lines as follows
>> getvalue(dio.Line([ 1 3 ]))
value =
1
1
This completes the introduction to digital I/O objects. You should delete the digital I/O object, dio, with the DELETE command to free
memory and other physical resources.
>> delete(dio);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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);
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
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:\Temp\tp160074.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'
The MathWorks - Demos - Logging Data to Disk http://www.mathworks.com/products/daq/demos.html?file=/products...
4 de 4 19/09/2005 12:39
To obtain channel information:
daqinfo.ObjInfo.Channel
ans =
1x2 struct array with fields:
ChannelName
HwChannel
Index
InputRange
NativeOffset
NativeScaling
SensorRange
Type
Units
UnitsRange
To obtain event information you can use the SHOWDAQEVENTS command to display the event information.
daqinfo.ObjInfo.EventLog;
showdaqevents(daqinfo.ObjInfo.EventLog)
1 Start ( 17:16:00, 0 )
2 Trigger#1 ( 17:16:00, 0 ) Channel: N/A
3 Trigger#2 ( 17:16:01, 1000 ) Channel: N/A
4 Trigger#3 ( 17:16:01, 2000 ) Channel: N/A
5 Trigger#4 ( 17:16:01, 3000 ) Channel: N/A
6 Trigger#5 ( 17:16:01, 4000 ) Channel: N/A
7 Stop ( 17:16:01, 5000 )
To obtain the hardware information:
daqinfo.HwInfo
ans =
AdaptorName: 'winsound'
Bits: 16
Coupling: {'AC Coupled'}
DeviceName: 'Emu10Kx Audio [B800]'
DifferentialIDs: []
Gains: []
ID: '0'
InputRanges: [-1 1]
MaxSampleRate: 44100
MinSampleRate: 8000
NativeDataType: 'int16'
Polarity: {'Bipolar'}
SampleType: 'SimultaneousSample'
SingleEndedIDs: [1 2]
SubsystemType: 'AnalogInput'
TotalChannels: 2
VendorDriverDescription: 'Windows Multimedia Driver'
VendorDriverVersion: '5.10'
Lastly, clean up the data acquistion object
delete(ai.LogFileName)
delete(ai);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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
The MathWorks - Demos - Generation of Audio Using the Sound Card http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 2 19/09/2005 12:42
When the data has been output, the analog output object is stopped automatically. The analog output object should be deleted with
the DELETE command to free memory and other physical resources.
delete(ao);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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);
The MathWorks - Data Acquisition Toolbox 2.7 - Demos http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 2 19/09/2005 12:43
To retrieve all the data
data = getdata(AI);
Termination
The acquisition ends once all the data is acquired. To end the acquisition session, we can delete the AI
object from the workspace:
delete(AI)
Results
Let's now determine the frequency components of the tuning fork and plot the results. First, we calculate
the absolute value of the FFT of the data.
xfft = abs(fft(data));
Next we convert the absolute value into dB magnitude and extract the real frequency components:
mag = 20*log10(xfft);
mag = mag(1:end/2);
The results show the fundamental frequency to be around 440 Hz and the first overtone to be around 880
Hz. A simple way to find actual fundamental frequency is:
[ymax,maxindex]=max(mag);
The answer is 441 Hz.
Using Different Hardware
This example could also be repeated using different hardware by simply changing two lines of code. For
example, if we were to use a National Instruments multifunction card then we could create the analog input
object using:
AI=analoginput('nidaq',1);
addchannel(AI,0)
Likewise, if we were to use a Measurement Computing board to acquire the data, the code would read:
AI=analoginput('mcc',8);
addchannel(AI,1)
More Examples
To see more Data Acquisition Toolbox example applications, please visit the repository of applications
submitted by users and developers on MATLAB Central.
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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');
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)
%%
The MathWorks - Demos - Measuring a Noise Floor Using Custom Tr... http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 3 19/09/2005 12:44
% First, we get the information needed to evaluate the trigger condition.
extraData = get(ai, 'UserData');
timerPeriod = get(ai,'TimerPeriod');
sampleRate = get(ai,'SampleRate');
%%
% Then, we look at the data received during the last timer period.
sampleData = peekdata(ai, timerPeriod * sampleRate);
maxValue = max(sampleData);
minValue = min(sampleData);
%%
% Next, we analyze the data received and look for our trigger condition.
% If we have not found the first signal, look for it.
if ( ~extraData.signalFound )

if ( maxValue > extraData.signalVoltage || minValue < -extraData.s
ignalVoltage )

% The first signal has been found.
extraData.signalFound = true;
fprintf('First signal found. Waiting for quiet period of %d seconds.
\n', ...
extraData.secondsOfQuietNeeded);

end

% If a signal has been found, we look for the desired period of quiet.
elseif ( ~extraData.quietFound )
if ( minValue > -extraData.quietVoltage && maxValue < extr
aData.quietVoltage )

% Increment the seconds of quiet that we have seen.
extraData.secondsOfQuietFound = extraData.secondsOfQuietFound + time
rPeriod;

if extraData.secondsOfQuietFound >= extraData.secondsOfQuietNeede
d

% When the desired quiet period is found, we execute the trigger
.
trigger(ai);
extraData.quietFound = true;
disp('Quiet period found. Logging started.');

end
% No longer quiet. Reset the seconds of quiet that we have seen.
else
extraData.secondsOfQuietFound = 0;
end

% If the quiet period has been found, look for the second signal.
else
if ( maxValue > extraData.signalVoltage || minValue < -extraData.s
ignalVoltage )

% When the second signal is found, we stop the acquisition.
stop(ai);
disp('Second signal found. Acquisition stopped.');
end
end
%%
% Finally, we save the updated information to the UserData property so
% that it will be available for the next execution of the timer callback
% function.
set(ai, 'UserData', extraData);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
The MathWorks - Data Acquisition Toolbox 2.7 - Demos http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 1 19/09/2005 12:45
Productos y servicios Industrias Educacin Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Close Window
Deployment of a Soundcard Audio Analysis Application
This demo will show how you can use MathWorks products to deploy an application that acquires live streaming data from the PC
soundcard. The data is collected using the Data Acquisition Toolbox. We will generate a standalone executable using the MATLAB
Compiler, and then run the application outside the MATLAB environment. We will then use the MATLAB Builder for COM to
generate a component, which we will integrate with a Microsoft Visual Basic .NET project.
The demo provides an overview of the application and four short videos that show the key steps in the process. The video
segments run automatically, but you can set your own pace using the buttons at the bottom of the video window. You will need a
soundcard and speakers to hear the audio narration.
Contents
Application Overview
Running the Application
Generating a Standalone Executable
Building a Component
Integrating the Component with Microsoft Visual Basic .NET
Additional Information
Application Overview
The application that we will deploy processes and displays audio signals from a PC soundcard. The signals are read using the
Data Acquisition Toolbox, and processed using MATLAB Fourier Transform functions and plotting capabilities. A graphical user
interface (GUI) provides a convenient way to run the application and quickly visualize the results as the audio signal changes.
daqwaterfall Spectrum Analysis using the Data Acquisition Toolbox. Click on image to see enlarged view.
The GUI consists of three plots and several controls, which are used to start and stop the simulation, modify plot types, and
adjust the signal sample rate. The top plot shows the time domain of the audio signal. In the middle is a two-dimensional plot of
the signal's frequency domain. The bottom plot displays a brief time history of the same frequency domain signal. We can modify
the bottom plot type using the visualization drop-down menu.
Running the Application
We will now start our application and whistle into a microphone connected to our soundcard to see if the application works
properly. After viewing the video, close the video viewer window to return to this main demo window.
Watch the video. (1 minutes, 57 seconds)
Generating a Standalone Executable
Now that we know our application works properly, we will generate a standalone executable using the MATLAB Compiler. After
viewing the video, close the video viewer window to return to this main demo window.
Watch the video. (2 minutes, 32 seconds)
Building a Component
To integrate our application with a larger program, we can generate a C or C++ library or a component. In this example, we will
use the MATLAB Builder for COM to generate a COM object. After viewing the video, close the video viewer window to return to
this main demo window.
Watch the video. (3 minutes, 18 seconds)
Integrating the Component with Microsoft Visual Basic .NET
Now that we have our application in the form of a component, we can integrate it with a Microsoft Visual Basic .NET project.
After viewing the video, close the video viewer window to return to this main demo window.
Watch the video. (4 minutes, 27 seconds)
Additional Information
Learn more about MathWorks deployment products.
MATLAB Compiler
MATLAB Builder for COM
MATLAB Builder for Excel
Excel Link
MATLAB Web Server
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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
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]
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'
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]
The MathWorks - Demos - Accessing Analog Input Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
5 de 5 19/09/2005 12:46
'Volts'
2 'Chan2' 2 [-1 1] [-1 1] [-1 1]
'Volts'
This concept can be extended to assign multiple properties different values for multiple channels. The cell array of property values
must be m-by-n, where m is the number of objects and n is the number of properties.
Each row of the property values cell array contains the property values for a single object. Each column of the property values cell
array contains the property values for a single property.
The assigned property values matrix relate to each object and property name as follows:
set(ai.Channel, {'Units'; 'UnitsRange'}, {'LeftUnits', [0 30]; 'Ri
ghtUnits', [0 40]});
ai.Channel
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Left' 1 [-1 1] [-2 2] [0 30]
'LeftUnits'
2 'Chan2' 2 [-1 1] [-1 1] [0 40]
'RightUnits'
You can use the dot notation to assign values to channel properties.
ch1.Units = 'OneUnits';
ch2.SensorRange = [-4 4];
ai.Channel(1).ChannelName = 'Chan1';
ai.Channel
Or, you can assign values to channel properties through named referencing.
ai.Chan2.Units = 'TwoUnits';
ai.Channel
ch1.Units = 'OneUnits';
ch2.SensorRange = [-4 4];
ai.Channel(1).ChannelName = 'Chan1';
ai.Chan2.Units = 'TwoUnits';
ai.Channel
Index: ChannelName: HwChannel: InputRange: SensorRange: UnitsRange:
Units:
1 'Chan1' 1 [-1 1] [-2 2] [0 30]
'OneUnits'
2 'Chan2' 2 [-1 1] [-4 4] [0 40]
'TwoUnits'
You can convert the analog input signals into values that represent specific engineering units by specifying the following Channel
properties:
SensorRange - Expected range of data from sensor.
InputRange - Range of A/D converter.
UnitsRange - Range of data in MATLAB workspace.
Units - Engineering units name.
For example, suppose you are using a microphone which can measure sound levels up to 120 dB and this range produces an output
voltage from -0.5 volts to 0.5 volts. Your A/D converter may have several valid voltage ranges that it can be set to. The best A/D
hardware range is the one that encompasses the expected sensor range most closely.
The channel configuration would be set as follows:
set(ai.Channel, 'SensorRange', [-0.5 0.5]);
set(ai.Channel, 'InputRange', [-1 1]);
set(ai.Channel, 'UnitsRange', [0 120]);
set(ai.Channel, 'Units', 'dB');
Only linear engineering unit conversions are supported. You can perform nonlinear conversions by creating the appropriate M-file
function.
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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');
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.
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');
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);
The MathWorks - Demos - Using Analog Input Triggers http://www.mathworks.com/products/daq/demos.html?file=/products...
5 de 5 19/09/2005 12:47
set(ai, 'TriggerDelayUnits', 'seconds');
set(ai, 'TimeOut', 2);
start(ai)
You can retrieve the 3000 data samples stored in the data acquisition engine with the GETDATA command. If the trigger condition was
not met, GETDATA will timeout after two seconds and no data will be returned.
The data is then plotted against time with the trigger occurring at time = 0.
try
clear data time;
[data,time] = getdata(ai);
catch
time = 0; data = 0;
disp('A timeout occurred.');
end
plot(time,data);
zoom on;
title('Software Trigger');
xlabel('Relative time in seconds.');
ylabel('Data in volts');
A timeout occurred.
Now delete the analog input object.
delete(ai)
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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'
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
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;
The MathWorks - Demos - Counting Complex Events Using Analog I... http://www.mathworks.com/products/daq/demos.html?file=/products...
4 de 4 19/09/2005 12:48
% Define the minimum duration of 50 ms.
minDuration = 0.050;
% Find the pulses that are less than 50 ms.
pulsesToRemove = find(pulseTimes < minDuration);
% Remove the pulses that are too short by setting their value to +5 V.
for ii = 1:length(pulsesToRemove);
startInd = pulseIndices(pulsesToRemove(ii));
endInd = pulseIndices(pulsesToRemove(ii)+1);
processedData(startInd:endInd) = 5;
end
% Plot the smoothed data.
plot(time, processedData)
Count the Pulses
Now that spurious pulses have been removed, it is possible to count the number of pulses in the data signal. The edges of the pulses
are determined in the same manner as before, and you only need to count the number of edges.
% Create the offset data. Need to append a NaN to the final sample since
% both vectors need to have the same length.
offsetData = [processedData(2:end); NaN];
% Find the rising edge.
risingEdge = find( processedData < threshold & offsetData > thresh
old );
numPulses = length(risingEdge)
numPulses =
14
Clean Up
When you are done with a data acquisition object, you should clean up any unneeded data acquisition objects. Delete the analog input
object and clear it from the workspace.
delete(ai);
clear ai ch
Summary
This demo showed how to use the analog input subsystem of a data acquisition device to count complex events. After creating a data
acquisition object and acquiring and viewing the data, it was clear that a simple counting algorithm would not work. A simple filter was
designed to remove the switch bounce and the filter was then applied to the acquired data. It was then possible to count the number
of button presses in the acquired data using a straightforward thresholding technique.
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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'
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
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.
The MathWorks - Demos - Accessing Analog Output Channels http://www.mathworks.com/products/daq/demos.html?file=/products...
4 de 4 19/09/2005 12:49
set(ch, {'UnitsRange'}, {[-20 20];[0 10]});
ch
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Left' 1 [-1 1] [-20 20] 'Volts'
2 'Chan2' 2 [-1 1] [0 10] 'Volts'
This can be extended to assign multiple properties different values for multiple channels. The cell array of property values must be
m-by-n, where m is the number of objects and n is the number of properties. Each row of the property values cell array contains the
property values for a single object. Each column of the property values cell array contains the property values for a single property.
The assigned property values matrix relate to each object and property name as follows:
set(ao.Channel, {'Units'; 'UnitsRange'}, {'LeftUnits', [0 30]; 'Ri
ghtUnits', [0 40]});
ao.Channel
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:

1 'Left' 1 [-1 1] [0 30] 'LeftUnits'

2 'Chan2' 2 [-1 1] [0 40] 'RightUnits'

You can use the dot notation to assign values to channel properties.
ch1.Units = 'OneUnits';
ch2.UnitsRange = [0 50];
ao.Channel(1).ChannelName = 'Chan1';
ao.Channel
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:

1 'Chan1' 1 [-1 1] [0 30] 'OneUnits'

2 'Chan2' 2 [-1 1] [0 50] 'RightUnits'

Or, you can assign values to channel properties through named referencing.
ao.Chan2.Units = 'TwoUnits';
ao.Channel
Index: ChannelName: HwChannel: OutputRange: UnitsRange: Units:
1 'Chan1' 1 [-1 1] [0 30] 'OneUnits'
2 'Chan2' 2 [-1 1] [0 50] 'TwoUnits'
The range of data output to your D/A converter and the valid ranges the D/A converter can be set to are controlled by the following
engineering units properties:
OutputRange - the D/A converter range.
UnitsRange - output data range.
Units - Engineering units name.
The data and D/A hardware ranges should be selected so that the output data is not clipped and you use the largest possible dynamic
range of the output hardware.
For example, suppose you are outputting data that ranges between -2 volts and 2 volts, and the D/A converter has a maximum range
of -1 volt to 1 volt. If the data is not scaled, it will we clipped since the data's range exceeds the hardware's range. By setting the
UnitsRange property to -2 volts to 2 volts, the data will be scaled so that a data value of -2 will map to a value of -1 at the hardware
level and a data value of 2 will map to a value of 1 at the hardware level and clipping will not occur.
The channel configuration would be set as follows:
set(ao.Channel, 'OutputRange', [-1 1]);
set(ao.Channel, 'UnitsRange', [-2 2]);
Only linear engineering unit conversions are supported. You can perform nonlinear conversions by creating the appropriate M-file
function.
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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')
The MathWorks - Demos - Using Analog Output Triggers http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 2 19/09/2005 12:51
ans =
On
ans =
0
Let's execute the manual trigger and the data will be output to the sound card, and then wait up to 2 seconds for the output to
complete.
trigger(ao);
wait(ao,2);
Finally, delete the analog output object.
delete(ao)
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
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 Educacin 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'
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 =
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'
The MathWorks - Demos - Accessing Digital Lines http://www.mathworks.com/products/daq/demos.html?file=/products...
4 de 4 19/09/2005 12:52
2 'Line2' 1 0 'Out'
You can assign different property values to multiple lines by specifying a cell array of property values in the SET command.
>> set(daqline, {'Direction'}, {'Out'; 'In'})
>> daqline
Index: LineName: HwLine: Port: Direction:
1 'Line1' 0 0 'Out'
2 'Line2' 1 0 'In'
This can be extended to assign multiple properties different values for multiple lines. The cell array of property values must be
m-by-n, where m is the number of objects and n is the number of properties. Each row of the property values cell array contains the
property values for a single object. Each column of the property values cell array contains the property values for a single property.
>> set(dio.Line, {'Direction'; 'LineName'}
{'In', 'DIOLine1'; 'Out', 'DIOLine2'});
>> dio.Line
Index: LineName: HwLine: Port: Direction:
1 'DIOLine1' 0 0 'In'
2 'DIOLine2' 1 0 'Out'
The assigned property values matrix relate to each object and property name as follows
Direction LineName
line1 'In' 'DIOLine1'
line2 'Out' 'DIOLine2'
You can use the dot notation to assign values to line properties.
>> line1.Direction = 'Out';
>> line2.LineName = 'MyLine2';
>> dio.Line(1).LineName = 'MyLine1';
>> dio.Line
Index: LineName: HwLine: Port: Direction:
1 'MyLine1' 0 0 'Out'
2 'MyLine2' 1 0 'Out'
Or, you can assign values to line properties through named referencing.
>> dio.MyLine2.LineName = 'Digital';
>> dio.Line
Index: LineName: HwLine: Port: Direction:
1 'MyLine1' 0 0 'Out'
2 'Digital' 1 0 'Out'
This completes the introduction to digital I/O lines. You should delete the digital I/O object, dio, with the DELETE command to free
memory and other physical resources.
>> delete(dio);
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad
The MathWorks - Demos - Managing Large Data Sets by Logging to Disk http://www.mathworks.com/products/daq/demos.html?file=/products...
1 de 3 19/09/2005 12:53
Productos y servicios Industrias Educacin Soporte Comunidad de usuarios La empresa
Data Acquisition Toolbox 2.7
Managing Large Data Sets by Logging to Disk
In this demo we will show logging of a data acquisition session to disk. There are a number of reasons to do this: acquiring large data
sets that would not normally fit into memory, or acquiring data samples that we plan on examining at a later time.
Contents
Creating and Configuring an Analog Input Object
Configuring the Analog Input Object to Log to Disk
Extracting Logged Data
Working with Subsets of Logged Data
Creating and Configuring an Analog Input Object
Before acquiring any data, you must create an analog input object and specify the channels from which to acquire data. You may need
to modify the following code to match your acquisition hardware.
ai = analoginput('winsound');
addchannel(ai, 1);
Configure the analog input object for acquisition. The configuration we will use is:
1000 samples per trigger
repeat the trigger 20 times, for a total of 21 triggers
A sample rate of 44100 samples per second
set(ai, 'SamplesPerTrigger', 1000);
set(ai, 'TriggerRepeat', 20);
set(ai, 'SampleRate', 44100);
Configuring the Analog Input Object to Log to Disk
Now configure the acquisition to log to disk.
set(ai, 'LoggingMode', 'Disk');
When logging to disk, you can specify what file to write to. To alter the name of the log file, set the LogFileName property.
set(ai, 'LogFileName', 'LogFile.daq');
You can now begin your acquisition.
%Start the acquisition and wait for it to finish
start(ai);
wait(ai, 2);
Extracting Logged Data
When our data acquisition is complete, extract the data samples you have collected.
data = daqread('LogFile.daq');
plot(data);
You can also obtain a time vector that represents the time stamp of each data sample relative to the first trigger.
[data, time] = daqread('LogFile.daq');
The MathWorks - Demos - Managing Large Data Sets by Logging to Disk http://www.mathworks.com/products/daq/demos.html?file=/products...
2 de 3 19/09/2005 12:53
In addition, you can obtain the hardware settings that were used during acquisition. This returns a structure composed of two fields
containing all the hardware information at the time of acquisition. To obtain this, simply pass in the logged data file name with the
info parameter to daqread.
info = daqread('LogFile.daq', 'info')
info =
ObjInfo: [1x1 struct]
HwInfo: [1x1 struct]
Working with Subsets of Logged Data
So far you have seen only how to look at all the data collected. By using different parameter-value pairs, you can look at the data
through a number of different constraints. This is useful when you are interested in only a portion of the data collected while working
with large data files. For example, you can request only those samples that fall within a certain sample range. To do this, pass in the
samples keyword along with the range of samples you want to daqread.
data = daqread('LogFile.daq', 'samples', [100 1200]);
plot(data)
You can request the data that occurred only in a specific time frame. To do this you use daqread with the time keyword paired with a
time vector (in seconds).
[data, time] = daqread('LogFile.daq', 'time', [.1 .25]);
plot(time, data);
You can request the data that occurred only within a range of triggers. To do this, use daqread with the triggers keyword paired with
either a trigger range or a single trigger.
data= daqread('LogFile.daq', 'triggers', [6 8]);
plot(data);
The MathWorks - Demos - Managing Large Data Sets by Logging to Disk http://www.mathworks.com/products/daq/demos.html?file=/products...
3 de 3 19/09/2005 12:53
With these capabilities, daqread can be used to log data and acquisition information, as well as work with large data sets by extracting
and operation on a subset of logged data at a time.
1994-2005 The MathWorks, Inc. - Ayuda Del Sitio - Patentes - Marcas comerciales - Politica de privacidad

You might also like