Skip to content
Snippets Groups Projects
timer_1.ino 880 B
Newer Older
  • Learn to ignore specific revisions
  • Markus Scheck's avatar
    Markus Scheck committed
    // This module uses TIMER1 to keep track of time
    
    #include "timer_1.h"
    #include <avr/interrupt.h>
    
    uint32_t overflow_count;
    
    #define TIMER_MASK (1<<CS10)
    
    inline void timer_init(void) {
      // enable overflow interrupt
      TIMSK1 |= (1<<TOIE1);
    }
    
    inline void timer_start(void) {
      //disable interrupts globally
      cli();
      //clear out timer counting register
      TCNT1 = 0;
      //clear overflow count
      overflow_count = 0;
      // set up clock source
      // we have a 16MHz Clock
      // and a 16 Bit timer
      // Use a prescaler of 256 -> 16/256 = 62.5kHz
      TCCR1B |= TIMER_MASK;
      //enable interrupts
      sei();
      
    }
    
    inline uint32_t timer_ticks(void) {
      return TCNT1 ^ (overflow_count << 16);
    }
    
    inline uint32_t timer_stop(void) {
      // stop timer clock
      TCCR1B &= ~(TIMER_MASK);
      return timer_ticks();
    }
    
    ISR(TIMER1_OVF_vect) {
      overflow_count++;
    }