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

Timer/Counter1 (ATmega168)

Last-modified: 2012-08-20 (Mon) 00:29:31 (2160d)
Top / Timer / Counter1 (ATmega168)

Timer1Test

Timer/Counter1のオーバーフロー割り込みを使って、20ms周期のパルスを生成したサンプルプログラム。Timer/Counter0が8ビットであるのに対し、Timer/Counter1は16ビットであるので、TCNT1_InitValが(65536-80)になっている。その他は同じ。

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

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

#define TCNT1_InitVal   (65536-80)  // 10ms (128usX80=10.24ms)

//-----------------------------------------------------------------------------
//  Initialize Timer/Counter1
//-----------------------------------------------------------------------------
void init_Timer1()
{
    TCCR1B = 0x00;  // Stop Timer/Counter1
    TCNT1 = TCNT1_InitVal;  // Initial Value of Timer/Counter1
    TIMSK1 = _BV(TOIE1);    // Timer/Counter1 Overflow Interrupt Enable
    TCCR1B = 0x05;  // Start Timer/Counter1 clk/1024 125nsX1024=128us
}

//-----------------------------------------------------------------------------
//  Timer/Counter1 Overflow Handler
//-----------------------------------------------------------------------------
ISR(TIMER1_OVF_vect)
{
    TCNT1 = TCNT1_InitVal;  // Clear Timer/Counter1

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

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

    init_Timer1();  // Initialize Timer/Counter1
    sei();          // Interrupt Enable

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

    return 0;
}

Attach file: fileTimer1Test.c 878 download [Information]