setting a timer Matlab

3 次查看(过去 30 天)
Madison Gladstone
Trying to start a timer when a button is pushed and stop the timer when the button is pushed again and store the times everytime any of the four buttons are pushed. I tried reading on the Matlab help page on how to make a timer but got lost. This is the code I have right now but the times in the command window are all over the place and are not stored when the button is turned off. Any help would be appreciated! Thanks
a = arduino; %register Arduino Uno
t = timer('StartFcn',@(~,~)disp('timer started.'),'TimerFcn',@(~,~)disp(rand(1)));
while 1==1 %make code continuous
pin1 = readDigitalPin (a, 'D2'); %continuously read button 1
pin2 = readDigitalPin (a, 'D4'); %continuously read button 2
pin3 = readDigitalPin (a, 'D6'); %continuously read button 3
pin4 = readDigitalPin (a, 'D8'); %continuously read button 4
if pin1==1 %if button 1 is pushed
start(t);
writeDigitalPin(a, 'D10', 1); %turn on RGB LED to green
else %when button 1 is pushed again
stop(t);
writeDigitalPin(a, 'D10', 0); %RGB LED turns off
end
if pin2==1 %if button 2 is pushed
start(t);
writeDigitalPin(a, 'D13', 1); %turn on yellow LED
else %when button 2 is pushed again
stop(t);
writeDigitalPin(a, 'D13', 0); %LED turns off
end
if pin3==1 %if button 3 is pushed
start(t);
writeDigitalPin(a, 'D12', 1); %turn on red LED
else %when button 3 is pushed again
stop(t);
writeDigitalPin(a, 'D12', 0); %LED turns off
end
if pin4==1 %if button 4 is pushed
start(t);
writeDigitalPin(a, 'D11', 1); %turn on RGB LED to blue
else %when button 4 is pushed again
stop(t);
writeDigitalPin(a, 'D11', 0); %RGB LED turns off
end
end
  8 个评论
Madison Gladstone
Nevermind Tommy I got it all figured out!!! Thank you so much for the help!
Steven Lord
Steven Lord 2020-4-9
I'm guessing that your actual application for which you want to use this technique isn't to display random numbers when a button is depressed. Can you say a little more about the actual application? It's possible that the functionality to achieve your main goal already exists and doesn't require a timer.
For example, if you wanted to record for how long the button remained depressed, instead of using a timer I would store the current time (returned by datetime('now') as a datetime array) when the button is pressed and subtract the stored time from the current time when the button is released.
rightNow = datetime('now');
pause % wait for the user to end the pause
howlong = datetime('now')-rightNow;
disp("MATLAB was paused for " + seconds(howlong) + " seconds." + newline)

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by