Reputation: 15
I am setting up a serial communication in matlab without GUI.
The serial initialisation looks like this (main program):
handles.s = serial('COM10' ,'BaudRate', 9600);
set(handles.s,'Terminator','CR');
set(handles.s,'Timeout',1);
set(handles.s, 'BytesAvailableFcnMode', 'byte');
set(handles.s, 'BytesAvailableFcnCount', 1);
set(handles.s, 'BytesAvailableFcn', {@serialEventHandler, handles});
fopen(handles.s);
I am reading the buffer with a callback function (serialEventHandler)
function serialEventHandler(serialConnection, ~, handles)
bytes = get(serialConnection, 'BytesAvailable');
if(bytes > 0 ) % we may have alread read the data
handles.data = fscanf(serialConnection)
% fwrite(handles.appenderFile, handles.data); (not relevant here)
end
end
For some reason, the callback does not update my handles structure and I am unable to access the serial data the main code. I understand this is the role of guidata(hobject, handles) in a GUI application, but is there a way to do this without GUI? Many thanks,
Upvotes: 1
Views: 792
Reputation: 1439
As an alternative method to the ones well described by @gnovice, you could always write the variable contents to a file and read them in other parts of code.
Upvotes: 0
Reputation: 125854
You'll want to take a look at the documentation for Sharing Data Between Workspaces. Two of the options there should work for you, depending on where serialEventHandler
is with respect to your main code:
For functions in separate files: You will need to use global
variables to share your handles
structure between them. In your main program:
global handles
%... Initialize handles ...
set(handles.s, 'BytesAvailableFcn', @serialEventHandler); % Don't have to pass it
And in serialEventHandler
:
function serialEventHandler(serialConnection, ~) % Don't have to pass it
global handles
%... Rest of code ...
end
For functions in the same file: You can nest one function inside the other, allowing them to share access to variables without having to pass them as input or output arguments:
function main
%... Initialize handles ...
set(handles.s, 'BytesAvailableFcn', @serialEventHandler); % Don't have to pass it
%... Rest of main code ...
function serialEventHandler(serialConnection, ~) % Don't have to pass it
%... serialEventHandler code ...
end
end
There is a third option as well (not mentioned in the above documentation on sharing data), but it could be substantially more work to implement: Creating your own class to use in place of your handles
structure and deriving from the handle
class to give it reference-like (i.e. pointer-like) behavior. Although creating a new class would be more involved, it would allow you to pass your handles
object to any function without having to return a modified version. Your code above would likely remain unchanged.
Upvotes: 1