Opening of serial port during GUI formation.

조회 수: 5 (최근 30일)
Paramjit Yadav
Paramjit Yadav 2024년 6월 3일
댓글: Matlab Pro 2024년 6월 6일
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

채택된 답변

Matlab Pro
Matlab Pro 2024년 6월 3일
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
Paramjit Yadav
Paramjit Yadav 2024년 6월 3일
@Noah Respected Sir,
Thank you so much for the answer. It is working.
Kind regards
Matlab Pro
Matlab Pro 2024년 6월 6일
.. always happy to help

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Serial and USB Communication에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by