Main Content

Use Callbacks for Bluetooth Communication

You can enhance the power and flexibility of your Bluetooth® device by using events and callbacks. An event occurs after a condition is met and can result in one or more callbacks.

While MATLAB® is connected to a Bluetooth device, you can use events to display a message, display data, analyze data, and so on. You can control callbacks through callback properties and callback functions. All event types have an associated callback property. Callback functions are MATLAB functions that you write to suit your specific application needs. Execute a callback when a particular event occurs by specifying the name of the callback function as the value for the associated callback property.

Callback Properties

The Bluetooth properties and functions associated with callbacks follow.

Property or FunctionPurpose
NumBytesAvailableNumber of bytes available to read
BytesAvailableFcnBytes available callback function
BytesAvailableFcnCountNumber of bytes of data to trigger callback
BytesAvailableFcnModeBytes available callback trigger mode
configureCallbackSet callback function and trigger condition for communication with Bluetooth device
ErrorOccurredFcnCallback function triggered by error event
UserDataGeneral purpose property for user data

Using Callbacks

This example uses a HC-06 Bluetooth transceiver module configured as a loopback device.

  1. Create the callback function. Define a callback function collectData that reads received data and stores it in the UserData property of the bluetooth object.

    function collectData(src,evt)
        src.UserData = [src.UserData; read(src,src.BytesAvailableFcnCount)];
    end
    
  2. Create a bluetooth object hc06 for the HC-06 module.

    hc06 = bluetooth("HC-06",1)
    hc06 = 
      bluetooth with properties:
    
                     Name: "HC-06"
                  Address: "98D331FB3B77"
                  Channel: 1
        NumBytesAvailable: 0
          NumBytesWritten: 0
    
      Show all properties
    
    
  3. Configure callback properties to read and collect data each time five bytes are sent by the device and received in MATLAB.

    configureCallback(hc06,"byte",5,@collectData);
  4. Clear the bluetooth device object when you are done working with it.

    clear hc06

See Also

| |

Related Topics