Assigning ASC-II Characters in MATLAB

Recently I have been working to replicate the cockpit of Piper PAS 28 aircraft in MATLAB. Although the things went pretty well, but I was having serious trouble to define interface such that the user can control the instruments from keyboard. After some lengthy search and experiments with the programme I managed to assign my instruments with keyboard commands. I thought it is now a best idea to share this with others who are trying something along the same lines. It worked well for me, so I hope it will work with you too.

The graphic model includes the commands defining the user interface, allowing user to control the simulator from keyboard. The user interface model incorporates two files, first file ‘GETKEY’, waits for a key press and returns the ASCII code. Accepts all ASC-II characters, including backspace (8), space (32), and enter (13), etc, that can be typed on the keyboard. Non-ASC-II keys (ctrl, alt, ..) return a NaN. The example of GETKEY function is illustrated below:

function ch = GETKEY(m)
global Display
fprintf(‘\nPress any key: ‘) ;
ch = getkey ;
fprintf(‘%c\n’,ch) ;
fprintf(‘\nPress the Ctrl-key: ‘) ;
if strcmp(getkey(‘non-ascii’),’control’),
fprintf(‘OK\n’) ;
else
fprintf(‘ … wrong key …\n’) ;
end

In order to assign the keys to variables and appropriate figure, Display structures and MATLAB graphics library as discussed earlier are extensively used. The graphic handles assigned in sub-modules of graphic library are used to allocate the key commands. This is best illustrated by the following example:

% Determine the callback string to use
if nargin == 1,
if strcmp(lower(m),’non-ascii’),
callstr = [‘set(gcbf,”Userdata”,get(gcbf,”Currentkey”)) ;
uiresume ‘] ;
else
error(‘Argument should be the string ”non-ascii”’) ;
end
else
callstr = [‘set(gcbf,”Userdata”,double(get(gcbf,”Currentcharacter”))) ; uiresume ‘] ;
end

% Set up the figure
fh = figure(‘keypressfcn’,callstr, … % using Handle defined
‘windowstyle’,’modal’,…
‘position’,[0 0 1 1],…
Name’,’GETKEY’, …
‘userdata’,’timeout’) ;
try

% Wait for something to happen
uiwait ;
ch = get(fh,’Userdata’) ;
if isempty(ch),
ch = NaN ;
end
catch% error return to empty matrix.
ch = [] ;
end

Hope you guys got the idea. Happy Programming and please do not hesitate to add or comment about the article

Advertisements

Leave a comment

Filed under Engineering

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s