필터 지우기
필터 지우기

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 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