Main Content

Acquire Data in the 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 allow your code to access data as the hardware acquires it or to react to any errors as they occur. In this example, you acquire data from a microphone with ID Audio1 using the ScansAvailableFcnCount property to trigger the function call defined by the ScansAvailableFcn property. Using a callback allows a plot to be updated in real time while acquisition continues.

Get a list of devices so you can identify the microphone you want to use. The partial listing here indicates the device ID.

daqlist
      VendorID       DeviceID                              Description
    _____________    ________    ________________________________________________________________

    "directsound"    "Audio1"    "DirectSound Headset Microphone (Plantronics BT600)"            

Create a directsound DataAcquisition object with a microphone input channel on Audio1. You might have to use a different device.

d = daq("directsound");
ch = addinput(d,"Audio1",1,"audio");

Create a simple callback function to plot the acquired data and save it as plotMyData.m in your current working folder. Enter the following code in the file.

function plotMyData(obj,evt)
% obj is the DataAcquisition object passed in. evt is not used.
     data = read(obj,obj.ScansAvailableFcnCount,"OutputFormat","Matrix");
     plot(data)
 end

Set the callback function property of the DataAcquisition object to use your function.

d.ScansAvailableFcn = @plotMyData;

Start the acquisition to run for 5 seconds in the background.

start(d,"Duration",seconds(5))

Speak into the microphone and watch the plot. It updates 10 times per second.

See Also

Functions

Related Topics