jenswilly.dk


Timers

Here is a link to an excellent tutorial about timers: Newbie's Guide to AVR Timers (also available as PDF here: Newbie's Guide to AVR Timers PDF.

After reading that tutorial, understanding the following ATmega168 code should pose no problems whatsoever:

// OC1A pin is automatically toggled due to the COM1A0 setting on TCCR1A
// B0 pin is toggled by way of compare A match interrupt

int main(void)
{
    // setup
    DDRB |= _BV( PB1 ) | _BV( PB0 );   // B1 (OC1A, pin 15, Arduino pin DIG9) and B0 (pin 14, Arduino DIG8) -> output
    PORTB |= _BV( PB0 );               // B0 HIGH
    PORTB &= ~_BV( PB1 );              // B1 LOW
    TCCR1B = 0;                        // stop timer1 by shutting off the clock - just to be sure
    TCNT1 = 0;                         // force count to start from scratch - just to be sure

    // configure timer1
    TCCR1A = _BV( COM1A0 );            // toggle OC1A on compare match
    OCR1A = 62499;                     // compare value for 1 Hz: val = F_CPU/prescaler/target freq. - 1: 16000000/256/1 - 1
    TIMSK1 |= _BV( OCIE1A );           // enable interrupt for timer1 output compare A match

    // start timer
    sei();                               // enable interrupts
    TCCR1B = _BV( WGM12 ) | _BV( CS12 ); // start timer1: waveform generation mode = 4 (TOP=OCR1A), clock source = system clock w/ prescaler 256

    // loop
    while( 1 )
        ;

    return 0;
}

ISR( TIMER1_COMPA_vect )
{
    PINB |= _BV( PB0 );   // toggle port B0 by writing a HIGH to the input bit of an output pin
}

Leave a Reply