Opening of serial port during GUI formation.

5 visualizzazioni (ultimi 30 giorni)
Hello everyone,
I am trying to create a GUI which uses serial port for communication. Here, I the GUI runs but I have to everytime open or pass the command to open the serial port when ever I have to communicate.
Is their a possible way by which I can open port just once inside the classdef method instead of writting it again and again in method (static) and opening it again and again. It consumes time and the GUI becomes slow.
I will kindly request, to please help to suggest ways by which I can open serial port only once and then communicate with it as many times as possible.
I have also attached a sample code specifying my current problem.
Thanking you,
Kind regards
classdef classEl < handle
properties
fig
daq
UI
position_limits
position_read_1
end
properties (SetObservable, AbortSet) % for listeners
position
pre_value
end
methods
function obj = classEl() % constructor
obj.position_limits = [0, 360];
addlistener(obj,'position','PostSet',@classEl.handlePropEvents);
obj.position = [0 0 0 0]; % initial
obj.pre_value =[0 0 0 0];
obj.fig = uifigure( 'Name',class(obj),'Position', [100 100 979 446]);
...
...
end
end
methods (Static)
function handlePropEvents(src,evnt)
obj = evnt.AffectedObject;
switch src.Name
case {'position','pre_value'}
if(obj.pre_value(1) ~= obj.position(1))
serial_port =serialport("COM4",9600);
...
elseif(obj.pre_value(2) ~= obj.position(2))
serial_port =serialport("COM4",9600);
...
end
end
end
end
end

Risposta accettata

Matlab Pro
Matlab Pro il 3 Giu 2024
Hi
I have enhanced your class:
Added serial_port to the properties:
properties
fig
daq
UI
position_limits
position_read_1
serial_port
end
When initiaiting connection - calling this property:
obj.serial_port = serialport("COM4",9600);
.. and adding a desturctore method to delete the connection when class is deleted:
function delete(obj) % Destructor
if ~isempty(obj.serial_port) && ishandle(obj.serial_port)
delete(obj.serial_port)
end
end
Thus - when class is instantiated - it holds the "obj.serial_port" for usege (like write(obj.serial_port,data,'uint8')
  2 Commenti
Paramjit Yadav
Paramjit Yadav il 3 Giu 2024
@Noah Respected Sir,
Thank you so much for the answer. It is working.
Kind regards

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by