time.c 1.09 KB
Newer Older
springob's avatar
springob committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <util/atomic.h>
#include <avr/sleep.h>
//#include <avr/cpufunc.h>


#if defined(ARDUINO)

#ifdef __cplusplus
extern "C" {
#endif

volatile uint32_t clock_ticks;

static uint32_t get_clock_ticks() {
  uint32_t m;
  uint8_t oldSREG = SREG;
  cli();
  m = clock_ticks;
  SREG = oldSREG;
  return m;
};


unsigned long millis() {
  return get_clock_ticks() / 50;
}


unsigned long micros() {
  return get_clock_ticks() * 20;
}


static void delay_ticks(unsigned long ticks) {
  uint32_t end = get_clock_ticks()+ticks;
  while (1) {    
    yield();
    uint32_t dt = get_clock_ticks() - end;
    if (!(dt&0x80000000)) {
      return;
    }
  }
}

void delay(unsigned long ms) {
  while (ms) {
    delay_ticks(50);
    ms--;
  }
}

void _time_suspend() {
  TIMSK1 &= ~_BV(OCIE1A);
  TCCR1A = 0;
  TCCR1B = 0;
}

void _time_resume() {
  TCCR1A = 0;
  TCCR1B = _BV(WGM12) | _BV(CS11); // CTC, PS=8
  OCR1A = 20-1; // 20 us  // 50 kHz
  TIMSK1 |= _BV(OCIE1A);
}

#ifdef __cplusplus
}
#endif


ISR(TIMER1_COMPA_vect) {
  clock_ticks++;
}


#endif