Blink LED at specify time with Matlab - Arduino

Hi, I want to turn on LED for a given time such as 2 minutes and then it will turn off by using Matlab with Arduino hardware. I already search how to code it but I have no idea how to do it. The code below is my trial.
time = str2num(get(handles.edit3,'String'));
S = seconds(time);
if S > 0
writeDigitalPin(a, 'D13',1);
else
writeDigitalPin(a, 'D13', 0);
end

2 Comments

@melisa: Please mention, how this question is related to Matlab. How is the LED connected to Matlab? Without knowing this detail, an answer would required to guess.
hi, thank you for replying and sorry for my mistake. I already edit my question.

Sign in to comment.

 Accepted Answer

Jan
Jan on 4 Feb 2018
Edited: Jan on 4 Feb 2018
time = str2num(get(handles.edit3,'String'));
% S = seconds(time); % [EDITED] Not needed
writeDigitalPin(a, 'D13', 1);
pause(time); % [EDITED] assumed, that edit3 contains the seconds
writeDigitalPin(a, 'D13', 0);
Or with a timer, which does not block Matlab:
TimerH = timer('TimerFcn', {TimerCB, 'off', a}, ...
'StartDelay', time, ... % [EDITED] S -> time
'ExecutionMode', 'SingleShot', ...
'StartFcn', {TimerCB, 'on', a});
start(TimerH);
which calls the Timer callback function at starting and stopping:
function TimerCB(TimerH, EventData, Cmd, a)
switch Cmd
case 'on'
writeDigitalPin(a, 'D13', 1);
case 'off'
writeDigitalPin(a, 'D13', 0);
end
end

7 Comments

Note: on MS Windows, pause() has a resolution of 0.01 seconds. On OS-X and Linux the resolution is finer grained (but a bit complicated on OS-X.)
I got an error for pause(S). Why is it?
Jan probably overlooked (as did I) that seconds() returns a duration object, and that you cannot pass a duration object to pause(). You would
pause(time)
instead -- presuming that time is a variable holding the length of time to keep the LED lit.
oo..okay, now I learn something from you guys. Thank you so much for helping me.
@melissa: Whenever you mention in the forum, that you get an error, post a copy of the complete error message. This helps to understand what's going on.
okay, I will take note. Thank you
thank you very much it's work

Sign in to comment.

More Answers (1)

You can use tic and toc for this. When you run tic it starts a stopwatch style timer, you can then use toc to know the elapsed time and use a while loop to check if it is still less than your desired elapsed time.

2 Comments

timelimit = 2*60;
writeDigitalPin(a, 'D13',1);
start = tic;
while toc(start) < timelimit
pause(0.01); %do _something_, even if just a useless computation
end
writeDigitalPin(a, 'D13', 0);

Sign in to comment.

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Asked:

on 1 Feb 2018

Commented:

on 10 Mar 2021

Community Treasure Hunt

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

Start Hunting!