Change active serial port
4 次查看(过去 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!