входящие последовательные данные, мешающие обратным вызовам MATLAB - PullRequest
0 голосов
/ 03 октября 2019

У меня есть код, который использует информацию, полученную через последовательный порт, сравнивает ее с сохраненной строкой, а затем изменяет значения цвета панели в графическом интерфейсе. это сделано для 2 разных панелей. если значение strcmp для обеих панелей равно 1, активируется кнопка закрытия GUI. я хочу использовать простую функцию closereq (), чтобы закрыть его, но это не сработало. чтобы попробовать что-то другое, я прокомментировал closereq () и добавил в disp («Успех»). При нажатии на кнопку «Успех» появится в окне команд, но только после того, как я вручную приостановлю программу с панели редактора.

это мой код:

function varargout = WorkingGUI3(varargin)
% WORKINGGUI3 MATLAB code for WorkingGUI3.fig
%      WORKINGGUI3, by itself, creates a new WORKINGGUI3 or raises the existing
%      singleton*.
%
%      H = WORKINGGUI3 returns the handle to a new WORKINGGUI3 or the handle to
%      the existing singleton*.
%
%      WORKINGGUI3('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in WORKINGGUI3.M with the given input arguments.
%
%      WORKINGGUI3('Property','Value',...) creates a new WORKINGGUI3 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before WorkingGUI3_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to WorkingGUI3_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help WorkingGUI3

% Last Modified by GUIDE v2.5 02-Oct-2019 14:53:57

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @WorkingGUI3_OpeningFcn, ...
    'gui_OutputFcn',  @WorkingGUI3_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before WorkingGUI3 is made visible.
function WorkingGUI3_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to WorkingGUI3 (see VARARGIN)
handles.uipanels = [handles.uipanel1, handles.uipanel2];
set(handles.pushbutton5, 'enable', 'off');
% Choose default command line output for WorkingGUI3
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes WorkingGUI3 wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = WorkingGUI3_OutputFcn(hObject, eventdata, handles)
delete(instrfind('Port', 'COM3'));
tag = serial('COM3');
fopen(tag);
BOX = char(zeros(2,14)); % matrix to be populated with incoming serial data
TrueValueData = 'C:\RfidChipTrueValues.xlsx';
[~,~,TrueValMat] = xlsread(TrueValueData);
% Creates matrix filled with the correct values
% indexed by box, which is the first row
% all proceeding rows are the master value
for i=1:inf
    for n = 1:2
        if i>10
            readData = fscanf(tag);
            if length(readData)>12
                BOX(str2double(readData(8)),1:14)= readData(11:24);
                if strcmp(TrueValMat{2,n}, BOX(n,:))
                    set(handles.uipanels(n), 'BackgroundColor', 'g');
                else
                    set(handles.uipanels(n), 'BackgroundColor', 'r');
                end
                drawnow
                if strcmp(TrueValMat{2,1}, BOX(1,:))...
                        && strcmp(TrueValMat{2,2}, BOX(2,:)) == 1
                    set(handles.pushbutton5, 'enable', 'on');
                end
            end
        end
    end
end
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%closereq();
disp('It Works')

последний раздел

% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%closereq();
disp('Success')

удерживает обратный вызов для кнопки. Я знаю, что он правильно подключен к файлу .fig, потому что нажатие кнопки вызывает успех, но только после ручной приостановки программы.

любая помощь будет высоко ценится.

1 Ответ

0 голосов
/ 07 октября 2019

Как показала @Rotem, добавление паузы после первого цикла for позволило программе закрыться.

...