Run pushbutton callback only 3 times, after that display warning message

1 view (last 30 days)
Hi! I am new in matlab, can you please help me with this question: While clicking on pushbutton callback it plays wav file. I want to limit number of clicks to max 3 times. When clicking 4th time get error message: warndlg({'Warning: You exceeded number of repetitions.';}); Should I use loops or what?? Thank you in advance!!!
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if handles.status==1
handles.status=0;
play(handles.r);
end

Accepted Answer

David Sanchez
David Sanchez on 5 Jun 2013
in GUI initialization function:
global times_pushed
times_pushed = 0;
in your callback function:
global times_pushed
times_pushed = times_pushed + 1;
if times_pushed == 4
errordlg('your error message here');
times_pushed = 0;
end

More Answers (2)

David Sanchez
David Sanchez on 5 Jun 2013
Define a global variable and initialize to 0 within initialization function:
global times_pushed
times_pushed = 0;
Within the callback function, increment the value of this variable each time the function is called ( the button in pushed )
timer_pushed = times_pushed + 1;
if times_pushed == 4
errordlg('your error message here');
times_pushed = 0;
end
  2 Comments
Iain
Iain on 5 Jun 2013
Don't use globals if you can avoid them.
You can use "persistent" variables, if you only want one function to access it.
You can put a count of how many times it has been played into the "userdata" property of a graphics object and retrieve it with set and get

Sign in to comment.


Lucky
Lucky on 5 Jun 2013
Thank you very much! But i still dont understand where should i put this: if handles.status==1 handles.status=0; play(handles.r); end
Should it be after initializing the variable?
global times_pushed
times_pushed = 0;
if handles.status==1
handles.status=0;
play(handles.r);
end
times_pushed = times_pushed + 1;
if times_pushed == 4
errordlg('your error message here');
times_pushed = 0;
end
  1 Comment
Iain
Iain on 5 Jun 2013
set(h, 'Userdata', variable)
Takes the contents ot "variable", and puts it in the "userdata" property of the item referred to by "h".
v = get(h,'Userdata')
Retrives the contents of the userdata property of the item referred to by h, and puts it in the variable "v".

Sign in to comment.

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!