2013-07-31 32 views
0

enter image description here!我使用MATLAB來設計模擬時鐘。目前,我的代碼只是用手(小時,分鐘,秒)顯示(或繪製)時鐘設計,並且不打勾。這裏是我的代碼:在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 

這是採取簡單的靜態值數據,小時,分鐘和第二個參數時,我開始打電話給我的功能。我試着用下面的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]的信息,因此我可以在時鐘滴答時實時計算相應的點座標。

回答

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. 
+0

這看起來不錯。但是當圖表窗口關閉時,有沒有辦法停止計時器?我想如果我不停止計時器,我可能會一遍又一遍地得到圖表。 – noobcoder

+0

查看修改。 <字符數限制> – Pursuit

+0

它確實給了我當前的時間,但我在MATLAB中得到一個奇怪的消息,作爲 '「在評估定時器'timer-18'的TimerFcn時出錯'。'輸入參數太多''' 它只給我當前時間,並給出錯誤,我如何穩定地捕捉時間每秒,所以我可以回調我的函數每秒更改圖形?請注意,當我調用函數 – noobcoder