void rtc32_init_v (void) { /* Apply a resetr of the VBAT */ VBAT.CTRL |= VBAT_ACCEN_bm; /* Set access enable bit */ CCPWrite_v((void *)&VBAT.CTRL, VBAT_RESET_bm); /* Enable 32.768kHz crystal oscillator */ CrystalOscillator_v( ); /* Enable low power mode for external oscillator */ OSC.XOSCCTRL = OSC_X32KLPM_bm; /* Reset CNT register */ SetCount_v(0); /* Set PER to 1024. CLK source of the RTC32 is 1024 ticks / second = 1 Hz */ SetPeriod_v(1024); /* Enable overflow interrupts */ RTC32.INTCTRL = RTC32_OVFINTLVL_MED_gc; /* Enable global interrupts */ sei(); } void CCPWrite_v( volatile uint8_t * address, uint8_t value ) { volatile uint8_t * tmpAddr = address; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { #ifdef RAMPZ RAMPZ = 0; #endif asm volatile( "movw r30, %0" "\n\t" "ldi r16, %2" "\n\t" "out %3, r16" "\n\t" "st Z, %1" "\n\t" : : "r" (tmpAddr), "r" (value), "M" (CCP_IOREG_gc), "i" (&CCP) : "r16", "r30", "r31" ); } } /*! \brief This function Enable the 32 kHz crystal oscillator . * */ void CrystalOscillator_v( void ) { /* Enable 32.768kHz crystal oscillator */ VBAT.CTRL |= VBAT_XOSCEN_bm | VBAT_XOSCSEL_bm; /* Wait until oscillator is stable */ while(!(VBAT.STATUS & VBAT_XOSCRDY_bm)); } void SetCount_v( uint32_t count ) { /* Make sure that CNT is not currently synchronizing, or write will fail. */ do { } while ( RTC32_SyncBusy() ); /* Write new count value and wait for synchronization before returning. */ RTC32.CNT = count; do { } while ( RTC32_SyncBusy() ); } void SetPeriod_v( uint32_t period ) { /* Disable the RTC32 module before writing to it. Wait for synch. */ //RTC32.CTRL &= ~RTC32_ENABLE_bm; /* Reset RTC32 module */ RTC32.CTRL = 0; /* Wait until sync done */ do { } while ( RTC32_SyncBusy() ); RTC32.PER = period; /* Enable the RTC32 module. Wait for synch. */ RTC32.CTRL |= RTC32_ENABLE_bm; do { } while ( RTC32_SyncBusy() ); }