MATLAB Example Code - isKeyPressed
Note: The function requires MATLAB 7.4 or greater for the
KeyReleaseFCN? functionality. Attempting to run the function on any version earlier than 7.4 will result in an error.
The isKeyPressed function checks to see if a certain key is pressed. For simplicity, a string is used for the arrow keys (upArrow, downArrow, leftArrow, rightArrow) as opposed to using the nominal control characters normally associated with the arrow keys. Single keys may also be checked by passing their values to the function.
Examples
Check to see if the up arrow key is being pressed
if isKeyPressed('upArrow') == 1
% React to the fact that the upArrow key is currently being pressed
end
if isKeyPressed('A') == 1
% React to the fact that the A key is currently being pressed
end
Source Code
function [keyPressed]= isKeyPressed(keyToCheck)
% usage: isKeyPressed(keyToCheck)
% purpose: Tests to see if a key is being pressed
global gCurrentKeyPress;
currentKey = gCurrentKeyPress;
% Is there anything to process?
if isempty(currentKey) == 1;
keyPressed = 0;
return;
end
% Default is 0 unless we find otherwise
keyPressed = 0;
% Quick check of an exact match
if keyToCheck == currentKey
currentKey= 1;
else
% Exceptions using string checks for the string mappings of arrows
% (our mapping, not MATLAB's)
if strcmp(keyToCheck, 'upArrow') == 1;
if currentKey == 30
keyPressed = 1
end
end
if strcmp(keyToCheck, 'downArrow') == 1;
if currentKey == 31
keyPressed = 1
end
end
if strcmp(keyToCheck, 'rightArrow') == 1;
if currentKey == 29
keyPressed = 1
end
end
if strcmp(keyToCheck, 'leftArrow') == 1;
if currentKey == 28
keyPressed = 1
end
end
end
end
Other Notes
- It does not prevent the capture of multiple key strokes, i.e. if the key is still pressed multiple calls to isKeyPressed will still show that it is pressed.
Related Code / Code Dependencies