2016年8月19日 星期五

DIY - PIC24:PIC24FJ64GA008 Timer2 軟件時鐘程式(四十五)

DIY - PIC24PIC24FJ64GA008 Timer2 軟件時鐘程式(四十五): 

筆者利用 Microchip PIC24FJ64GA008 Timer2 B類型計時器是 16-bit Timer0 ~ 65535)製作軟件時鐘(Software Time Clock),軟件時鐘是會使用到中斷服務。軟件時鐘都是基於系統時鐘作基準,在計時器模式下,首先使用 PR2 寄存器設定的預設時間,預分頻器設置,然後啓動計時器,計時器的數值在每個指令週期都會遞增,當計時器的數值遞增至 PR2 寄存器預設數值,便會觸發中斷服務程式,中斷服務程式便會作時分秒處理,處理完成中斷服務程式,計時器便會重置,數值從新開始遞增。

PIC24FJ64GA008 Timer2 軟件時鐘顯示
PIC24FJ64GA008 Timer2 軟件時鐘比較
Timer2 配置: 
1TON 位置 1 = 1)。 
2 使用 TCKPS1:TCKPS0 位選擇計時器的預分頻比。 
3 使用 TCS TGATE 位元選擇時鐘和門控模式。 
4 TSYNC 位置 1 或清零分別配置為同步或非同步操作。 
5 將計時器的週期值裝載到 PR2 寄存器。 
6 如果需要中斷,將中斷允許位 T2IE 1。使用優先級 T2IP2:T2IP0 位設置中斷優先順序。

Microchip PIC24FJ64GA008 Timer2 初始化程式:
#include                    // timer.h
// Initialise Timer2  
timer2_isr();                                            // Interrupt Service Timer2
InitTimer2();                                           // Init Timer2

Microchip PIC24FJ64GA008 Timer2 中斷程式
// Timer2 Interrupt
void __attribute__((interrupt, no_auto_psv)) _T2Interrupt(void) {
           if(IFS0bits.T2IF == 1){ // Check the timer2 interrupt flag
                     timer2_isr();    // Jump to the timer2 interrupt funtio
IFS0bits.T2IF = 0;
}

Microchip PIC24FJ64GA008 Timer2 中斷服務程式
void timer2_isr(void){
           static int counter = 0; // A static variable is only initialized once and stays alive after the function ends.
                                             // It is like a global variable that exists only in this function.
           counter++;
           if(counter == 100){
                     counter = 0;
                     seconds++;
                     if(seconds == 60){
                                seconds = 0;
                                minutes++;
                     }
                     if(minutes == 60){
                                minutes = 0;
                                hours++;
                     }
                     if(hours == 24){
                                hours = 0;
                     }
           }
           IFS0bits.T2IF = 0; // Clear the interrupt flag.
                                                                 // If you forget this line, an interrupt wil occur again immediately
                                                                 // and your program will be stuck in the interrupt routine.
}        

PIC24FJ64GA008 Timer2 軟件時鐘程式執行
2016年 8月 19日 天氣報告
氣溫:26.8@ 20:50
相對濕度:百分之 94%
天氣:微雨

沒有留言:

張貼留言