user3101497
user3101497

Reputation: 31

pass value between two callback function in matlab GUI

I have 2 pushbutton. If i press one infinte loop will be running and if i press other loop must break. please some help in code.

Thanks in advance

Upvotes: 0

Views: 689

Answers (1)

Steve Osborne
Steve Osborne

Reputation: 680

Are you using GUIDE or a "programmatic" gui? The following is a little example for a programmatic gui; similar concepts may apply for GUIDE. (I personally like the added flexibility of the programmatic gui route, plus I always end up irrevocably breaking any GUIDE gui's I create...)

Anyway, a few things to note in this example:

  1. use of the gui's figure handle UserData field to store "global" information. This is a way to pass data between callbacks.
  2. the pause statement within the "infinite" loop is needed so that the interrupt from cb_button2 is processed. From Matlab help: "If the Interruptible property of the object whose callback is executing is on , the callback can be interrupted. However, it is interrupted only when it, or a function it triggers, calls drawnow, figure, getframe, pause, or waitfor."

    function my_gui(varargin)
    
        mainfig = figure;
    
        out.h_button1 = uicontrol(mainfig,...
                                    'Style','pushbutton',...
                                    'Units','Normalized',...
                                    'Position',[0,0.5,1,0.5],...
                                    'String','Button 1',...
                                    'Callback',@cb_button1);
    
        out.h_button2 = uicontrol(mainfig,...
                                    'Style','pushbutton',...
                                    'Units','Normalized',...
                                    'Position',[0,0,1,0.5],...
                                    'String','Button 2',...
                                    'Callback',@cb_button2);
    
        out.button2_flag = 0; %flag indicating whether button 2 has been pressed yet
    
        set(mainfig,'UserData',out);%store "global" data in mainfig's UserData (for use by callbacks)          
    
    
    function cb_button1(varargin)
    
        out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
    
        while ~out.button2_flag
            disp('Aaaahhh, infinite loop! Quick press Button 2!');
            out = get(gcbf,'UserData'); %reload "global" data
            pause(0.1); %need this so this callback may be interrupted by cb_button2
        end
    
        disp('Thanks!  I thought that would never end!');
    
    
    function cb_button2(varargin)
        out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
        out.button2_flag = 1;
        set(gcbf,'UserData',out); %save changes to "global" data
    

Upvotes: 2

Related Questions