Main Content

Communicate in Parallel with Multiple Devices

This example shows how to use Parallel Computing Toolbox™ to communicate with two serial devices simultaneously.

Serial loopback devices connected to ports COM3 and COM4 are used, so the data sent is the same as data received. Parallel Computing Toolbox is required for this example. By performing serial reads and writes in parallel, the total time required for data transfer can be reduced.

Define Data

Specify the number of bytes to transfer.

numBytes = 10000;

Generate random data to send to the loopback devices.

dataToSend = uint8(randi([0 255], 1, numBytes));

Identify Serial Ports

To find available serial ports, use serialportlist. This command displays all serial ports currently available on your system. Choose the two ports that correspond to your device connections.

serialPortNames = serialportlist("available")
serialPortNames = 1×2 string array
    "COM3"    "COM4"

Parallel Writing and Reading

Next, start a parallel pool with one worker for each device. This parallelizes communication with both devices, reducing execution time overall. This is a local pool of workers on one machine, so each worker has access to a different port.

p = parpool("Processes", 2);
Starting parallel pool (parpool) using the 'Processes' profile ...
Connected to parallel pool with 2 workers.

Parallel Computing Toolbox provides spmd capability, which is useful when you have multiple identical instrument models that take the same commands. In a spmd block, have each worker independently open a serial port. The spmd index assures each worker uses a different port.

spmd
    s = serialport(serialPortNames(spmdIndex), 9600);
end

Use a spmd block to have each worker write and read data.

spmd
    write(s, dataToSend, "uint8");
    dataSPMD = read(s, numBytes, "uint8");
end

After the spmd block finishes, you can retrieve the data by indexing into the Composite object dataSPMD.

data1 = dataSPMD{1};
data2 = dataSPMD{2};

Finally, shut down the parallel pool to free up the system resources.

delete(p);
Parallel pool using the 'Processes' profile is shutting down.

Verify Data Transfer

After transferring data in parallel to both serial devices, you can verify that the data sent matches the data received by using the isequal function. This confirms that the loopback devices are functioning correctly and that the parallel communication was successful.

isData1Correct = isequal(dataToSend, data1);
isData2Correct = isequal(dataToSend, data2);

if(isData1Correct && isData2Correct)
    disp("Data transfer successful: Received data matches sent data on both devices.");
else
    disp("Data transfer failed: Received data does not match data sent on one or both devices.");
end
Data transfer successful: Received data matches sent data on both devices.