新聞中心

        EEPW首頁 > 嵌入式系統 > 設計應用 > AVR單片機的TC0定時溢出例程

        AVR單片機的TC0定時溢出例程

        作者: 時間:2016-11-25 來源:網絡 收藏
        程序生成向導配置TC0,溢出中斷,產生1ms/20ms延時。

        定時公式:Time=PRE*(MAX-TCNT0+1)/F_cpu單位S ,其中,PRE為與分頻數

        本文引用地址:http://www.104case.com/article/201611/321461.htm

        #include
        #include
        void port_init(void)
        {
        PORTA = 0xFF;
        DDRA= 0x00;
        PORTB = 0xFF;
        DDRB= 0xFF;
        PORTC = 0xFF; //m103 output only
        DDRC= 0x00;
        PORTD = 0xFF;
        DDRD= 0x00;
        }
        //TIMER0 initialize - prescale:8/256
        // WGM: Normal
        // desired value: 1mSec/20ms
        // actual value:1.000mSec (0.0%)/19.968ms(0.16%)
        void timer0_init(void)
        {
        TCCR0 = 0x00; //stop
        //TCNT0 = 0x83; //set count T=PRE*(MAX-TCNT0+1)/F_cpu=8*(255-130)/1MHz=1ms
        TCNT0 = 0xB2; //set count T=PRE*(MAX-TCNT0+1)/F_cpu=256*(255-178+1)/1MHz=19.968ms
        OCR0= 0x7D;//set compare 程序中未使用
        //TCCR0 = 0x02; //start timer8分頻
        TCCR0 = 0x04; //start timer256分頻
        }
        #pragma interrupt_handler timer0_ovf_isr:iv_TIM0_OVF
        void timer0_ovf_isr(void)
        {
        //TCNT0 = 0x83; //reload counter value 重載TCNT0,使TC0重復從0x83-0xff計數
        TCNT0 = 0xB2; //reload counter value 重載TCNT0,使TC0重復從0xB2-0xff計數
        PORTB^=BIT(7)|BIT(6)|BIT(5);//翻轉PB6/PB7口,實現兩個LED燈的1ms間隔亮滅
        }
        //call this routine to initialize all peripherals
        void init_devices(void)
        {
        //stop errant interrupts until set up
        CLI(); //disable all interrupts
        port_init();
        timer0_init();
        MCUCR = 0x00;
        GICR= 0x00;
        TIMSK = 0x01; //timer interrupt sources
        SEI(); //re-enable interrupts
        //all peripherals are now initialized
        }
        //
        void main(void)
        {
        init_devices();
        //insert your functional code here...
        }




        評論


        技術專區

        關閉
        主站蜘蛛池模板: 东乌珠穆沁旗| 六枝特区| 颍上县| 大港区| 泊头市| 长海县| 大关县| 久治县| 开封市| 包头市| 莆田市| 云南省| 应城市| 勐海县| 石河子市| 介休市| 滨海县| 即墨市| 文成县| 公主岭市| 体育| 顺平县| 高邑县| 琼海市| 五指山市| 阳西县| 灵石县| 沾益县| 崇明县| 牟定县| 庄河市| 营山县| 五大连池市| 泾川县| 巴林右旗| 泉州市| 天柱县| 宜兴市| 信丰县| 富宁县| 扎鲁特旗|