Experiments example 6: Current Designs dial (fORP 905)

The MEG Lab has a fiber-optic rotary dial (Current Designs HHSC-1x1-DIAL) that participants can turn left or right inside the MSR, for rating scales, continuous tracking or adjustment tasks. It reaches the stimulus PC through the Current Designs FIU-905 interface, which plugs in by USB.

The hardware, ports and cabling are described in the KIT system specification. This page is about using the dial from Psychtoolbox.

Scripts can be found under experiments/psychtoolbox/dial_test/.

How the dial arrives in MATLAB

The 905 behaves like a USB keyboard. It decodes the dial itself and types one key per step:

Dial movement

What the 905 sends

one step clockwise

a short tap (about 1 ms) of the key t

one step counter-clockwise

a short tap of the key b

at rest

usually nothing; sometimes alternating t b t b ... taps (see Rest chatter below)

Nominally one step is 1 degree, i.e. 360 steps per turn. Check it once with dial_dot_demo (below) and pass the measured number to dial_open if it differs.

Because every step is a key tap, you read the dial with a Psychtoolbox keyboard queue (KbQueueCreate / KbEventGet), which collects taps in the background so none are lost while a frame is drawn. The position is simply the number of t taps minus the number of b taps. Do not use KbCheck: it only sees keys that are down at the moment you call it, and each tap lasts about 1 ms.

Warning

The 905 sets its optical gain at the moment its USB cable is plugged in. If the dial is not moving at that moment, the gain is wrong for a rotary device and the 905 mis-decodes the direction (about as many b as t in one turn). Always:

  1. connect the dial (and the fiber bundle, if used) to the 905 first,

  2. have someone turn the dial continuously,

  3. plug in the 905 USB cable while the dial is turning, keep turning for a few seconds,

  4. run dial_dot_demo to confirm that one turn moves the dot once round.

This has to be repeated whenever the 905 loses USB power (cable unplugged, PC cold boot), not after every MATLAB session.

Rest chatter

When the dial comes to rest exactly on an encoder edge, the 905 can keep sending alternating t b t b ... taps at more than 100 per second, and the TRIGGER and B1 LEDs on its front panel blink continuously. The taps cancel out in the t - b count, so the measured position does not drift. Two practical consequences:

  • while an experiment is not running, the chatter is typed into whichever window has focus. Unplug the 905 USB when it is not in use (and redo the gain procedure when plugging it back in), or nudge the dial by a degree;

  • dial_poll may report a delta of +1 or -1 on consecutive frames while the dial is at rest. If a trial should end “when the dial stops moving”, use a tolerance of a few steps rather than exactly zero.

Test scripts

dial_dot_demo: a dot on a circle follows the dial. Use it to check the cabling, the gain procedure and the number of steps per turn (press SPACE at 12 o’clock, turn the dial exactly once, read the step count on screen).

cd experiments/psychtoolbox/dial_test
dial_dot_demo            % 360 steps per turn, on the last screen
dial_dot_demo(360, 1)    % on screen 1
function dial_dot_demo(stepsPerTurn, screenNum)
% DIAL_DOT_DEMO  Visualise the Current Designs dial: a dot moves on a circle.
%
% The FIU-905 reports the dial as keyboard taps: 't' = one step clockwise,
% 'b' = one step counter-clockwise (1 degree per step as specified). The
% dot's angle is simply (t taps - b taps) * 360 / stepsPerTurn, measured
% clockwise from 12 o'clock. Rest chatter (alternating t b t b ...) cancels
% out in that difference, so the dot stays put.
%
% Usage:  dial_dot_demo            % 360 steps per turn, on the last screen
%         dial_dot_demo(400)       % if the probe measured 400 steps/turn
%         dial_dot_demo(360, 1)    % on screen 1
%
% Keys (operator keyboard):  SPACE = reset dot to 12 o'clock,  ESC = quit.
%
% Before running: the 905 must have had its gain set with the dial turning
% (attach the dial, then plug in the 905's USB while turning the dial).

if nargin < 1 || isempty(stepsPerTurn), stepsPerTurn = 360; end
if nargin < 2 || isempty(screenNum),    screenNum = max(Screen('Screens')); end

KbName('UnifyKeyNames');
keyT = KbName('t'); keyB = KbName('b');
keyEsc = KbName('ESCAPE'); keySpace = KbName('space');

% Demo only: do not stall on the display timing tests of this PC.
oldSync = Screen('Preference', 'SkipSyncTests', 1);
PsychDefaultSetup(2);

win = []; %#ok<NASGU>
cleanup = onCleanup(@() cleanupAll(oldSync)); %#ok<NASGU>

[win, rect] = PsychImaging('OpenWindow', screenNum, 0.5);
Screen('BlendFunction', win, 'GL_SRC_ALPHA', 'GL_ONE_MINUS_SRC_ALPHA');
[cx, cy] = RectCenter(rect);
R    = 0.35 * min(rect(3:4));   % circle radius (px)
dotD = 0.05 * min(rect(3:4));   % dot diameter (px)
Screen('TextSize', win, 28);
HideCursor(win);

white = [1 1 1]; black = [0 0 0]; dotCol = [1 0.85 0.2];

KbQueueCreate();
KbQueueStart();
KbQueueFlush([], 3);
ListenChar(-1);   % keep the dial's taps out of the MATLAB console

steps = 0; nT = 0; nB = 0;
taps = zeros(2, 0);     % [time; +1 or -1] of the taps in the last second

% tick marks every 30 degrees
tick = zeros(2, 24);
for k = 0:11
    a = deg2rad(30 * k);
    tick(:, 2*k+1) = [cx + R * sin(a);        cy - R * cos(a)];
    tick(:, 2*k+2) = [cx + 0.93 * R * sin(a); cy - 0.93 * R * cos(a)];
end

while true
    % ---- decode dial taps -------------------------------------------
    while KbEventAvail() > 0
        e = KbEventGet();
        if ~e.Pressed, continue; end
        switch e.Keycode
            case keyT,     steps = steps + 1; nT = nT + 1; taps(:, end+1) = [e.Time; +1]; %#ok<AGROW>
            case keyB,     steps = steps - 1; nB = nB + 1; taps(:, end+1) = [e.Time; -1]; %#ok<AGROW>
            case keySpace, steps = 0; nT = 0; nB = 0;
            case keyEsc,   return;
        end
    end
    tNow = GetSecs;
    taps(:, taps(1, :) < tNow - 1) = [];
    rate    = size(taps, 2);          % taps in the last second
    netRate = sum(taps(2, :));        % net steps in the last second

    % ---- geometry: angle clockwise from 12 o'clock -------------------
    ang = 360 * steps / stepsPerTurn;
    a   = deg2rad(ang);
    x   = cx + R * sin(a);
    y   = cy - R * cos(a);
    turns = floor(steps / stepsPerTurn);

    % ---- draw ---------------------------------------------------------
    Screen('FrameOval', win, white, CenterRectOnPoint([0 0 2*R 2*R], cx, cy), 3);
    Screen('DrawLines', win, tick, 2, white);
    Screen('DrawLine', win, white * 0.7, cx, cy, x, y, 2);
    Screen('DrawDots', win, [x; y], dotD, dotCol, [], 2);
    Screen('DrawDots', win, [cx; cy], 8, white, [], 2);

    if rate > 30 && abs(netRate) < rate / 4
        chat = '  (rest chatter: taps cancel out)';
    else
        chat = '';
    end
    txt = sprintf('%6.1f deg      steps %+d  (t %d, b %d)      turns %+d      %d taps/s%s', ...
        mod(ang, 360), steps, nT, nB, turns, rate, chat);
    DrawFormattedText(win, txt, 'center', rect(4) * 0.08, white);
    DrawFormattedText(win, 'Turn the dial.   t = clockwise, b = counter-clockwise.   SPACE = reset   ESC = quit', ...
        'center', rect(4) * 0.93, black);

    Screen('Flip', win);
end
end

function cleanupAll(oldSync)
try ListenChar(0);    catch, end
try KbQueueRelease(); catch, end
try ShowCursor;       catch, end
try sca;              catch, end
try Screen('Preference', 'SkipSyncTests', oldSync); catch, end
end

dial_probe: records every raw key event from the 905 while you turn one full turn each way, saves them to a CSV and reports counts, net steps and chatter. Use it when the dial seems to misbehave, and attach the CSV when asking for help.

dial_probe               % 15 s per turn, 10 s to walk to the dial

Using the dial in your experiment

Add experiments/psychtoolbox/dial_test to the MATLAB path (or copy the four dial_*.m functions into your experiment folder). Then the whole integration is four calls:

dial = dial_open();            % once, after opening the PTB window (360 steps/turn)

dial = dial_reset(dial);       % at the start of each trial: current position = 0

while ~done
    dial = dial_poll(dial);    % once per frame
    % dial.delta : steps since the previous frame (+ clockwise, - counter-clockwise)
    % dial.steps : net steps since dial_reset
    % dial.angle : dial.steps in degrees, 0..360
    % dial.otherKeys : any other keys pressed, e.g. any(dial.otherKeys == KbName('ESCAPE'))
    ...
    Screen('Flip', win);
end

dial_close(dial);              % once, at the end (also in your catch block)

Converting steps to a rating, a position or an angle is one line, for example a 0-100 scale where 200 steps (just over half a turn) span the whole scale:

rating = min(100, max(0, rating + 0.5 * dial.delta));

Things to keep in mind:

  • there is one keyboard queue per keyboard. dial_open takes the default one (all keyboards on Windows). If your experiment already uses KbQueueCreate on the default keyboard, read your own keys from dial.otherKeys instead, or call dial_open after releasing your queue;

  • the operator keyboard’s t and b keys count as dial steps too;

  • the dial has no button. To confirm a rating, use a response box (Experiments example 5: Response buttons experiment), a hold time, or a timeout;

  • dial_open suppresses keyboard input to the MATLAB console (ListenChar(-1)) and dial_close restores it.

The functions:

function dial = dial_open(stepsPerTurn)
% DIAL_OPEN  Start reading the Current Designs dial (HHSC-1x1-DIAL via FIU-905).
%
%   dial = dial_open()        % 360 steps per turn (1 degree per step)
%   dial = dial_open(400)     % if dial_dot_demo showed another number of steps per turn
%
% The FIU-905 interface shows up as a USB keyboard and types one key per step:
%   't' = one step clockwise        'b' = one step counter-clockwise
% dial_open starts a Psychtoolbox keyboard queue that collects these keys in
% the background, so no step is lost while your experiment draws a frame.
%
% Typical use in an experiment:
%
%   dial = dial_open();                 % once, after opening the PTB window
%   while ~done
%       dial = dial_poll(dial);         % once per frame
%       x = dial.angle;                 % 0..360 degrees, clockwise from start
%       ...draw something at x...
%       Screen('Flip', win);
%   end
%   dial_close(dial);                   % once, at the end
%
% Notes
%   * Call dial_open AFTER your own KbQueueCreate/KbQueueRelease calls, if any:
%     there is only one keyboard queue per keyboard, and dial_open takes the
%     default one. Other keys pressed meanwhile are returned by dial_poll in
%     dial.otherKeys, so you can still detect e.g. ESCAPE through the dial.
%   * The operator keyboard's 't' and 'b' keys also count as dial steps.
%   * The 905 sets its optical gain when its USB cable is plugged in: attach
%     the dial first, then plug the USB in WHILE SOMEONE TURNS THE DIAL.
%     See the lab documentation page "Current Designs dial".

if nargin < 1 || isempty(stepsPerTurn), stepsPerTurn = 360; end

KbName('UnifyKeyNames');

dial.stepsPerTurn = stepsPerTurn;
dial.keyT  = KbName('t');       % clockwise step
dial.keyB  = KbName('b');       % counter-clockwise step
dial.steps = 0;                 % net steps since dial_open / dial_reset (+ = clockwise)
dial.delta = 0;                 % steps since the previous dial_poll
dial.angle = 0;                 % dial.steps in degrees, wrapped to 0..360
dial.nT    = 0;                 % total clockwise taps
dial.nB    = 0;                 % total counter-clockwise taps
dial.lastTapTime = NaN;         % GetSecs time of the last step
dial.otherKeys   = [];          % keycodes of non-dial keys pressed since last poll
dial.isOpen = true;

KbQueueCreate();                % default keyboard = all keyboards on Windows
KbQueueStart();
KbQueueFlush([], 3);            % discard anything already waiting
try
    ListenChar(-1);             % keep the dial's taps out of the MATLAB console
catch
end
end
function dial = dial_poll(dial)
% DIAL_POLL  Read the new dial steps since the last call. Call once per frame.
%
%   dial = dial_poll(dial);
%
% Updates these fields of the struct returned by dial_open:
%   dial.delta        steps since the previous dial_poll (+ clockwise, - counter-clockwise)
%   dial.steps        net steps since dial_open / dial_reset
%   dial.angle        dial.steps converted to degrees, wrapped to 0..360
%   dial.lastTapTime  GetSecs time of the most recent step (NaN if none yet)
%   dial.otherKeys    keycodes of any other keys pressed since the last poll,
%                     e.g. any(dial.otherKeys == KbName('ESCAPE'))
%
% Rest chatter: when the dial sits exactly on an encoder edge the 905 can send
% alternating t b t b ... taps at over 100 per second. They cancel out in
% dial.steps, so the position does not drift; only dial.delta may jitter by +-1.

dial.delta = 0;
dial.otherKeys = [];

while KbEventAvail() > 0
    ev = KbEventGet();
    if ~ev.Pressed, continue; end           % the 905 taps keys: only count presses
    if ev.Keycode == dial.keyT
        dial.delta = dial.delta + 1;
        dial.nT = dial.nT + 1;
        dial.lastTapTime = ev.Time;
    elseif ev.Keycode == dial.keyB
        dial.delta = dial.delta - 1;
        dial.nB = dial.nB + 1;
        dial.lastTapTime = ev.Time;
    else
        dial.otherKeys(end+1) = ev.Keycode; %#ok<AGROW>
    end
end

dial.steps = dial.steps + dial.delta;
dial.angle = mod(360 * dial.steps / dial.stepsPerTurn, 360);
end
function dial = dial_reset(dial)
% DIAL_RESET  Set the current dial position as zero (angle 0, steps 0).
%
%   dial = dial_reset(dial);
%
% Use it at the start of every trial, so dial.angle / dial.steps measure the
% rotation made during that trial. Pending taps are discarded.

KbQueueFlush([], 3);
dial.steps = 0;
dial.delta = 0;
dial.angle = 0;
dial.otherKeys = [];
end
function dial_close(dial)
% DIAL_CLOSE  Stop reading the dial and release the keyboard queue.
%
%   dial_close(dial);
%
% Always call it at the end of the experiment (also in your catch block), so
% the keyboard queue and the MATLAB console are restored.

try KbQueueRelease(); catch, end
try ListenChar(0);    catch, end
if nargin > 0 && isstruct(dial)
    dial.isOpen = false; %#ok<NASGU>
end
end

Complete example: a rating task

dial_example_rating shows a 0-100 scale with a marker driven by the dial. A trial ends when the marker has not moved for 2 s (or after 15 s), and the rating, the time of the first movement and the dial steps are returned. The lines marked COPY are the ones to take into your own task.

results = dial_example_rating(3)   % three trials
function results = dial_example_rating(nTrials, screenNum)
% DIAL_EXAMPLE_RATING  Minimal rating task driven by the Current Designs dial.
%
% Each trial shows a horizontal scale from 0 to 100 with a marker. Turning the
% dial clockwise moves the marker right, counter-clockwise moves it left. The
% trial ends when the marker has not moved for 'holdSec' seconds, or at
% 'maxSec'. The rating, the reaction time and the dial steps are returned.
%
%   results = dial_example_rating()          % 3 trials, last screen
%   results = dial_example_rating(5, 1)      % 5 trials on screen 1
%
% Operator keys: ESCAPE aborts. Everything you need to reuse is marked
% "COPY" below: the dial calls and the step-to-rating conversion.
%
% Replace the "no movement for holdSec" rule by a button-box press if your
% task has a confirm button (see getButtonColor in experiments/psychtoolbox/general).

if nargin < 1 || isempty(nTrials),   nTrials = 3; end
if nargin < 2 || isempty(screenNum), screenNum = max(Screen('Screens')); end

% ---- settings you will want to change ----------------------------------
unitsPerStep = 0.5;     % rating units per dial step (1 step = 1 degree): 200 steps = full scale
holdSec      = 2.0;     % trial ends after this long without dial movement
maxSec       = 15;      % hard limit per trial
startRating  = 50;      % marker position at trial start
questions = {'How pleasant was the image?', 'How loud was the sound?', 'How confident are you?'};

% ---- window ---------------------------------------------------------------
oldSync = Screen('Preference', 'SkipSyncTests', 1);   % demo only
PsychDefaultSetup(2);
KbName('UnifyKeyNames');
keyEsc = KbName('ESCAPE');

dial = [];
cleanup = onCleanup(@() cleanupAll(oldSync)); %#ok<NASGU>

[win, rect] = PsychImaging('OpenWindow', screenNum, 0.5);
[cx, cy] = RectCenter(rect);
Screen('TextSize', win, 32);
HideCursor(win);

scaleW = 0.6 * rect(3);                 % scale width in px
x0 = cx - scaleW / 2; x1 = cx + scaleW / 2;

% ---- COPY: open the dial once -------------------------------------------
dial = dial_open();                     % 360 steps per turn

results = struct('trial', {}, 'rating', {}, 'rt', {}, 'steps', {}, 'aborted', {});

for trial = 1:nTrials
    question = questions{mod(trial - 1, numel(questions)) + 1};

    % ---- COPY: zero the dial at the start of the trial ----------------
    dial = dial_reset(dial);
    rating  = startRating;
    tStart  = Screen('Flip', win);
    tMoved  = NaN;                      % time of the first dial movement
    tLast   = tStart;                   % time of the last dial movement
    aborted = false;

    while true
        % ---- COPY: read the dial, convert steps to a rating ----------
        dial = dial_poll(dial);
        if dial.delta ~= 0
            rating = min(100, max(0, rating + unitsPerStep * dial.delta));
            tLast  = GetSecs;
            if isnan(tMoved), tMoved = tLast; end
        end
        if any(dial.otherKeys == keyEsc), aborted = true; break; end

        % ---- end-of-trial rules ------------------------------------
        tNow = GetSecs;
        if ~isnan(tMoved) && tNow - tLast > holdSec, break; end
        if tNow - tStart > maxSec, break; end

        % ---- draw the scale ----------------------------------------
        DrawFormattedText(win, question, 'center', cy - 150, [1 1 1]);
        Screen('DrawLine', win, [1 1 1], x0, cy, x1, cy, 4);
        for v = 0:25:100
            xv = x0 + scaleW * v / 100;
            Screen('DrawLine', win, [1 1 1], xv, cy - 15, xv, cy + 15, 2);
            DrawFormattedText(win, sprintf('%d', v), xv - 20, cy + 50, [1 1 1]);
        end
        xm = x0 + scaleW * rating / 100;
        Screen('FillOval', win, [1 0.85 0.2], CenterRectOnPoint([0 0 30 30], xm, cy));
        DrawFormattedText(win, sprintf('%.0f', rating), 'center', cy - 70, [1 0.85 0.2]);
        Screen('Flip', win);
    end

    results(end+1) = struct('trial', trial, 'rating', rating, 'rt', tMoved - tStart, ...
                            'steps', dial.steps, 'aborted', aborted); %#ok<AGROW>
    fprintf('Trial %d: rating %.0f, first movement after %.2f s, %+d dial steps\n', ...
        trial, rating, tMoved - tStart, dial.steps);
    if aborted, break; end

    DrawFormattedText(win, sprintf('Recorded: %.0f', rating), 'center', 'center', [1 1 1]);
    Screen('Flip', win);
    WaitSecs(1);
end

% ---- COPY: close the dial at the end (cleanupAll also does it) -----------
dial_close(dial);
end

function cleanupAll(oldSync)
try dial_close(); catch, end
try ShowCursor;   catch, end
try sca;          catch, end
try Screen('Preference', 'SkipSyncTests', oldSync); catch, end
end