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.
The Bluetooth properties and functions associated with callbacks follow.
|Property or Function||Purpose|
|Number of bytes available to read|
|Bytes available callback function|
|Number of bytes of data to trigger callback|
|Bytes available callback trigger mode|
|Set callback function and trigger condition for communication with Bluetooth device|
|Callback function triggered by error event|
|General purpose property for user data|
This example uses a HC-06 Bluetooth transceiver module configured as a loopback device.
Create the callback function. Define a callback function
collectDatathat reads received data and stores it in the
UserDataproperty of the
function collectData(src,evt) src.UserData = [src.UserData; read(src,src.BytesAvailableFcnCount)]; end
hc06for 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
Configure callback properties to read and collect data each time five bytes are sent by the device and received in MATLAB.
bluetoothdevice object when you are done working with it.