Detect Keyboard Input Matlab

前端 未结 4 819
不知归路
不知归路 2020-12-11 03:01

I have a simple question, although it\'s harder than it seems; I couldn\'t find the answer on the interwebs :O

I\'m writing a script in Matlab. What I want to do is

相关标签:
4条回答
  • 2020-12-11 03:10

    KeyPressFcn is good because it forces you to write event-driven code. Which is generally a good idea! However, if KeyPressFcn doesn't seem right for you, for example if you must keep running in a loop, and you just want to poll whether a key has been pressed, I found this solution buried in the matlab website:

    get(gcf,'CurrentCharacter')
    

    Then you could set this property to a blank, and poll it as required. e.g:

    finish=false;
    set(gcf,'CurrentCharacter','@'); % set to a dummy character
    while ~finish
      % do things in loop...
    
      % check for keys
      k=get(gcf,'CurrentCharacter');
      if k~='@' % has it changed from the dummy character?
        set(gcf,'CurrentCharacter','@'); % reset the character
        % now process the key as required
        if k=='q', finish=true; end
      end
    end
    

    This worked well for me in 2014b. The downside is that the graphics window needs to be focused to receive the key events.

    0 讨论(0)
  • 2020-12-11 03:14

    I frequently ran into similar use cases and typically preferred to react to joystick buttons because of the more convenient interface provided by vrjoystick. However, I recently wrote a library that provides a similar interface for keyboard inputs.

    % Pause on ESC
    kb = HebiKeyboard();
    while true
        state = read(kb);
        if state.ESC
          % PAUSE DRIVING
        else
          % DRIVE CAR
        end
    end
    

    It's non-blocking and doesn't require focus on any particular figure.

    File Exchange: http://mathworks.com/matlabcentral/fileexchange/61306-hebirobotics-matlabinput

    Github: https://github.com/HebiRobotics/MatlabInput

    0 讨论(0)
  • 2020-12-11 03:18

    In a matlab figure you can define a 'KeyPressFcn' that works similar to do what you ask.

    If you are in the console you have to work around that matlab is single threaded. Basically you need to halt the program flow to check for key presses.

    btw - also when you use 'KeyPressFcn' you will need to make some pauses so that Matlab will check if anything has happened.

    btw2 - I should also add during this pauses Matlab will not only read your key presses - but also do some housekeeping such as redrawing its window and stuff.

    0 讨论(0)
  • 2020-12-11 03:28

    I had a related task once, and i did it with getkey form matlab file exchange. Basicly you will want to have it listen for ascii 1B (27 decimal)

    if getkey does not solve your problem you can still have a look at its code and maybe find the line that will do the trick for you.

    0 讨论(0)
提交回复
热议问题