0

在此处输入图像描述!我正在使用 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 传递给相应的参数。我想知道如何使用 TIMER 对象和回调来提取 [hrs mins secs] 的信息,这样我就可以在时钟滴答时实时计算各个点坐标。

4

1 回答 1

6

我会在这里做几件事。

首先,如果您正在显示当前时间,您可能真的不需要传递h, m,输入。s将此添加到函数的顶部以自动设置这些变量。

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);

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

set(gcf,'DeleteFcn',@(~,~)stop(t));  %NOte:  Better to explicitly use a figure number, rather than gcf.
于 2013-07-31T21:17:05.843 回答