Front page   Edit Freeze Diff Backup Upload Copy Rename Reload   New List of pages Search Recent changes   Help   RSS of recent changes

Timer/Counter2 (ATmega168)

Last-modified: 2012-08-20 (Mon) 00:29:30 (1981d)
Top / Timer / Counter2 (ATmega168)

Timer2Test

Timer/Counter2のオーバーフロー割り込みを使って、20ms周期のパルスを生成したサンプルプログラム。Timer/Counter0の場合と同じ。

//-----------------------------------------------------------------------------
//  ATmega168
//  Internal 8 MHz RC Osc.
//  (1/8M = 125 ns)
//-----------------------------------------------------------------------------

#include <avr/io.h>
#include <avr/interrupt.h>

#define TCNT2_InitVal   (256-80)    // 10ms (128usX80=10.24ms)

//-----------------------------------------------------------------------------
//  Initialize Timer/Counter2
//-----------------------------------------------------------------------------
void init_Timer2()
{
    TCCR2B = 0x00;          // Stop Timer/Counter2
    TCNT2 = TCNT2_InitVal;  // Initial Value of Timer/Counter2
    TIMSK2 = _BV(TOIE2);    // Timer/Counter2 Overflow Interrupt Enable
    TCCR2B = 0x07;          // Start Timer/Counter0 clk/1024 125nsX1024=128us
}

//-----------------------------------------------------------------------------
//  Timer/Counter2 Overflow Handler
//-----------------------------------------------------------------------------
ISR(TIMER2_OVF_vect)
{
    TCNT2 = TCNT2_InitVal;  // Clear Timer/Counter2

    PINB |= _BV(PB1);       // Invert PB1
}

//-----------------------------------------------------------------------------
//  Main
//-----------------------------------------------------------------------------
int main()
{
    DDRB  |= _BV(PB1);  // Set PB1 Output
    PORTB |= _BV(PB1);  // Set PB1 High

    init_Timer2();  // Initialize Timer/Counter2
    sei();          // Interrupt Enable

    while (1) {
        asm("sleep"::);
    }

    return 0;
}

Attach file: fileTimer2Test.c 796 download [Information]