GUI button to initiate serialport object - Impossible?
Show older comments
Hi All
I am implementing a programmatic GUI. I want a button which, when pressed, will initiate a serialport object and connect to it and automatically stream data back to the base workspace.
Problem is, I dont think this can be done.
BGcolour = [0.20 0.92 0.86];
serial_port = "COM11";
serial_baud = 230400;
serial_connected = 0;
figureGUI = figure('position',[200 200 800 600],...
'name','Serial Interface',...
'numbertitle','off',...
'resize','OFF',...
'toolbar','none',...
'menubar','none',...
'color', BGcolour);
serialConnectui=uicontrol(figureGUI, 'style','pushbutton',...
'units','pixels',...
'position',[70 410 62 62],...
'callback', {@serialConnect, serial_port,serial_baud});
function [] = serialConnect(src, event,serial_port,serial_baud)
serial_connected = evalin('base', 'serial_connected');
% s = evalin('base', 's');
if (serial_connected == 1)
disp("already connected");
else
fprintf("Attempting to Connect to %s at %3.0f kb/s\n", serial_port, serial_baud);
try
s = serialport(serial_port, serial_baud);
catch
disp("***Connection Failed***");
serial_connected = 0;
assignin('base','serial_connected',serial_connected);
return;
end
configureCallback(s,"byte",1,@bytesavailable);
% assignin('base','s',s);
serial_connected = 1;
assignin('base','serial_connected',serial_connected);
disp("***Connected!***");
%pause(10);
end
end
function bytesavailable(src, ~)
msg = read(src,src.NumBytesAvailable,"char");
disp(msg);
end
Here is my attempt. I cant get the data to keep streaming using my Display() function. it is because as soon as serialConnect ends, the serialport object, s, is lost. This can be demonstrated by putting a Pause(10) in directly under the line Display("***Connected***");. It will stream for 10 seconds then stop when the function finishes.
However, callbacks in GUI's cant return values, so I can't simply return s.
As you can see I have tried using evalin and its friend assignin to get a serialport from the base workspace. The problem with this is that, contrary to what https://uk.mathworks.com/help/instrument/serialport.html would have you initially believe, there is no empty constructor for the serialport object. Thus, I cannot simply declare a placeholder "blank" serialport object called s at the base workspace level.
I dont want to have my serialport connect immediately as the program starts.
Is there any workaround to tihs?
Cheers
Accepted Answer
More Answers (0)
Categories
Find more on Serial and USB Communication in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!