2011年3月13日 星期日

DIY - PIC: PIC18F4550 Software Clock 程式 (三十五)

DIY - PIC PIC18F4550 Software Clock 程式 (三十五)

利用 PIC18F4550 內的 Timer 功能,可以作為實時時鐘 (Real Time Clock) ,雖然軟體實時時鐘不及硬體實時時鐘準確,但是軟體實時時鐘是利用程式作為計算,所以是不用額外增加電子元件,減低成本。程式利用內置的 Timer2 TMR2 PR2作為基礎,設定 PR2 = 195,當 TMR2 增加至 PR2 的數值,便會觸發中斷,中斷副程式將會增加在時分秒的記憶數值,利用 LCD 作出顯示。程式利用時脈作為基本的時間值,所以要準確的計算出時脈總數是需要明白 PIC18F4550 內的時鐘工作原理  (參考 DIY - 電子: PIC18F4550 微控制器的時鐘結構 ( 廿十四 ))

Software Clock 流程圖
主程式:
void main(void)
{
    //               1234567890123456               
    char LCD_name[]=" BWS Clock 2011";
    int i;
    unsigned int timeout=0;
    char data;

    ADCON0 = 0x00;                         // Disable the AD converter
    ADCON1 = 0x0F;                         // Set all ports to digital
    TRISA = 0b00000000;                    // Setup PORTA as Output

    // Initialise LCD
     OpenXLCD(FOUR_BIT&LINES_5X7);        // Init the LCD Display
    while(BusyXLCD());
    WriteCmdXLCD(BLINK_OFF & CURSOR_OFF ); 
    while(BusyXLCD());    
    stdout = _H_USER;                    // Redirect I/O to LCD
    //Delay10KTCYx(24);                 // 10,000x24x1/12us = 20ms
    LcdSetLine1();                        // Put cursor on start of line 1
    putsXLCD(LCD_name);                    // Display text

    // Initialise Timer2   
    timer2_isr();
    InitTimer2();                        // Init Timer2

    while(1)
    {
           LATAbits.LATA0 = 0;                // RA0=0 LED=OFF Scope=50ms
        LcdSetLine2();                    // Put cursor on start of line 2
        //printf("Printf Testing");       // Printf text
        //Display time. %02i means display integer with 2 characters (04 instead of 4)
        printf("Time: %02i:%02i:%02i", hours, minutes, seconds);
       
        LATAbits.LATA0 = 1;                // RA0=1 LED=ON Scope=1
        Delay10KTCYx(10);                  // 10,000 x 10 x (4 x 0.05us) = 20ms
                                        // Scope = 20ms
    }
}
中繼程式:
void timer2_isr(void){
    static int counter = 0;
                           
    counter++;
    if(counter == 100){
        counter = 0;
        seconds++;
        if(seconds == 60){
            seconds = 0;
            minutes++;
        }
        if(minutes == 60){
            minutes = 0;
            hours++;
        }
        if(hours == 24){
            hours = 0;
        }
    }
    PIR1bits.TMR2IF = 0;
                       

}



PIC18F4550 Software Clock運行並顯示時間
2011 03 13 天氣報告
氣溫:20.6 @ 23:00 
相對濕度:百分之88% 
天氣:天色大致良好 
※日本調升地震強度至九級,又警告未來幾日還會有餘震,強度預測大約七級,可能引發海嘯。將2011 03 11 (星期五) 發生的大地震震級為由八點九級調升至九級,是一九零零年以來全球第五強震,也是日本自二三年官方測定地震震級以來最強烈一次地震。

沒有留言:

張貼留言