Diusha
Diusha

Reputation: 21

Loop and keyboard don’t work simultaneously

I am writing a MATLAB program, (1) containing main loop and (2) using keyboard. However, they are don’t work simultaneously.

  1. Code
function p
 
fig=figure(1);
set(fig,'KeyPressFcn',@myfun);
 
% plot(1,1)   %2
% drawnow     %2
 
ex=0;
% while ~ex   %1
% % ...       %1
% end         %1
 
  function myfun(~,event)
    disp(event.Key);
  end
 
end

works: Figure 1 window opens, and all keystrokes appear in command window.

  1. Open lines marked with %1, i.e. add the main loop, and start the script execution. Figure 1 window doesn’t open. Stopping the script execution with Ctrl-C, Figure 1 opens and keystrokes begin to appear in command window.

  2. Now open lines marked with %2 and start. The Figure 1 window opens, but there is no visible reaction to keystrokes. Stopping the script execution with Ctrl-C, all keystrokes that occurred between startup and Ctrl-C dump out into the command window.

How can I make main loop and keystrokes response to work simultaneously?

Upvotes: 2

Views: 41

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60761

When MATLAB is running code (as it does for example in your loop), it does nothing else. UI evens are queued and not handled until the computation (code execution) stops.

Instead, let your function terminate. The figure will continue to exist, and will continue to react to UI events.

To interact with the COM port at regular time intervals, use timer. Similarly to UI events, the timer will continue running even when MATLAB is idling.

Alternatively, if you need to do some long computation and still allow for user interaction, regularly issue a short pause so that UI events can be handled. There is also drawnow, which should allow UI events to be handled, but I have not been very successful with it in the past.

Upvotes: 4

Related Questions