在MATLAB中使用timer来提取系统时间

时间:2013-07-31 20:36:26

标签: matlab octave matlab-guide

enter image description here!我正在使用MATLAB设计一个模拟时钟。目前,我的代码只是用手(小时,分钟,秒)显示时钟设计(或者说情节),而不是勾选。这是我的代码:

function raviClock(h,m,s)
drawClockFace;


%TIMER begins-------
t = timer;
t.ExecutionMode = 'FixedSpacing';  %Use one of the repeating modes
t.Period = 1;                      %Fire on 1 second intervals
t.TimerFcn = @timer_setup;           %When fired, call this function
start(t);
set(gcf,'DeleteFcn',@(~,~)stop(t));
end

function timer_setup(varargin)

format shortg;
timenow = clock;
h = timenow(4);
m = timenow(5);
s = timenow(6);

% hour hand
hours= h + m/60 + s/3600;
hourAngle= 90 - hours*(360/12);

% compute coordinates for pointing end of hour hand and draw it
[xhour, yhour]= polar2xy(0.6, hourAngle);
plot([0 xhour], [0 yhour], 'k-','linewidth',7.4)

% minute hand
mins= m + s/60;
minsAngle= 90 - mins*(360/60);

% compute coordinates for pointing end of minute hand and draw it
[xmins, ymins]= polar2xy(0.75, minsAngle);
plot([0 xmins], [0 ymins], 'r-','linewidth',4)


%second's hand
second = s;
secAngle = 90- second*(360/60);

[xsec, ysec]= polar2xy(0.85, secAngle);
plot([0 xsec], [0 ysec], 'm:','linewidth',2)
%end   % while ends
end

%--------------------------------------------------------

function drawClockFace

%close all          
axis([-1.2 1.2 -1.2 1.2])  
axis square equal
hold on            


theta= 0;
for k= 0:59
    [xX,yY]= polar2xy(1.05,theta);
        plot(xX,yY,'k*')

        [x,y]= polar2xy(0.9,theta);
    if ( mod(k,5)==0 )  % hour mark
        plot(x,y,'<')
    else                % minute mark
        plot(x,y,'r*')
    end
    theta= theta + 360/60;
    end
end

%-----------------------------------------------------------------
function [x, y] = polar2xy(r,theta)

rads= theta*pi/180;  
x= r*cos(rads);
y= r*sin(rads);
end

当我最初调用我的函数时,这只是为HOUR,MINUTE和SECOND参数取值的静态数据。我尝试在while循环中使用以下内容,但它没有多大帮助

format shortg
c=clock
clockData = fix(c)
h = clockData(4)
m = clockData(5)
s = clockData(6)

并将h,m和s传递给相应的cuntions。我想知道如何使用TIMER obkjects和回调来提取[hrs mins secs]的信息,这样我就可以在时钟滴答时实时计算各自的坐标坐标。

1 个答案:

答案 0 :(得分:6)

我在这里做了几件事。

首先,如果您要显示当前时间,则可能不需要传递hms输入。将其添加到函数顶部以自动设置这些变量。

if nargin == 0
    [~,~,~,h,m,s] = datevec(now);
end

然后,使用时间定期调用此函数非常容易。这样的事情。

t = timer;
t.ExecutionMode = 'FixedSpacing';  %Use one of the repeating modes
t.Period = 1;                      %Fire on 1 second intervals
t.TimerFcn = @(~,~)raviClock;      %When fired, call this function (ignoring 2 inputs)
start(t);                          %GO!

使用docsearch timer深入记录计时器对象。但上面的代码应该让你开始。

要停止计时器,请运行

stop(t);

要在窗口关闭时停止计时器,请将stop命令放入窗口删除回调:

set(gcf,'DeleteFcn',@(~,~)stop(t));  %NOte:  Better to explicitly use a figure number, rather than gcf.