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

34 ビュー (過去 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.
Background:
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.
Goal:
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.
Problem:
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
Tried:
  1. parfor-loop | no results returned
  2. https://de.mathworks.com/matlabcentral/answers/372772-how-can-i-pass-a-tcpip-handle-to-a-parfeval-worker | undefined function 'read'
Current Test-Script:
clear all
close all
clc
% Start Parallel Pool
parpool(2);
% Open and configure Serialport at COM5
SERIAL = serialport("COM5",115200,"Timeout",1);
configureTerminator(SERIAL,0);
% 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);
fetchOutputs(job);
delete(gcp('nocreate'));
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");
end
end

採用された回答

Thomas Falch
Thomas Falch 2022 年 7 月 6 日
You need to use the function handle version of parallel.pool.Constant (which is what https://www.mathworks.com/matlabcentral/answers/372772-how-can-i-pass-a-tcpip-handle-to-a-parfeval-worker 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);
end
cSerial = parallel.pool.Constant(@openSerialPort)
% Rest of the code unchanged

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSerial and USB Communication についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by