Acquire Data in Background with Live Plot Updates
This example shows how to acquire data in the background using callbacks while MATLAB® continues to run.
A background acquisition uses callbacks to access data as the hardware collects it or
to handle errors as they occur. In this example, you acquire data from a microphone with
ID Audio1, and you define a callback for the
ScansAvailableFcn property to update a plot in real time while
acquisition continues.
A background acquisition uses callbacks to allow your code to access data as the
hardware acquires it or to react to any errors as they occur. In this example, you
acquire data from a microphone with ID Audio1 using the
ScansAvailableFcnCount property to trigger the function call
defined by the ScansAvailableFcn property. Using a callback allows
a plot to be updated in real time while acquisition continues.
Device Discovery and Setup
Get a list of devices so you can identify the microphone you want to use. The partial listing here indicates the device ID.
daqlist
VendorID DeviceID Description
_____________ ________ ____________________________________________________
"directsound" "Audio1" "DirectSound Headset Microphone (Plantronics BT600)"Create a directsound
DataAcquisition
object with a microphone input channel on Audio1.
d = daq("directsound"); ch = addinput(d,"Audio1",1,"audio");
Background Acquisition and Live Plot Setup
Configure a callback function using the ScansAvailableFcn property to update a live plot with the data from background acquisition. This callback is triggered when the number of scans accumulated exceeds the default value of ScansAvailableFcnCount property.
d.ScansAvailableFcn = @plotMyData;
Start the acquisition to run for 5 seconds in the background.
start(d,"Duration",seconds(5))Create a live-updating line plot by storing its handle in the
UserData property of the data acquisition object. This allows
the callback function to access and update the line plot dynamically during the
background acquisition process.
figure; xlabel("Time (s)"); ylabel("Amplitude"); d.UserData = animatedline;
Callback Function
This callback function updates the live plot with the data acquired in the background.
function plotMyData(src,evt) % src is the DataAcquisition object passed in. and evt is not used. [data, timestamps, ~] = read(src, src.ScansAvailableFcnCount, 'OutputFormat', 'Matrix'); addpoints(src.UserData, timestamps , data); end
During the background acquisition, speak into the microphone and see the plot update in real time.
