Reconnecting to a Bluetooth device within a class
3 views (last 30 days)
Show older comments
I have built a class to communicate with a Bluetooth device, setting one of the class properties as the Bluetooth object 's'. Within a class function that updates the device, I need to reset the device, which breaks the link with MATLAB. I've created a basic disconnect command that has worked thus far from outside the class.
function disconnect(obj)
obj.s.delete;
obj.s=[];
end
When I do this from inside the class function and then reconnect...
BTaddr=obj.s.Address;
BTchan=obj.s.Channel;
obj.s.delete;
obj.s=[];
obj.s=bluetooth(BTaddr,BTchan);
...the function continues to run as expected, but then the 'myDev.s' object is a "handle to deleted bluetooth" variable. I am then able to disconnect and reconnect outside of the class, but it seems unnecessarily messy. Is there something that I could do better to make this work as expected?
0 Comments
Answers (1)
Broy
on 19 Jan 2026
Edited: Broy
on 19 Jan 2026
The behavior you are describing, where the object properties revert to their previous state after the method finishes, suggests that your class is currently defined as a Value Class.
In MATLAB, modifications made to a Value Class inside a method are local to that method unless the modified object is returned. To ensure that the disconnection and reconnection persist outside the function, you need to define your class as a Handle Class.
You can do this by inheriting from the handle class in your classdef line:
classdef YourClassName < handle
% Your properties and methods
end
Helpful Documentation for Comparison of Handle and Value Classes:
Hope it helps.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!