44 static int __use_32khz = 0;
47 void rtc_init_osc(
int use_32khz)
49 __use_32khz = use_32khz;
60 CRM->RINGOSC_CNTLbits.ROSC_EN = 0;
63 CRM->XTAL32_CNTLbits.XTAL32_EN = 1;
68 CRM->SYS_CNTLbits.XTAL32_EXISTS = 1;
71 while (CRM->RTC_COUNT == old)
80 CRM->RINGOSC_CNTLbits.ROSC_EN = 1;
81 CRM->XTAL32_CNTLbits.XTAL32_EN = 0;
84 CRM->RINGOSC_CNTLbits.ROSC_CTUNE = 0x6;
85 CRM->RINGOSC_CNTLbits.ROSC_FTUNE = 0x17;
92 uint32_t __rtc_try(
int loading,
int timeout)
101 #define RTC_LOADING_MIN 0
102 #define RTC_LOADING_MAX 19960
111 #define MAX_F (FSTEP*FTUNE_MAX)
115 int ctune_start = (loading - MAX_F) / CSTEP;
116 int ctune_end = loading / CSTEP;
117 int best_err = loading, best_ctune = 0, best_ftune = 0;
121 if (ctune_start < 0) ctune_start = 0;
122 if (ctune_end > CTUNE_MAX) ctune_end = CTUNE_MAX;
124 for (ctune = ctune_start; ctune <= ctune_end; ctune++)
126 int this_loading, this_err;
128 ftune = ((loading - (ctune * CSTEP)) + (FSTEP / 2)) / FSTEP;
129 if (ftune < 0) ftune = 0;
130 if (ftune > FTUNE_MAX) ftune = FTUNE_MAX;
132 this_loading = ctune * CSTEP + ftune * FSTEP;
133 this_err =
abs(this_loading - loading);
134 if (this_err < best_err) {
145 CRM->RINGOSC_CNTLbits.ROSC_CTUNE = best_ctune;
146 CRM->RINGOSC_CNTLbits.ROSC_FTUNE = best_ftune;
147 CRM->CAL_CNTLbits.CAL_TIMEOUT = timeout;
148 CRM->STATUSbits.CAL_DONE = 1;
149 CRM->CAL_CNTLbits.CAL_EN = 1;
150 while (CRM->STATUSbits.CAL_DONE == 0)
154 count = CRM->CAL_COUNT;
155 if (count == 0) count = 1;
160 void rtc_calibrate(
void)
166 int low = RTC_LOADING_MIN, high = RTC_LOADING_MAX;
177 for (i = 0; i < 9; i++)
179 mid = (low + high) / 2;
180 count = __rtc_try(mid, TIMEOUT);
182 rtc_freq = REF_OSC / ((count + TIMEOUT/2) / TIMEOUT);
195 void rtc_delay_ms(uint32_t msec)
199 start = CRM->RTC_COUNT;
200 while ((CRM->RTC_COUNT - start) < ((msec * rtc_freq) / 1000))