MATLAB: How to open and close serial port in GUI based on flag

gui

I am trying to open and close port using handle.port_stt. It seems not to work for some reason. Also i can not open and close port multiple times.
Error using serial/fscanf (line 154)
Unsuccessful read: OBJ must be connected to the hardware with FOPEN.*
function open_port_btn_Callback(hObject, eventdata, handles)
global myport;
%----------------------Port opening-----------------------%
%
handles=guidata(hObject);
if(~strcmp(handles.port_stt,'opened'))
fopen(myport);
handles.port_stt='opened';
guidata(hObject,handles);
end
% --- Executes on button press in close_port_btn.
function close_port_btn_Callback(hObject, eventdata, handles)
global myport;
%----------------------Port closing-----------------------%
handles=guidata(hObject);
if(~strcmp(handles.port_stt,'closed'))
fclose(myport);
handles.port_stt='closed';
guidata(hObject,handles);
end
% --- Executes on button press in read_btn.
function read_btn_Callback(hObject, eventdata, handles)
global myport;
handles=guidata(hObject);
while(strcmp(handles.port_stt,'opened'))
handles=guidata(hObject);
x=fscanf(myport,'%f')/100
pause(0.0001);
end

Best Answer

You did an fopen(), but you do not know that it worked. You should check the Status property of the object, which will become 'open' upon success.
Related Question