2012-12-19 13 views
0

該代碼片段針對Atmega8編寫,取自clapper circuit using Atmega8。任何人都可以將這個代碼片段轉換爲Atmega16並附上一點解釋。由於我正在嘗試爲Atmega16實現相同的功能,並且在計時器部件上遇到了一些麻煩。將Atmega8的計時器代碼實現爲Atmega16

#define BURST_TIME 70 
#define READY_TIME 150 
#define TIME_OUT 300 

void timer_init() 
{ 
    TIFR |= (1<<TOV0);  
    //set interrupt on overflow 
    TIMSK |= (1<<TOIE0); 
    TCNT0 = 223; 
} 

ISR (TIMER0_OVF_vect) 
{  
    TCNT0 = 223; 
    timer++; 

    if (timer == BURST_TIME) 
    { 
     burst = 1; 
     ready = 0; 
    } else if (timer == READY_TIME) 
    { 
     burst = 0; 
     ready = 1; 
    } else if (timer == TIME_OUT) 
    { 
     timer = 0; 
     burst = 0; 
     ready = 0; 
     first = 0; 
     stop_timer(); 
    } 
} 

void start_timer() 
{ 
    TCCR0 |= (1<<CS02); 
} 

void stop_timer() 
{ 
    TCCR0 &= ~(1<<CS02); 
} 

回答

2

嘗試使用Atmel的數據表的芯片和比較定時器寄存器,你會發現所有你所需要的

的Atmega8:http://www.atmel.com/images/doc2486.pdf 有用:註冊摘要頁280

Atmega16的:http://www.atmel.com/Images/doc2466.pdf 有用的功能:寄存器彙總Page 331

你想要使用定時器0,即一個8位定時器(第71頁Atmega16)

現在讓我們嘗試分析一下代碼

TIFR |= (1<<TOV0); // TIFR Thats the Timer/Counter0 Interrupt Flag Register 
        // TOV0: Timer/Counter0 Overflow Flag 
        // The bit TOV0 is set when an overflow occurs in Timer/Counter0. 
        // Datasheet page: 86 

TIMSK |= (1<<TOIE0); // Timer/Counter Interrupt Mask Register 
         // TOIE0: Timer/Counter0 Overflow Interrupt Enable 
         // When the TOIE0 bit is written to one, and the I-bit in the `status Register is set, the 
         // Timer/Counter0 Overflow interrupt is enabled 

TCNT0 = 223; // TCNT0: 0 to 255 or 0x00 to 0xFF 
      // with each clock it increases by 1 
      // when the register hits 255, a Timer-Overflow is triggerd (ISR...) 
      // The flag can be queried or used to trigger an interrupt. 
      // Datasheet Page 85 

TCCR0 |= (1<<CS02); // TCCR0: Timer/Counter Control Register 
        // CS02: Bit 2:0 – CS02:0: Clock Select 
        // This means that your running the Timer with a        
        // Prescaler of 256 (CPU frequency/256) 
        // This line starts the Timer! 
        // Datasheet Page: 85 

ISR (TIMER0_OVF_vect) // will be executed when a overflow is triggerd 
{ 
    // Do something 
    // Keep the execution time short in this section 
}