Microchip PIC18F Timer2 程式是利用 PIC18F4550 內的計時器 2 的 TMR2 和 PR2 及中斷來實現,程式開始是設定計時器 PR2=195 (10ms) 及中斷旗號,程式便進入循環。當時鐘上升,計時器 2 TMR2 加一直至等於 195 (PR2) 便會觸發中斷,中斷副程式將 TimeCount 加一,當 TimeCount 小於 100 LED 不閃動,但 TimeCount 大於 100 及小於 200,LED 便會閃動,大於 200 便會重置 TimeCount,完成中斷副程式後,返回程式繼續循環。
▲ Timer2 流程圖 |
//***** Vector Remapping ************************************************* #pragma interrupt high_isr #pragma code high_vector = 0x08 void high_interrupt (void) { _asm goto high_isr _endasm } #pragma code //***** END Vector Remapping ******************************************** /************************************************************************* /************************************************************************* * Function: void main(void) * * PreCondition: None * Input: None * Output: None * Side Effects: None * Overview: Main program entry point. * Note: None ************************************************************************/ void main (void) { TRISA = 0x00; // Port A As Output // Set Timer2 OpenTimer2 ( TIMER_INT_ON & // Interrupt: ON T2_PS_1_16 & // Prescaler 1:1/4/16 T2_POST_1_16 // Postscaler 1:1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16 ); PR2=195; // PR2 = 195 count RCONbits.IPEN = 0; // Interrupt Priority Control: OFF // (RCON register IPEN bit = 0) PIE1bits.TMR2IE = 1; // Timer2 interrupt enable INTCONbits.PEIE = 1; // peripheral interrupt enable // INTCON register bit b6: low interrupt enable / disable // (When interrupt priority control) INTCONbits.GIE = 1; // all interrupt enable // INTCON register bit b7: high interrupt enable / disable // (When interrupt priority control) while (1) // wait for interrupt doing nothing { } } void high_isr (void) { PIR1bits.TMR2IF = 0; // Timer2 interrupt flag to 0 PR2=195; // 0.05μsec × 4 × 16 × 16 x 195 = 10000μsec = 10msec // (FOSC = HS at the system clock 20MHz=0.05us) // TMR2 = PR2 interrupt occurs TimeCount ++; // 10msec for each increment if (TimeCount <100) // count of 100 or less (1000msec = 10msec × 100) { LATAbits.LATA0 = 0; //RA0 = 0 LED: OFF Scope=0 } else if (TimeCount <200) // count from 100 to 200 (2000msec = 10msec × 100) { LATAbits.LATA0 = 1; // RA0 = 1 LED: ON Scope=1 } else TimeCount = 0; // Reset count = 0 } |
2011 年 03 月 07 日 天氣報告
氣溫:15.9 度 @ 23:00
相對濕度:百分之90%
天氣:微雨
沒有留言:
張貼留言