How Can I pass an open serialport-handle to a parallel worker?
16 views (last 30 days)
Show older comments
Martin Quintus
on 19 Jun 2022
Answered: Thomas Falch
on 6 Jul 2022
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:
- parfor-loop | no results returned
- 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
0 Comments
Accepted Answer
Thomas Falch
on 6 Jul 2022
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 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!