Skip to main content
XR.1
Senior
April 14, 2025
Question

RTC writes the year in BCD when the format is RTC_FORMAT_BIN on the STM32G070 part

  • April 14, 2025
  • 1 reply
  • 480 views

This is the thing: when I save the value 25 for the year, the built-in RTC saves the value 37 when the time saving precedes the date saving:

rtc.set_time( time ); 
rtc.set_date( date ); // it calls HAL_RTC_SetDate( this->rtc_, &rtc_date, RTC_FORMAT_BIN )

So in my display (supposing today's date) it's printed: 14/04/37 (dd/mm/yy).

However, when I called the saving functions swapped I get the correct year:

rtc.set_date( date );
rtc.set_time( time );

In my display it's printed: 14/04/25.

 

And it only happens with the year: day, month and weekday are written as expected. It seems that the HAL's function that make the conversion from binary to BCD is working also as expected:

/**
 * @brief Convert a 2 digit decimal to BCD format.
 * @PAram Value Byte to be converted
 * @retval Converted byte
 */
uint8_t RTC_ByteToBcd2(uint8_t Value)
{
 uint32_t bcdhigh = 0U;
 uint8_t Param = Value;

 while(Param >= 10U)
 {
 bcdhigh++;
 Param -= 10U;
 }

 return ((uint8_t)(bcdhigh << 4U) | Param);
}

 

I was already aware that reading from the RTC must follow this pattern: read first the date and then read the time. Does this same bug applies also for writing? (Years ago this missbehavior was considered a bug, later on ST change its status to "by design", and the bug has been spread out among a lot of families).

 

Greetings!

 

 

 

 

 

1 reply

TDK
Super User
April 15, 2025

> I was already aware that reading from the RTC must follow this pattern: read first the date and then read the time.

You must read time first, then date.

This is intentional to keep the time+date consistent and avoid a race condition.

 

> Does this same bug applies also for writing?

No, but because the date may tick over, you should set time first, then date. As long as it takes under a second to complete, it will work.

 

 

> This is the thing: when I save the value 25 for the year, the built-in RTC saves the value 37 when the time saving precedes the date saving:

Maybe provide a complete example showing the problem. The source code is inspectable. Unlikely to be a glaring error in a common peripheral that has gone unnoticed for years.

"If you feel a post has answered your question, please click ""Accept as Solution""."