Created
December 3, 2012 05:34
-
-
Save WickedDevice/4192970 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* timebase.c | |
* | |
* Created on: Dec 3, 2012 | |
* Author: vic | |
*/ | |
#include <inttypes.h> | |
#include <avr/io.h> | |
#include <avr/interrupt.h> | |
#include "timebase.h" | |
// double buffered timestamp | |
volatile uint32_t timestamp_ms_buf[2] = {0, 1}; | |
volatile uint8_t timestamp_ms_buf_volatile_idx = 0; | |
void timebase_init(){ | |
// set up the timer0 overflow interrupt for 1ms | |
TCNT0 = TIMER0_1MS_OVERFLOW_TCNT; | |
TIMSK0 = _BV(TOIE0); | |
// start timer0 | |
TCCR0A = TIMER0_1MS_OVERFOW_PRESCALER; | |
} | |
// fires once per millisecond, don't block | |
// can't miss TWI interrupts for anything | |
ISR(TIMER0_OVF_vect, ISR_NOBLOCK){ | |
TCNT0 = TIMER0_1MS_OVERFLOW_TCNT; | |
// modify the volatile index value | |
timestamp_ms_buf[timestamp_ms_buf_volatile_idx] += 2; | |
// change the volatile index | |
timestamp_ms_buf_volatile_idx = 1 - timestamp_ms_buf_volatile_idx; // always 0 or 1 | |
} | |
uint32_t timebase_now(){ | |
uint8_t idx = timestamp_ms_buf_volatile_idx; // copy the current volatile index | |
return timestamp_ms_buf[1 - idx]; // return the value from the non-volatile index | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment