2015-08-08 40 views
-1

我从MatLab开始。在MatLab指南中创建新字段

我创建了一个指南UI。我继续前进,并假设我可以在创建的句柄结构中添加新的表达式。

我可以这样做吗?

例如,当我在我的程序中引用handle.s时,出现一个错误,我正在接受一个不存在的字段。

handles.s被创建用来存储一个串行端口对象,该对象在函数中生成,该函数初始化我的PC和微控制器之间的串行通信。

串口对象具有自己的方法和域...可能是因为我无法将对象作为域传递给包含导向UI属性的句柄对象吗?

这里是我与

function [ s, flag] = setupSerial(comPort) 
%Initialize serial port communication between Arduino and Matlab 
%Ensure that the arduino is also communicating with Matlab at this time. 
%if setup is complete then the value of setup is returned as 1 else 0. 

flag =1; 
s = serial(comPort); 
set(s,'DataBits',8); 
set(s,'StopBits',1); 
set(s,'BaudRate',9600); 
set(s,'Parity','none'); 
fopen(s); 
a='b'; 
while (a~='a') 
    a=fread(s,1,'uchar'); 
end 
if (a=='a') 
    disp('serial read'); 
end 
fprintf(s,'%c','a'); 
mbox = msgbox('Serial Communication setup.'); uiwait(mbox); 
fscanf(s,'%u'); 
end 

工作在我的UserInterface.m文件中的代码,我传过来的对象在claaback功能如下

function SerialBtn_Callback(hObject, eventdata, handles) 
% hObject handle to SerialBtn (see GCBO) 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA 
comPort = get(handles.COMportTxt,'String'); 
if(~exist('serialFlag','var')) 
    [handles.s, handles.serialFlag] = setupSerial(comPort); 
end 
end 

我得到的错误,当我按'主页'按钮。这里是回调功能可按

function HomeButton_Callback(hObject, eventdata, handles) 
% hObject handle to HomeButton (see GCBO) 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA) 
disp('home button pressed'); 
fprintf(handles.s,'%s', 'G2'); 
set(handles.CurrentPositionTxt, 'String', '0'); 
end 

有错误我得到的是以下

Reference to non-existent field 's'. 

这里您在GUI信息

enter image description here

+1

请将代码发布在您定义手柄的位置。你是否用guidata保存句柄? –

+0

我添加了代码。我不认为我用guidata没有保存手柄。简单地将对象传递给之前确实存在的新的场景。 – Ethienne

回答

1

回调,其中handles.s被定义为不保存手柄对象。您必须使用guidata进行保存,以便稍后在另一个回叫中使用它。

function SerialBtn_Callback(hObject, eventdata, handles) 
% hObject handle to SerialBtn (see GCBO) 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA 
comPort = get(handles.COMportTxt,'String'); 
if(~exist('serialFlag','var')) 
    [handles.s, handles.serialFlag] = setupSerial(comPort); 
end 
guidata(hObject,handles) 

希望这会有所帮助。

+0

工作正常!谢谢 – Ethienne