How Can I pass an open serialport-handle to a parallel worker?

22 ビュー (過去 30 日間)
Martin Quintus
Martin Quintus 2022 年 6 月 19 日
回答済み: Thomas Falch 2022 年 7 月 6 日
Hello everyone,
I'm still figuring out parallel workers and am obviously not very good at them.
I'm talking to a TI Microcontroller which controlls a stepper motor + rotary encoder via a Serialport. This works as script AND in an app aswell. As long as this remains single-threaded everything works fine.
I would like to be able to send the configuration commands via the "main script" or "app" BUT I also want to be able to read a pre-set amount of bytes over the same serial port in parallel. While this measurement takes place, no other commands need to be sent by matlab.
I can't get it to work. Either no Data is returned at all or I'm getting errors, that serialport-specific functions are undefined
  1. parfor-loop | no results returned
  2. | undefined function 'read'
Current Test-Script:
clear all
close all
% Start Parallel Pool
% Open and configure Serialport at COM5
SERIAL = serialport("COM5",115200,"Timeout",1);
% Create a parpool-Constant with the Serialport-Handle
cSERIAL = parallel.pool.Constant(SERIAL);
% Measure P,V,D in parallel worker
job = parfeval(gcp(),@STEPPER_DEST,3,cSERIAL, 10);
With the external function being:
function [Position, Geschwindigkeit, Richtung] = STEPPER_DEST(s,Zeit_s)
% Convert time s to ms
Zeit_ms = Zeit_s *1000;
% Create Measuring Vectors
Position = zeros(1, Zeit_ms);
Geschwindigkeit = zeros(1, Zeit_ms);
Richtung = zeros(1, Zeit_ms);
for i=1:Zeit_ms
Position(1,i) = double(read(s,1,"int32")) * 0.18;
Geschwindigkeit(1,i) = double(read(s,1,"uint32"))* 18;
Richtung(1,i) = read(s,1,"int8");


Thomas Falch
Thomas Falch 2022 年 7 月 6 日
You need to use the function handle version of parallel.pool.Constant (which is what does).
Instead of opening the serial port on the client, and then sending it with the Constant to the worker (which will not work), the function handle version sends a function handle to the worker, which will run on the worker, and open the serial port on the worker.
In other words, something like:
function s = openSerialPort()
s = serialport("COM5",115200, "Timeout", 1);
configureTerminator(s, 0);
cSerial = parallel.pool.Constant(@openSerialPort)
% Rest of the code unchanged

その他の回答 (0 件)




Community Treasure Hunt

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

Start Hunting!

Translated by