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

Timer/Counter0 (ATtiny26)

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

Timer0Test

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

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

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

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

volatile unsigned char flag = 0;

//-----------------------------------------------------------------------------
//  Timer/Counter0 Initialization
//-----------------------------------------------------------------------------
void init_timer0()
{
    TCCR0 = 0x00;       // Stop Timer/Counter0
    TCNT0 = INIT_VAL;   // initial value
    TIMSK = _BV(TOIE0); // Overflow Interrupt Enable
    TCCR0 = 0x05;        // Start Timer/Counter0 clk/1024 125nsX1024=128us
}

//-----------------------------------------------------------------------------
//  Timer/Counter0 Overflow Handler
//-----------------------------------------------------------------------------
ISR(TIMER0_OVF0_vect)
{
    TCNT0 = INIT_VAL;  // Clear Time/Counter0

    if (flag) PORTA |= _BV(PA0);
    else PORTA &= ~_BV(PA0);

    flag = ~flag;
}

//-----------------------------------------------------------------------------
//	Main
//-----------------------------------------------------------------------------
int main()
{
    DDRA  |= _BV(PA0);
    PORTA |= _BV(PA0);

    init_timer0();
    sei();

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

    return 0;
}