Reconnecting to a Bluetooth device within a class

11 views (last 30 days)
Brian
Brian on 8 Jan 2026
Edited: Broy on 19 Jan 2026 at 4:53
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?

Answers (1)

Broy
Broy on 19 Jan 2026 at 3:44
Edited: Broy on 19 Jan 2026 at 4:53
Hi @Brian,
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.

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!