
我正在用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这只是为最初调用函数时的小时、分钟和第二个参数获取值的静态数据。我尝试在much循环中使用下面的内容,但没有多大帮助
format shortg
c=clock
clockData = fix(c)
h = clockData(4)
m = clockData(5)
s = clockData(6)并将h,m和s传递给各自的楔形。我想知道如何使用计时器指令和回调来提取小时分钟秒的信息,以便在时钟滴答时实时计算各个点的协调。
发布于 2013-07-31 21:17:05
我会在这里做几件事。
首先,如果要显示当前时间,您可能实际上不需要传递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对timer对象进行深入的文档化。但是上面的代码会让你开始。
要停止计时器,请运行
stop(t);若要在窗口关闭时停止计时器,请将停止命令放入窗口删除回调中:
set(gcf,'DeleteFcn',@(~,~)stop(t)); %NOte: Better to explicitly use a figure number, rather than gcf.https://stackoverflow.com/questions/17980481
复制相似问题