Reading Arrow Key Input

조회 수: 40 (최근 30일)
sayyid khan
sayyid khan 2011년 6월 4일
What I'm basically trying to do is control a robot by using the arrow keys on the keyboard. I'm already familiar with outputting commands via MATLAB my main problem is how to read what arrow keys I'm pressing. Ultimately I would like to press an arrow button and have it displayed on the command window.
I came across this bit of code online. It works great but I need the keystrokes to be store in a variable (possibly as a number instead of a string) so I can output it. There may be a simple solution but since I don't really understand the code my attempt to edit it didn't work.
h_fig = figure;
set(h_fig,'KeyPressFcn',@(h_obj,evt) disp(evt.Key));
Thank You
Sayyid Khan

채택된 답변

Matt Fig
Matt Fig 2011년 6월 4일
Here is an example of how to use the arrow keys in the keypressfcn.
function [] = move_fig()
% move figure with arrow keys.
S.fh = figure('units','pixels',...
'position',[500 500 200 260],...
'menubar','none',...
'name','move_fig',...
'numbertitle','off',...
'resize','off',...
'keypressfcn',@fh_kpfcn);
S.tx = uicontrol('style','text',...
'units','pixels',...
'position',[60 120 80 20],...
'fontweight','bold');
guidata(S.fh,S)
function [] = fh_kpfcn(H,E)
% Figure keypressfcn
S = guidata(H);
P = get(S.fh,'position');
set(S.tx,'string',E.Key)
switch E.Key
case 'rightarrow'
set(S.fh,'pos',P+[5 0 0 0])
case 'leftarrow'
set(S.fh,'pos',P+[-5 0 0 0])
case 'uparrow'
set(S.fh,'pos',P+[0 5 0 0])
case 'downarrow'
set(S.fh,'pos',P+[0 -5 0 0])
otherwise
end
%
%
%
%
EDIT
% This assigns the string value of the key to a in the base workspace.
set(h_fig,'KeyPressFcn',@(H,E) assignin('base','a',E.Key));
  댓글 수: 2
Matt Fig
Matt Fig 2011년 6월 5일
sayyid khan comments,
Thanks for the quick response. But is there a way I can use that original 2 lines of code and just have it save to a variable.
For example
Press right arrow > a = 'right arrow'; Press left arrow > a = 'left arrow'.
If it could give me the variable in terms of the ascii code that would be perfect.
Thank you
Sayyid Khan
Matt Fig
Matt Fig 2011년 6월 5일
See my edit above.
Put comments on particular answers in the comments section, not as new 'answers'....

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Desktop에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by