Detect Bluetooth BLE device disconnection event - Add listener to 'Connected' property

11 vues (au cours des 30 derniers jours)
Hello,
I am working on an app designer based application where I would like to be able to detect a BLE device disconnection event, so the user interface reacts consequently (e.g. displaying a "Device disconnected" message on a text label).
My initial idea was to add a listener to the BLE object 'Connected' property, but I have tried this and does not work.
I have explored the 'Connected' property and it cannot be observed.
findprop(ble('HC-08'),'Connected') %you need to have some BLE device active to be able to execute successfully this line
I could poll periodically the state of this property, but the main state machine function on my application is designed to be executed only when an specific event happens. The only way I see to solve the problem is to add a timer that periodically checks this property value and reacts in consequence.
Is there any other way to listen to this property instead of polling it continuously?
Thank you,
Regards
David L.

Réponses (1)

Sudarsanan A K
Sudarsanan A K le 29 Avr 2024
Hi David,
To ensure efficient Bluetooth Low Energy (BLE) connection monitoring within your application, you can adopt different strategies based on the communication pattern with the BLE device:
  • Continuous Data Transfer: If you are doing continuous data transfer within a while loop, you can check the status using the "Connected" property of the BLE object. This approach allows for immediate detection of disconnection events during active communication phases.
  • Background Data Transfer: However, if you are doing more background data transfer, the best way forward is to use a timer and frequently check the connection status. This method is particularly useful for applications that operate in the background or have intermittent periods of activity.
For implementing the timer-based approach, you can use the following MATLAB code:
function startBLECheckTimer(bleDevice)
% Timer to check BLE connection status every 5 seconds
t = timer('ExecutionMode', 'fixedRate', 'Period', 5, ...
'TimerFcn', @(~,~) checkBLEConnection(bleDevice));
start(t); % Start the timer
end
function checkBLEConnection(bleDevice)
if ~bleDevice.Connected
disp('Device disconnected');
else
disp('Device is connected');
end
end
This code snippet sets up a timer that periodically checks the "Connected" property of the BLE object every 5 seconds, making it an effective solution for background data transfer scenarios. By integrating these strategies and code into your application, you can maintain robust BLE connection monitoring tailored to both active and less active communication phases.
I hope this helps!

Produits


Version

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by