How to deal with timing error when using Timer Function?

Hi everyone,
I am currently writing a code using Timer function to record mouse path with 1kHz rate (i.e. I want to record the position of the mouse every 0.001s). I discovered that the Timer function does not have the precision under 50ms. I also found that the matlab time outputs did not add up to the total trial running time (i.e. if I add up the time tracked by the Timer function, the value is always less than the actual running time of the mouse path). I think if the error in timing comes from the accumulation of excution time of the Timer function, in theory the value should be greater than the actual running time. I am hoping if anyone could take a look at my code and give me some suggestion, and am also wondering if people have encountered similar issue. The following is the Timer Function that I used:
timerObj = timer('TimerFcn', @recordMousePos, 'Period', 0.001, 'ExecutionMode', 'fixedRate');
Thank you!

回答 (1 件)

Ninad
Ninad 2024 年 7 月 4 日

0 投票

Hi Sicheng,
You can use the "get" MATLAB function to achieve your goal. This MATLAB function retrieves the current position of the mouse pointer (cursor) on the screen.
In the following command:
loc = get(0, 'PointerLocation');
  • The first argument (0) refers to the root object (the entire screen), and the second argument ('PointerLocation') specifies the property we want to retrieve.
  • The property 'PointerLocation' returns a 2-element vector [x, y], where x and y represent the horizontal and vertical coordinates of the mouse pointer, respectively.
I have written a dummy code where you can use the get function to track the cursor on the screen:
flag = 0;
while true
loc = get(0, 'PointerLocation');
if (flag==0)
prev_locx = loc(1);
prev_locy = loc(2);
flag=1;
end
new_locx = loc(1);
new_locy = loc(2);
if (new_locy~=prev_locy) || (new_locx~=prev_locx)
fprintf('Mouse position: X = %d, Y = %d\n', loc(1), loc(2));
prev_locx = new_locx;
prev_locy = new_locy;
end
pause(0.001); % Pause for 1 ms (adjust as needed)
end
Please go through the following MathWorks documentation to know more about the "get" function:
Regards,
Ninad

1 件のコメント

sicheng
sicheng 2024 年 7 月 5 日
Thank you for your reply.
However, I have tried other methods before, such as using tictoc to accurately time 1ms while recording events, but they didn't work. I am actually a little skeptical about whether errors in such a small time scale are inevitable, because as long as the program is called, these errors will exist.
“tic;
period = 0.001; % 1ms
while ishandle(fig) && cyclesCompleted < maxCycles
if toc >= period
recordMousePos();
tic;
end
pause(0.001);
end”
Regards,
Sicheng

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2024 年 7 月 4 日

コメント済み:

2024 年 7 月 5 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by