dcmotor
dcmotor

Reputation: 58

How to pass serial communication object from one callback to another callback in matlab

I have created a button which on press will send data 's' to microcontroller and another button which on pressing needs to send 'g' to microcontroller .But the problem is that how can i send data using same serial communication object.I tried passing s using guidata but din't work. Can anyone help . I am new to matlab.

matlab code:

//first button

 function start_Callback(hObject, eventdata, handles)
 s = serial('COM2');
 set(s,'BaudRate',9600);
 set(s,'Timeout',10);
 set(s,'ReadAsyncMode','continuous');
 fopen(s);
 fprintf(s,'%c','s');
 guidata(hObject,s);

//second button

 function stop_Callback(hObject, eventdata, handles)
 s = guidata(hObject);
 fopen(s);
 fprintf(s,'%c','g');
 fclose(s)
 delete(s)

Upvotes: 1

Views: 589

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

You're not using guidata and handles in the right way. I would think you'll need something like:

//first button

 function start_Callback(hObject, eventdata, handles)
 s = serial('COM2');
 set(s,'BaudRate',9600);
 set(s,'Timeout',10);
 set(s,'ReadAsyncMode','continuous');
 fopen(s);
 fprintf(s,'%c','s');
 handles.s = s;
 guidata(hObject,handles);

//second button

 function stop_Callback(hObject, eventdata, handles)
 s = handles.s;
 fopen(s);
 fprintf(s,'%c','g');
 fclose(s)
 delete(s)

Think of it like this. handles is a big variable (a struct) that contains references to all the parts of your GUI in each of its fields.

It is stored in the parent figure of your GUI, and gets passed in to every GUI callback, so that the callback functions can refer to various parts of the GUI if they need to.

You can also store your own things in fields of handles (here we've stored your serial object s in a field called handles.s) - but if you do this, you need to refresh handles before the function ends, so that later callbacks get your updated version. That's what guidata does - it pushes your updated handles up to the ancestor of hObject, which is the parent figure of the GUI. Once that is done, later callbacks such as stop_callback get the updated handles, which now has s stored in a field, and it can be retrieved and used.

Upvotes: 1

Related Questions