summaryrefslogtreecommitdiff
path: root/timebase.c
blob: 07a5fe7bc62d4aaff0ee3c5848e2c71ecc755d6f (plain)
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
#include "main.h"
#include "timebase.h"

							      // at 12MHz:
#define T0COUNT     (F_CPU / 1024 / 64)	                         // 183
#define T0SECERR    (F_CPU - 1024L * 64 * T0COUNT)	         // 6912
#define T0COUNTSEC  (T0COUNT + T0SECERR / 1024)	                 // 189
#define T0MINERR    (F_CPU - 1024 * (63 * T0COUNT + T0COUNTSEC))  // 768
#define T0COUNTMIN  (T0COUNTSEC + (T0MINERR * 60 + 512) / 1024)  // 234

// 234 = 12000000 Hz
// 233 = 12000017 Hz = 4s/month


u8 timeflags;
u8 dcf77_period;
u8 dcf77_pulse;
u8 ct_64Hz;					// 64 Hz counter (4sec)


void timebase_init( void )
{
  TCCR0 = 1<<CS02^1<<CS00;			// prescale = 1024
  TIMSK = 1<<TOIE0;				// interrupt enable
}

extern uint8_t waitctr;

ISR (TIMER0_OVF0_vect)
{
  static u8 dcf77_time, old_dcf77;
					// DCF77 receive
  if( dcf77_time != 0xFF )			// stop on 0xFF
    dcf77_time++;				// count ticks
  if( ~(DCF77_PIN ^ old_dcf77) & 1<<DCF77 ){	// pin changed ?
    old_dcf77 ^= 0xFF;				// change old flag
    if( old_dcf77 & 1<<DCF77 ){
      dcf77_period = dcf77_time;		// store ticks of period
      dcf77_time = 0;				// count next period
    }else{
      dcf77_pulse = dcf77_time;			// store ticks of pulse
    }
  }

  if (waitctr)
    waitctr--;
					// time base 1 second
  TCNT0 = (u16)(256 - T0COUNT);			// reload per tick: -183
  if( ++ct_64Hz & 0x3F ){			// 64 ticks = one second
    timeflags = 1<<ONE_TICK;			// one tick over
  } else {
    TCNT0 = (u16)(256 - T0COUNTSEC);		// reload per second: -189
    if( timeflags & (1<< ONE_MINUTE ))
      TCNT0 = (u16)(256 - T0COUNTMIN);		// reload per minute: -234
    timeflags = 1<<ONE_SECOND^1<<ONE_TICK;	// one tick, one second over
  }
}


void sync_sec( void )			// synchronize by DCF77
{
  TCNT0 = (u16)(256 - T0COUNTMIN);
  ct_64Hz = 0;
  timeflags = 0;
}