フィルターのクリア

Using Try/For loop to allocate correct serial port number

3 ビュー (過去 30 日間)
Joseph
Joseph 2023 年 3 月 22 日
コメント済み: Joseph 2023 年 3 月 22 日
I am trying to create a code that will read the correct serial port for my device no matter what number the COM port is on the device I am connected. This code will be ran on multiple laptops/PCs and eventually created in to a GUI so I want to make sure I won't have to come back and edit this part of teh code again. From looking at google, on a PC there won't be more than 100 USB Serial COM ports hence I would like the code to try from COM1 to COM100. The reason I have used the try and catch functions in a for loop is beacsue the code will fail if it doesn't get the correct port.
This is the code that I have at the minute:
%%
clear all
close all
clc
%% conecting to serialport
ports1_9 = ['COM1','COM2','COM3','COM4','COM5','COM6','COM7','COM8','COM9']
ports10_20 = ['COM10','COM11','COM12','COM13','COM14','COM15','COM16','COM17','COM18','COM19','COM20']
Ports1_9 = regexp(ports1_9,'\COM[123456789]','match')
Ports10_20 = regexp(ports10_20,'\COM1[123456789]','match')
%%
for a = 1:9
try
ND280 = serialport(Ports1_9{a},9600,'Parity','None','DataBits',8,'StopBits',1,'FlowControl','software');
catch
warning('Locating correct Port')
try
ND280 = serialport(Ports10_20{a},9600,'Parity','None','DataBits',8,'StopBits',1,'FlowControl','software');
catch
warning('Locating correct Port')
end
end
end
This code does work however I am sure it isn't the most efficient method and as I want to get all the way up to COM100 and maybe more I need the help!

採用された回答

Fangjun Jiang
Fangjun Jiang 2023 年 3 月 22 日
See help document for "break" and "continue"
for k=1:100
port=sprintf('COM%d',k);
try
ND280 = serialport(port,...);
break; % successful, break the loop
catch
% not successful, continue searching for port
disp('Continue searching for port')
continue;
end
end % for-loop
  2 件のコメント
Fangjun Jiang
Fangjun Jiang 2023 年 3 月 22 日
"continue" is actually not required here
Joseph
Joseph 2023 年 3 月 22 日
Thank you so much, that worked a dream.

サインインしてコメントする。

その他の回答 (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