MATLAB Answers

How to check if a serial port is valid?

48 views (last 30 days)
Martin Velasquez
Martin Velasquez on 18 Apr 2019
Edited: Kyle Wilkin on 13 Mar 2020
Hello
I am trying to create a dialogue box that lets the user input a comport that is connected to an Aruino, if that comport is not valid however, then it will allow you to input another comport. The problem is that no matter what comport I enter, 'COM5', 'COM6', etc.. it will output the msgbox below, indicating that it is in fact the correct port, which is certainly not the case.
So my question is basically how can I detec which Comport the arduino is specifically connected to, save it in a variable, pass it to the Serial() function, and check whether it's valid or not.
I've used seriallist and it is a read only output, to my knowledge.
prompt = {'Enter COM port number, if Windows user use COM6 for example, if using MAC use /dev/tty.'};
dlgtitle = 'COM Port';
definput = {'30'};
answer = inputdlg(prompt,dlgtitle,[1 40],definput);
com= string(answer(1));
if isvalid(serial(sprintf('%s',com)))
ser=sprintf('%s',com);
while( ~isvalid(serial(ser)))
answer=inputdlg('Not a vlaid COMPORT, please try again',dlgtitle,[1 40], definput);
ser= string(answer(1));
end
end
msgbox('Thank you for the correct COMPORT')

  0 Comments

Sign in to comment.

Answers (1)

Rohan Kale
Rohan Kale on 14 Feb 2020
In my understanding you aim on retrieving the serial com port on which an Arduino board is connected. There could be two solutions here.
1. The seriallist function you mentioned indeed can be used for detection, but I would recommend using the serialportlist API :
You may pass the string array outputs of the serialportlist in a loop to the arduino object creation command under the assumption that arduino board name is known.
a = arduino(com, board);
% For example,
a = arduino(com, 'UNO');
% where com is the one of the output strings of serialportlist
You may want to put them under try and catch statements. A successful object creation would suggest a valid port.
2. In case the Arduino boardname and com ports are unknown , try creating arduino object and get the com port and board names with
a = arduino();
a.Port
a.Board

  1 Comment

Kyle Wilkin
Kyle Wilkin on 13 Mar 2020
Is there anything similar to serialportlist for before 2019b? I am using 2019a on an offline computer so an upgrade is not easy.

Sign in to comment.

Sign in to answer this question.

Products


Release

R2018b