55#include " sequans_controller.h"
66
77#include < Arduino.h>
8+ #include < avr/cpufunc.h>
89#include < avr/io.h>
910#include < avr/sleep.h>
1011
@@ -252,26 +253,30 @@ static uint32_t retrieveOperatorSleepTime(void) {
252253
253254static void enablePIT (void ) {
254255
255- // TODO: Fix this, should use external crystal
256- // Setup the clock for RTC. CTRL_SETUP is stored here just for convenience
257- // so that we discard the modifications in the register later
258- //
259- // CLKCTRL.XOSC32KCTRLA |= CLKCTRL_RUNSTBY_bm | CLKCTRL_LPMODE_bm |
260- // CLKCTRL_ENABLE_bm;
256+ uint8_t temp;
261257
262- // Wait for clock to stabilize
263- // while (CLKCTRL.MCLKSTATUS & CLKCTRL_XOSC32KS_bm &&
264- // CLKCTRL.XOSC32KCTRLA & CLKCTRL_SEL_bm) {}
258+ // Disable first and wait for clock to stabilize
259+ temp = CLKCTRL.XOSC32KCTRLA ;
260+ temp &= ~CLKCTRL_ENABLE_bm;
261+ _PROTECTED_WRITE (CLKCTRL.XOSC32KCTRLA , temp);
262+ while (CLKCTRL.MCLKSTATUS & CLKCTRL_XOSC32KS_bm) {}
265263
266- // Now we configure RTC which keeps track of the time during sleep. We do
267- // this here as we yield the RTC afterwards, so a setup every time is just
268- // to safe guard ourselves if other modules use the RTC
269- //
270- // Wait for all registers to be synchronized
264+ // We want the external crystal to run in standby and in low power mode
265+ temp = CLKCTRL.XOSC32KCTRLA ;
266+ temp |= CLKCTRL_RUNSTBY_bm | CLKCTRL_LPMODE_bm;
267+ temp &= ~(CLKCTRL_SEL_bm);
268+ _PROTECTED_WRITE (CLKCTRL.XOSC32KCTRLA , temp);
269+
270+ // Choose to use external crystal on XTAL32K1 and XTAL32K2 pins and enable
271+ // the clock
272+ temp = CLKCTRL.XOSC32KCTRLA ;
273+ temp |= CLKCTRL_ENABLE_bm;
274+ _PROTECTED_WRITE (CLKCTRL.XOSC32KCTRLA , temp);
275+
276+ // Wait for registers to synchronize
271277 while (RTC.PITSTATUS ) {}
272278
273- // TODO: use XOSC32K instead
274- RTC.CLKSEL |= RTC_CLKSEL_INT32K_gc;
279+ RTC.CLKSEL |= RTC_CLKSEL_XOSC32K_gc;
275280 RTC.PITINTCTRL |= RTC_PI_bm;
276281 RTC.PITCTRLA |= RTC_PERIOD_CYC32768_gc | RTC_PITEN_bm;
277282
@@ -285,7 +290,11 @@ static void enablePIT(void) {
285290static void disablePIT (void ) {
286291
287292 // Disable external clock and turn off RTC PIT
288- CLKCTRL.XOSC32KCTRLA &= (~CLKCTRL_ENABLE_bm);
293+ uint8_t temp;
294+ temp = CLKCTRL.XOSC32KCTRLA ;
295+ temp &= ~(CLKCTRL_ENABLE_bm);
296+ _PROTECTED_WRITE (CLKCTRL.XOSC32KCTRLA , temp);
297+
289298 RTC.PITCTRLA &= ~RTC_PITEN_bm;
290299}
291300
0 commit comments