Accessing serial ports in background tasks: the port is already in use

10 次查看(过去 30 天)
Hi there,
I have an object 'device' in my main function. The device object contains a property 'serialPort', and functions that perform read and write operations using the serialPort.
Now I want to be able to write to the serialPort from background functions as well. I do this by creating a background task and passing the 'device' object. So like this:
%create the object
device = serialdevice('COM9'); %device is an object which inherits from handle, with a property which is the serialPort
isa(device,'handle') %results in true
device.serialPort %results in "Serialport with properties: Port: "/dev/ttyACM0", BaudRate: 115200, NumBytesAvailable: 0"
device.setLed(true); %this writes a message accross the port which turns on the LED. No errors, the LED turns on.
%create a background task to turn on the LED
fA = parfeval(backgroundPool,@set_LED_background,0,device);
pause(1)%the future runs
fA.Error %this prints the error: 'Unable to connect to the serialport device at port 'COM9'.
%Verify that a device is connected to the port, the port is not in use, and all serialport input
%arguments and parameter values are supported by the device. Additional Information: Port is already in use.
function set_LED_background(device)
device.setLed(true);
end
So as per the comments in the snippet this does not work.
It seems that the port is in use by the main thread, and this disallows writing to the port from another thread.
I assumed that making the device a handle might help, but it does not.
Can anyone explain in more detail why this does not work? Is there any other way to do this, or should I close and re-open the port every time I launch a new background task (which is not desirable)?

回答(1 个)

Poorna
Poorna 2023-12-6
Hi Roel Budé,
I understand that you are trying to write to a serial port in background using “parfeval” but instead getting errors.
The “parfeval” requests are executed on separate processes and passing the device object created on the main thread to the background process will not work. Instead, you should create a separate device” object with its own serial port in the background process and then use it.
So, instead of passing the device object from the main thread. Create the device object inside the function executed by “parfeval” and then use it.
Please refer to the following answer which addresses similar query of passing serial device objects to parallel workers.
Hope this Helps!
Best regards,
Poorna.

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by