% KbPractice.m % Displays the number of seconds that have elapsed % when the user presses a key. % a simplified version of KbDemo modified by YW, 2022 KbName('UnifyKeyNames'); WaitSecs(1.0); disp('Testing KbCheck and KbName: press a key to see its number'); disp('Press the ''SPACE'' key to exit.'); escapeKey = KbName('SPACE'); ListenChar(2); while KbCheck; end % Wait until all keys are released. % This is a loop that flips around doing anything as long as KbCheck % reports back that a key is pressed on the keyboard. Means that the % program doesnĄ¯t continue until all keys have been released. startSecs = GetSecs; while 1 % while 1 is always true, so this loop will continue indefinitely. % Line 28 forceably breaks us out of the loop if the escape key is % pressed. % Check the state of the keyboard. % See if a key is currently pressed on the keyboard. If not, we skip % the next for loop from lines 20-38, and basically check again almost % immediately. [ keyIsDown, seconds, keyCode ] = KbCheck; % If the user is pressing a key, % then display its code number and name. if keyIsDown % Note that we use find(keyCode) because keyCode is an array. str=['You pressed key ', num2str(find(keyCode)),' which is ', KbName(keyCode), ' typed at time ', ... num2str(seconds - startSecs), 'seconds']; disp(str); % Display which key has been pressed. % If the key that has been pressed is the escape key break out of all loops % including the indefinite while loop. if keyCode(escapeKey) break; end while KbCheck; end % If the user holds down a key for more than a microsecond, % KbCheck will report multiple events, since computers are faster % than people's fingers % To condense multiple 'keyDown' events into a single event, % once a key has been pressed % we wait until all keys have been released % before going through the loop again end end ListenChar(0);