Now I work like this:
Code: Select all
#include <STM32RTC.h>
STM32RTC& rtc = STM32RTC::getInstance();
setup() {
rtc.setClockSource(STM32RTC::LSE_CLOCK);
rtc.begin(); // initialize RTC 24H format
}
Code: Select all
if ((RCC->BDCR & RCC_BDCR_RTCEN) != RCC_BDCR_RTCEN) //Check the clock, if not enabled, then initialize
{
RCC->APB1ENR |= RCC_APB1ENR_PWREN | RCC_APB1ENR_BKPEN; //Enable PWR and Backup clocking
PWR->CR |= PWR_CR_DBP; //Allow access to Backup area
RCC->BDCR |= RCC_BDCR_BDRST; //Reset Backup area
RCC->BDCR &= ~RCC_BDCR_BDRST;
RCC->BDCR |= RCC_BDCR_RTCEN | RCC_BDCR_RTCSEL_LSE; //Select LSE source (quartz 32768) and apply clocking
RCC->BDCR |= RCC_BDCR_LSEON; //Enable LSE
while ((RCC->BDCR & RCC_BDCR_LSEON) != RCC_BDCR_LSEON){} //Wait for power-on
BKP->RTCCR |= 3; //RCC calibration
while (!(RTC->CRL & RTC_CRL_RTOFF)); //check if RTC register changes are finished
RTC->CRL |= RTC_CRL_CNF; //Enable writing to RTC registers
RTC->PRLL = 0x7FFF; //Set the divider to 32768 (32767+1)
BKP->RTCCR |= BKP_RTCCR_CCO; //Enable the Temper pin
RTC->CRL &= ~RTC_CRL_CNF; //Disable writing to RTC registers
while (!(RTC->CRL & RTC_CRL_RTOFF)); //Wait for writing to finish
RTC->CRL &= (uint16_t)~RTC_CRL_RSF; //Synchronize RTC
while((RTC->CRL & RTC_CRL_RSF) != RTC_CRL_RSF){} //Wait for synchronization
PWR->CR &= ~PWR_CR_DBP; //prohibit access to Backup area
}