Change active serial port
조회 수: 7 (최근 30일)
이전 댓글 표시
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
Dennis
2020년 7월 14일
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')
답변 (1개)
Naga
2024년 10월 17일
편집: Naga
2024년 10월 17일
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.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!