Main Content

Log Characteristic Value from Bluetooth Low Energy Peripheral Device Using a MATLAB Class

This example shows how to implement a MATLAB® class and object to collect on demand the value of a characteristic of your Bluetooth® Low Energy (BLE) device for a desired duration.

To access the MATLAB® class file for this example, click the Open Live Script button and download the attached file.

Required Hardware

Any BLE device with characteristics that supports attributes such as Read and either Notify or Indicate. For more details see, Attributes.

For this example uses Arduino® Nano 33 BLE hardware.

Discover and Connect to BLE Device

First, check that the BLE device supports connections by finding it in MATLAB®. The blelist function scans nearby Bluetooth Low Energy peripheral devices that are advertising indications.

blelist
Run bluetoothlist to search for nearby Bluetooth classic devices.
ans=26×5 table
    Index         Name            Address        RSSI    Advertisement
    _____    ______________    ______________    ____    _____________

      1      ""                "2F9C86A6E132"    -19      1×1 struct  
      2      "Mambo_560253"    "E014F6303DFD"    -36      1×1 struct  
      3      ""                "1FA6CF2C2A06"    -36      1×1 struct  
      4      ""                "34312F6C837B"    -39      1×1 struct  
      5      ""                "1A14CB869510"    -50      1×1 struct  
      6      ""                "3AAFEC3833AE"    -54      1×1 struct  
      7      ""                "18116441AF7D"    -54      1×1 struct  
      8      "WaveGen"         "42162F5C6B30"    -57      1×1 struct  
      9      ""                "3C43509C1069"    -60      1×1 struct  
     10      ""                "2B416C7DA051"    -63      1×1 struct  
     11      ""                "2DA656DCF568"    -63      1×1 struct  
     12      ""                "076ACA437939"    -65      1×1 struct  
     13      ""                "38ABD95443B2"    -67      1×1 struct  
     14      ""                "1DAF492B7D39"    -68      1×1 struct  
     15      ""                "063BFA8A1AD9"    -71      1×1 struct  
     16      "Mambo_621221"    "D03A6110E621"    -73      1×1 struct  
      ⋮

Once you find the device is found in MATLAB, connect to it by calling ble. Specify the name of the device if it has a unique name, or specify the device address. This example uses the device address.

bleObj = ble("42162F5C6B30");

Retrieve Characteristic Value

Retrieve all the available characteristics of the BLE device.

allCharacteristics = bleObj.Characteristics;

This example uses a bleDataCollector class to collect and manage data from the BLE device. To access the bleDataCollector MATLAB® class file for this example, click the Open Live Script button and download the attached file.

Use the bleDataCollector object to connect to a specific characteristic, and set up a data collection callback function. Use the @ operator to assign the function handle to the DataAvailableFcn property of the characteristic object. Use an anonymous function to pass arguments to your callback in addition to the source and event data arguments passed by MATLAB. Anonymous functions can use any variables that are available in the current workspace. For more details, see Additional Arguments for Callback Function. Initialize the callback function to collect the characteristic value sent by the BLE device.

function obj = bleDataCollector(bleObj,serviceInput,characteristicInput)
            % Connect to the characteristic of a BLE device to collect the
            % data sent by the device.
            %
            % bleObj              - ble connection object
            % serviceInput        - Service name or UUID
            % characteristicInput - Characteristic name or UUID
            %
            % Example:
            % obj = bleDataCollector(bleObj,"180D","2A37")
            arguments
                bleObj              ble   {mustBeScalarOrEmpty}
                serviceInput        (1,1) {mustBeTextScalar}
                characteristicInput (1,1) {mustBeTextScalar}
            end
            % Create BLE characteristic object
            obj.CharObj = characteristic(bleObj,serviceInput,characteristicInput);
            % Initialize the callback function to collect the
            % characteristic value sent by the BLE device
            obj.CharObj.DataAvailableFcn = (@(src,event)collectCharacteristicValue(obj,src,event));
            % Disable characteristic value collection. Enable it on demand
            unsubscribe(obj.CharObj);
end

function data = collectDataForDuration(obj,duration)
            % Collect the ble characteristic value for a given duration.
            %
            % obj      - Object of bleDataCollector class
            % duration - Duration for which data needs to be collected
            %
            % Examples:
            % Collect the characteristic values for 5 seconds
            % collectDataForDuration(bleDataObj,5)
            arguments
                obj      (1,1) bleDataCollector
                duration (1,1) {mustBePositive}
            end
            % Initialize the data to be collected
            data = [];
            % Subscribe to the characteristic value notification or
            % indication. This will enable the callback function to be
            % triggered whenever BLE device has new characteristic value
            subscribe(obj.CharObj);
            % Pause till the required data is collected
            pause(duration);
            % Disable characteristic value collection after the required
            % duration
            unsubscribe(obj.CharObj);
            % Return the collected data. This data is the raw
            % characteristic value collected from the BLE device. Implement
            % additional decoding logic for specific end application
            % requirements.
            data = obj.CollectedData;
end

Select the characteristic that supports attributes such as Read and either Notify or Indicate. using the ServiceUUID and CharacteristicUUID input arguments. This selection enables you to read the characteristic value upon being notified by the BLE device.

% To read a characteristic value on being notified, Choose a
% characteristic with "Attributes" - "Read" and ("Notify" or "Indicate")
connectionObj = bleDataCollector(bleObj,allCharacteristics.ServiceUUID(4),allCharacteristics.CharacteristicUUID(4));

Use the collectDataForDuration method to collect the characteristic value for a specified duration and then return the collected data.

% Log the characteristic value for 10 seconds
% NOTE: The data collected here is the raw characteristic value collected
% from the BLE device. Implement additional decoding logic for specific end
% application requirements.
collectedData = collectDataForDuration(connectionObj,10);

Plot Characteristic Value

Use plot to plot the collected characteristic value.

% Plot the data collected
plot(collectedData);

Figure contains an axes object. The axes object contains an object of type line.

Clean Up

After you finish working with the characteristic, clear the bleDataCollector object and the BLE device connection.

% Clear the bleDataCollector object and BLE device connection
clear connectionObj bleObj;