How do I read from two serial ports in parallel on the same machine?

I would like to read in data from two serial ports on my machine in parallel. Currently, executing FREAD or FSCANF will read the data into MATLAB one after the other. I also do not want one read to wait for data and block the other read command from the input buffer. Is there a way I can read from the ports in parallel?

 Réponse acceptée

Yes, you can use the Parallel Computing Toolbox's SPMD feature to do this. You can have each worker MATLAB thread accessing individual COM ports as seen in the following example.
In this example, the two COM ports are COM1 and COM6. Depending on the return value of the 'labindex' function, each worker will access their respective assigned COM port to read and write from it. Note that this assumes you have two loopback serial connectors connected to your machine.
matlabpool(2)
spmd(2)
if labindex == 1
portID = 1;
else
portID = 6;
end
disp(labindex);
s = serial(['COM' num2str(portID)]);
fopen(s);
fprintf(s, ['Hello from port number ' num2str(portID)]);
out = fscanf(s, '%c');
fclose(s);
delete(s);
end
out{1}
out{2}
matlabpool close
The other alternative is to do time-slicing, where asynchronous reads would be performed using the 'bytesavailablefcn' callback.

1 commentaire

A loopback connector is a device that returns a communication to the originating port. It's a common device used to diagnose that inbound and outbound communications are working. They work physically by connecting certain pins directly to each other, so effectively the outgoing communication is immediately returned.
So you don't apply this to a script, it's a physical connector you place on the port. Google "buy serial loopback connector" for where to buy one (they are generally very inexpensive), or you can also make them yourself by connecting ports as directed -- Google "how to make a serial loopback cable" for instructions.
Note that the connector is only usefuly for diagnostics, if you had a serial cable connected to a device you would read/write data to it instead -- so the "Hello from port ..." part would have data in it rather than the "Hello from port" message.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by