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 Function | Purpose |
---|---|
NumBytesAvailable | Number of bytes available to read |
BytesAvailableFcn | Bytes available callback function |
BytesAvailableFcnCount | Number of bytes of data to trigger callback |
BytesAvailableFcnMode | Bytes available callback trigger mode |
configureCallback | Set callback function and trigger condition for communication with Bluetooth device |
ErrorOccurredFcn | Callback function triggered by error event |
UserData | General purpose property for user data |
Using Callbacks
This example uses a HC-06 Bluetooth transceiver module configured as a loopback device.
Create the callback function. Define a callback function
collectData
that reads received data and stores it in theUserData
property of thebluetooth
object.function collectData(src,evt) src.UserData = [src.UserData; read(src,src.BytesAvailableFcnCount)]; end
Create a
bluetooth
objecthc06
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
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);
Clear the
bluetooth
device object when you are done working with it.clear hc06
See Also
bluetooth
| configureCallback
| read