AnsweredAssumed Answered

STM32F103 RTC Issues

Question asked by Teddy Bonkers on Jul 27, 2015
Latest reply on Jul 29, 2015 by Teddy Bonkers
Hello

I am trying to configure the RTC of a cheap ARM board with STM32F103C8T6: ebay. I am using ST LINK V2-1 and it works, the clock is set for 72 MHz with HSE. The board also has a 32 KHz LSE but when I try to configure it it behaves somewhat strange. My setup routine is:
RCC->APB1ENR |= (RCC_APB1ENR_PWREN | RCC_APB1ENR_BKPEN);
PWR->CR |= PWR_CR_DBP;                                  // access to backup register
RCC->BDCR |= (RCC_BDCR_LSEON);                          // Enable LSE
while((RCC->BDCR & RCC_BDCR_LSERDY) == 0);              // wait until LSE is ready
RCC->BDCR |= RCC_BDCR_RTCSEL_LSE;                       // Select LSE
RCC->BDCR |= RCC_BDCR_RTCEN;                            // Enable RTC
RTC->CRL &= ~RTC_FLAG_RSF;                              // Clear RSF
while((RTC->CRL & RTC_FLAG_RSF) == 0);                  // Wait
 
while(!(RTC->CRL & RTC_CRL_RSF));                       // Wait for the RSF bit in RTC_CRL to be set by hardware
while((RTC->CRL & RTC_CRL_RTOFF) == 0);                 // Wait for RTOFF
 
RTC->CRL |= RTC_CRL_CNF;                                // Configuration mode
RTC->PRLH = 0x0000;                                     // Preload register
RTC->PRLL = 0x7FFF;                                     // Per datasheet for 1 sec signal
RTC->CNTH = 0x0000;
RTC->CNTL = 0x0000;
RTC->CRL &= ~RTC_CRL_CNF;
while((RTC->CRL & RTC_CRL_RTOFF) == 0);

I can confirm all registers get the value I intend to put into them. In my main loop I print the value of the RTC counter every second:
while (1)
{
    HAL_Delay(1000);
    tm = 0;
    tm = RTC->CNTH << 16;
    tm |= RTC->CNTL & 0xffff;
    trace_printf("%02u:%02u:%02u --- CNT: %u\n", (tm/3600), ((tm%3600)/60), ((tm%3600)%60), tm);
 
}
tm here is an uint32_t. And what happens is:
Clock frequency: 72000000 Hz
00:00:00 --- CNT: 0
00:00:01 --- CNT: 1
00:00:02 --- CNT: 2
00:00:02 --- CNT: 2
00:00:03 --- CNT: 3
00:00:03 --- CNT: 3
00:00:04 --- CNT: 4
00:00:05 --- CNT: 5
00:00:05 --- CNT: 5


This is my output. It appears the counter is not incrementing every second, but is also not incrementing every two seconds, and is sort of unpredictable. The HAL delay is working fine and gives 1 second, I checked it with a logic analyzer. When I try to configure the RTC with HAL functions and read the clock with the HAL driver I get the same result. The RTC prescaler is set to 0x7fff - I see the value when debugging.

Thanks

Outcomes