Using Try/For loop to allocate correct serial port number

7 Ansichten (letzte 30 Tage)
Joseph
Joseph am 22 Mär. 2023
Kommentiert: Joseph am 22 Mär. 2023
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!

Akzeptierte Antwort

Fangjun Jiang
Fangjun Jiang am 22 Mär. 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
  2 Kommentare
Fangjun Jiang
Fangjun Jiang am 22 Mär. 2023
"continue" is actually not required here
Joseph
Joseph am 22 Mär. 2023
Thank you so much, that worked a dream.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by