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 Center および File ExchangeSerial and USB Communication についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by