Using Try/For loop to allocate correct serial port number

3 views (last 30 days)
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!

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 22 Mar 2023
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

More Answers (0)

Community Treasure Hunt

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

Start Hunting!