Timer/Counter0 (ATmega168)
Last-modified: 2012-08-20 (Mon) 00:29:30 (2374d)
Timer0Test †
Timer/Counter0のオーバーフロー割り込みを使って、20ms周期のパルスを生成したサンプルプログラム。
//----------------------------------------------------------------------------- // ATmega168 // Internal 8 MHz RC Osc. // (1/8M = 125 ns) //----------------------------------------------------------------------------- #include <avr/io.h> #include <avr/interrupt.h> #define TCNT0_InitVal (256-80) // 10ms (128usX80=10.24ms) //----------------------------------------------------------------------------- // Timer/Counter0 Initialization //----------------------------------------------------------------------------- void initTimer0() { TCCR0B = 0x00; // Stop Timer/Counter0 TCNT0 = TCNT0_InitVal; // Initial Value of Timer/Counter0 TIMSK0 = _BV(TOIE0); // Timer/Counter0 Overflow Interrupt Enable TCCR0B = 0x05; // Start Timer/Counter0 clk/1024 125nsX1024=128us } //----------------------------------------------------------------------------- // Timer/Counter0 Overflow Handler //----------------------------------------------------------------------------- ISR(TIMER0_OVF_vect) { TCNT0 = TCNT0_InitVal; // Clear Time/Counter0 PINB |= _BV(PB1); // Invert PB1 } //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- int main() { DDRB |= _BV(PB1); // Set PB1 Output PORTB |= _BV(PB1); // Set PB1 High initTimer0(); // Initialize Timer/Counter0 sei(); // Interrupt Enable while (1) { asm("sleep"::); } return 0; }
Wait10usTest †
Timer/Counter0を使って、分解能10usのタイマー関数を実現したサンプルプログラム。
//----------------------------------------------------------------------------- // ATmega168 // Internal 8 MHz Osc. // (1/8M = 125 ns) //----------------------------------------------------------------------------- #include <avr/io.h> //----------------------------------------------------------------------------- // wait 10 us using Timer/Counter0 //----------------------------------------------------------------------------- void wait10us(int times) { int count; TCCR0B = 0x02; // Start Timer/Counter0 clk/8 125nsX8 = 1us TCNT0 = 0x00; // Clear Counter // wait timesX10us for (count = 0; count < times; count++) { while( TCNT0 < 10 ); // 1usX10 = 10us TCNT0 = 0x00; } } //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- int main() { DDRB |= _BV(PB1); // Set PB1 Output PORTB |= _BV(PB1); // Set PB1 High while (1) { wait10us(100); // wait 1ms PINB |= _BV(PB1); // invert PB1 } }
Attach file:


