Communicate with multiple serial port in same time
Mostrar comentarios más antiguos
Now I am trying to communicate with two serial ports in same time
I use spmd statement from parallel computing tool to achieve that.
Here is my code.
Send.m
%% Initialize
clear all
clc
delete(instrfind);
%% Create a Serial Port
slave1 = instrfind('Type', 'serial', 'Port', 'COM4', 'Tag', '');
slave2 = instrfind('Type', 'serial', 'Port', 'COM7', 'Tag', '');
global return_data;
return_data = "";
% Create the serial port object if it does not exist
% otherwise use the object that was found.
if isempty(slave1)
slave1= serial('COM4');
else
fclose(slave1);
slave1 = slave1(1);
end
if isempty(slave2)
slave2= serial('COM7');
else
fclose(slave2);
slave2 = slave2(1);
end
%Configuration
set(slave1,'BaudRate',9600);
set(slave2,'BaudRate',9600);
%% Serial Callback Function
slave1.BytesAvailableFcn = @(slave1,event) SerialCallback(slave1,event);
slave2.BytesAvailableFcn = @(slave2,event) SerialCallback(slave2,event);
%% Open Serial Port
fopen(slave1);
fopen(slave2);
%% Main Work
send_data = 1;
spmd
while(true)
fwrite(slave1,num2str(send_data));
fwrite(slave2,num2str(send_data));
send_data = ~send_data;
pause(1);
end
end
%% Close Serialport
fclose(serial(slave1.Port));
delete(slave1);
clear slave1
fclose(serial(slave2.Port));
delete(slave2);
clear slave2
and callback function SerialCallback.m, which displays the return value
function SerialCallback(src,~)
global return_data;
% Read data from Arduino
return_data = (fgetl(src));
%Trim the string
return_data = strtrim(return_data);
disp(return_data);
end
However , there is error message:
Error using Send.m
Error detected on workers 1 3.
Caused by:
Error using serial/fwrite (line 199)
Unsuccessful write: OBJ must be connected to the hardware with FOPEN.
-----------------------------------------------------------------------------------------------------------
If I remove the spmd statement, the code runs well.
Does someone know a solution?
Respuestas (1)
Walter Roberson
el 27 de Nov. de 2018
0 votos
you must create the serial object and configure its properties and fopen it in the lab that is going to use it . Each lab is aa different process and different processes do not share hardware resources .
I recommend that you rethink your code. You are creating multiple labs, number unspecified but probably the same as the number off physical cores. Then you try to have all of those labs write to one of the serial ports and then the other serial port. That could easily be 4 copies of the same message to each port. And you don't even transfer st the same time .
Categorías
Más información sobre Programming en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!