Why is KbCheck in Psychtoolbox not registering keyboard input?

2.3k Views Asked by At

I'm trying to run a programme coded in Psychtoolbox-3 that should register a keypress. But when I run it, even just this section from the command window, it doesn't respond to the E, P keys (or any) and I have to stop the operation using Ctrl-C. I have tried changing it to {e, p} (which are the names I found using KbName('KeyNames')), but it doesn't work. The same code works on my supervisor's computer - I am using a Mac with OS 11.1.

KbName('UnifyKeyNames');
keyresp = KbName({'E','P'});
key = 0;
while ~key
    [key,tkey] = CheckKeyPress(keyresp);
end

The CheckKeyPress is this function (and it works - gives output 0):

function [key,tkey] = CheckKeyPress(whichkeys)

if nargin < 1 || isempty(whichkeys)
    whichkeys = 1:256;
end

key = 0;
[iskeydown,tkey,keys] = KbCheck(-1);
if any(keys(whichkeys))
    key = find(keys(whichkeys),1);
end

end

I have also tried looking at PsychHID('Devices') and my keyboard is there (and no other keyboards).

Thanks for any help!

2

There are 2 best solutions below

0
On BEST ANSWER

Solved! It was a simple mac problem :)

After I tried KbQueueCreate and got an error message I found the same one on another thread - the only problem is I had to allow Matlab to access keyboard input on my laptop.

Settings - Security and Privacy - Input Monitoring

5
On

It is always a big pain in MacOs. I use this code:

close all
clear all
clc

ListenChar(0);
Devices=PsychHID('Devices');
keyboardsIDs = [];
for iiD = 1:numel(Devices)
    try
        KbQueueCreate(Devices(iiD).index);
        KbQueueStart(Devices(iiD).index);
        keyboardsIDs(end+1,1) = Devices(iiD).index;
    end
end

stopScript = 0;
while ~stopScript
    for iiD = 1:numel(keyboardsIDs)
        [keyIsDown, firstPress]=KbQueueCheck(keyboardsIDs(iiD));
        if keyIsDown
            keyID = find(firstPress)
            disp(keyID)
            if any(keyID ==20), stopScript =1; end
        end
    end
end
for iiD = 1:numel(keyboardsIDs)
    KbQueueStop(keyboardsIDs(iiD));
end
ListenChar();

UPDATE

This is a bit dirty workaround, but it will works in any situation.

Press 'q' to exit the loop