how to detect a keyboard key in a while loop using a figure

22 Ansichten (letzte 30 Tage)
Ahsan Ayyaz
Ahsan Ayyaz am 7 Jul. 2020
Kommentiert: Paul am 1 Dez. 2025 um 6:51
I am using arduino nano and checking push buttons in a while loop. I want to detect a keyboard key, say 'spacebar' and simulate a push button. A figure with a push button is the desired output. Everytime the figure is in focus and the 'spacebar' is pressed on the keyboard, it should turn on and off a digital output of arduino board.
  1 Kommentar
Paul
Paul am 1 Dez. 2025 um 6:51
That’s an interesting setup, especially for anyone trying to build small reaction-based projects. I’ve been experimenting with space-press mechanics myself while messing around with a simple browser game at https://space-bar-clicker.github.io/, and timing intervals really make a difference. Adding a delay to emulate spacebar presses should work well if you trigger it with a timer inside the callback.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Tommy
Tommy am 8 Jul. 2020
You could use the figure's KeyPressFcn, possibly combined with some of the ideas below:
myFig = figure('KeyPressFcn', @myKeyPressFcn,...
'UserData', false);
a = 0;
while true
a = a + rand;
if myFig.UserData
close(myFig)
break
end
drawnow % <- important so that myKeyPressFcn() gets called when a key is pressed
end
disp(a)
function myKeyPressFcn(src, evt)
if strcmp(evt.Key, 'space')
src.UserData = true;
end
end
  2 Kommentare
Ahsan Ayyaz
Ahsan Ayyaz am 9 Jul. 2020
Hi Tommy
'waitforbuttonpress' worked for me.
Thanks for your reply.
Tommy
Tommy am 10 Jul. 2020
Glad to hear you got it working!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Desktop finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by