Contiki-Inga 3.x
xmega_rtc.c
1 #include "xmega_rtc.h"
2 
3 void xmega_rtc_rcosc_enable(void)
4 {
5 #ifdef RTC32
6  #warning RTC32 not supported
7 #else
8  // Enable internal osciallator
9  OSC.CTRL |= OSC_RC32KEN_bm;
10 
11  // Wait for internal RC oscillator to be ready
12  while((OSC.STATUS & OSC_RC32KRDY_bm) == 0);
13 
14  // Use 32.KHz from internal oscillator
15  CLK.RTCCTRL = CLK_RTCSRC_RCOSC32_gc | CLK_RTCEN_bm;
16 #endif
17 }
18 
19 /**
20  * In devices with RTC32 the busy flag can be used for CNT and CTRL
21  */
22 
23 void xmega_rtc_wait_sync_busy(void)
24 {
25 #ifdef RTC32
26  while (RTC32.SYNCCTRL & RTC32_SYNCBUSY_bm);
27 #else
28  while((RTC.STATUS & RTC_SYNCBUSY_bm));
29 #endif
30 }
31 
32 /**
33  * In devices with RTC32 the SYNCCNT Flag will be cleared after sync
34  */
35 
36 void xmega_rtc_wait_sync_cnt(void)
37 {
38 #ifdef RTC32
39  while (RTC32.SYNCCTRL & RTC32_SYNCCNT_bm);
40 #else
41  xmega_rtc_wait_sync_busy();
42 #endif
43 }
44 
45 void xmega_rtc_set_cnt(uint16_t cnt)
46 {
47 #ifdef RTC32
48  RTC32.CNT = cnt;
49  // Start Syncronisation from CNT Register
50  RTC32.SYNCCTRL |= RTC32_SYNCCNT_bm;
51  // Wait for sync flag to be cleared
52  xmega_rtc_wait_sync_cnt();
53 #else
54  RTC.CNT = 0;
55 #endif
56 }
57 
58 // Set compare value
59  // If the compare register is 0 only every third interrupt will generate an event
60  // If the compare register is 1 only every second interrupt will generate an event
61  // if the compare register is greater than or equal two - every interrupt will generate an event
62 // .PER Register is not sychronized automatically, so we have to change COMP or CNT afterwards
63  // 32kHZ / 32 = 1kHz
64 
65 void xmega_rtc_set_per(uint16_t per)
66 {
67 #ifdef RTC32
68  RTC32.PER = per;
69 #else
70  RTC.PER = per;
71 #endif
72 }
73 
74 void xmega_rtc_set_comp(uint16_t cnt)
75 {
76 #ifdef RTC32
77  RTC32.COMP = cnt;
78 #else
79  RTC.COMP = 0;
80 #endif
81 }
82 
83 void xmega_rtc_set_interrupt_levels(uint8_t irq_ovf, uint8_t irq_comp)
84 {
85 #ifdef RTC32
86  // Clear Interrupts first and then add them
87  RTC32.INTCTRL = (RTC32.INTCTRL & ~(RTC32_COMPINTLVL_gm | RTC32_OVFINTLVL_gm)) | irq_ovf | irq_comp;
88 #else
89  RTC.INTCTRL = (RTC.INTCTRL & ~(RTC_COMPINTLVL_gm | RTC_OVFINTLVL_gm)) | irq_ovf | irq_comp;
90 #endif
91 }
92 
93 void xmega_rtc_enable(void)
94 {
95 #ifdef RTC32
96  RTC32.CTRL |= RTC32_ENABLE_bm;
97 #endif
98 }
99 
100 void xmega_rtc_set_prescaler(uint8_t prescaler)
101 {
102 #ifdef RTC
103  RTC.CTRL = (RTC.CTRL & ~RTC_PRESCALER_gm) | (prescaler & RTC_PRESCALER_gm);
104 #endif
105 }