Change active serial port

7 Ansichten (letzte 30 Tage)
Khaled Mahmoud
Khaled Mahmoud am 14 Jul. 2020
Bearbeitet: Naga am 17 Okt. 2024
Hello,
I have two devices "COM3, COM4" in the list of serial ports in MATLAB, and want to switch between the active device without disconnecting one of them.
Is there any option to select the active serial port in my workspace?
  2 Kommentare
Dennis
Dennis am 14 Jul. 2020
I don't know what you mean by active serial port.
You can address each device seperately without disconnecting them by using the port.
fprintf('COM3','mymessage')
fscanf('COM3')
fprintf('COM4','myothermessage')
fscanf('COM4')
Khaled Mahmoud
Khaled Mahmoud am 14 Jul. 2020
I mean by active serial port is that to use the device on COM3 without the need to disconnect COM4 (COM3 is active)

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Naga
Naga am 17 Okt. 2024
Bearbeitet: Naga am 17 Okt. 2024
Hello Khaled,
In MATLAB, manage multiple serial connections by creating separate serial port objects for each device. Switch between them by specifying the desired object for communication. Refer to the example below:
% Create serial port objects for COM3 and COM4
s1 = serialport("COM3", 9600);
s2 = serialport("COM4", 9600);
% Function to perform operations on the active serial port
function data = operateSerial(activeSerial, writeData, numBytes)
write(activeSerial, writeData, "char");
disp(['Data written to ', activeSerial.Port]);
data = read(activeSerial, numBytes, "char");
disp(['Data read from ', activeSerial.Port, ': ', data]);
end
% Initially set the active device to COM3 and perform operations
activeSerial = s1;
disp(['Active serial port set to: ', activeSerial.Port]);
data = operateSerial(activeSerial, "Command for COM3", 10);
% Switch to COM4 and perform operations
activeSerial = s2;
disp(['Active serial port switched to: ', activeSerial.Port]);
data = operateSerial(activeSerial, "Command for COM4", 10);
% Cleanup: Clear the serial port objects
clear s1 s2;
To learn more about the 'serialport' function, refer to the documentation below:
Also, please note that if the boards are identical, it is recommended to disconnect one board before connecting another. Since the boards are identical, the build can occur on either of the boards, irrespective of the COM port we are mentioning.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by