5.18 RTC Guide

This chapter describes the file composition, the 42 public functions and the 5 example projects of the RTC driver in the N32G41x standard peripheral library: the RTC keeps time on an independent RTCCLK and provides time and date, alarms A and B, the wakeup timer, the timestamp, daylight-saving switching, the output pin and calibration, so it can raise an interrupt or drive an output signal at a preset moment while the device stays in a low-power state. Read the RTC clock sources and the register definitions together with the “Real-time clock (RTC)” chapter of the user manual, and take the errata sheet as the authority on known chip issues. The example analysis is taken from the projects under projects/n32g41x_EVAL/examples/RTC/.

5.18.1 Related files

Relative path Purpose
firmware/n32g41x_std_periph_driver/inc/n32g41x_rtc.h Defines the RTC_InitType, RTC_TimeType, RTC_DateType and RTC_AlarmType structures and all configuration macros, and declares 42 public functions in 10 contiguous sections such as reset and initialization and time and date
firmware/n32g41x_std_periph_driver/src/n32g41x_rtc.c Implements those 42 functions: it read-modify-writes the registers through the 0xCA and 0x53 unlock sequence of RTC_WRP, covering the calendar, alarms, wakeup, timestamp, calibration and interrupt control
firmware/CMSIS/device/n32g41x.h Defines the RTC register structure pointer, the field masks and bit definitions, and the macros for the RTC clock sources
projects/n32g41x_EVAL/examples/RTC/ The RTC example category root, holding 5 buildable projects: Alarm, AlarmSubsecond, Calendar, RtcAutoWakeUp and TimeStamp
projects/n32g41x_EVAL/examples/RTC/Calendar/ The directory make-up of one typical example: src/main.c and src/n32g41x_it.c hold the main flow and the interrupt service, inc/main.h and inc/n32g41x_it.h are the headers and readme.txt is the description, with the MDK-ARM/ and EWARM/ project folders;
the shared helpers that read and write the date and time live in the sibling Common/ directory
projects/n32g41x_EVAL/bsp/ Board support code: the log serial logging and delay helpers that the RTC examples reference

5.18.2 API reference

Search API42 functions

The following 42 public functions are listed in the declaration order of n32g41x_rtc.h in 10 groups; each entry gives a summary and the original comment above the function in n32g41x_rtc.c.

Reset and initialization

RTC_DeInit, RTC_Init, RTC_StructInit, RTC_EnableWriteProtection, RTC_EnterInitMode, RTC_ExitInitMode, RTC_WaitForSynchro, RTC_EnableRefClock, RTC_EnableBypassShadow

Time and date configuration

RTC_TimeStructInit, RTC_ConfigTime, RTC_GetTime, RTC_GetSubSecond, RTC_DateStructInit, RTC_SetDate, RTC_GetDate

Alarm configuration

RTC_SetAlarm, RTC_AlarmStructInit, RTC_GetAlarm, RTC_EnableAlarm, RTC_ConfigAlarmSubSecond, RTC_GetAlarmSubSecond

Wakeup timer

RTC_ConfigWakeUpClock, RTC_SetWakeUpCounter, RTC_GetWakeUpCounter, RTC_EnableWakeUp

Daylight saving

RTC_ConfigDayLightSaving, RTC_GetStoreOperation

Output pin configuration

RTC_ConfigOutput, RTC_ConfigOutputType

Calibration

RTC_EnableCalibOutput, RTC_ConfigCalibOutput, RTC_ConfigSmoothCalib

Timestamp

RTC_EnableTimeStamp, RTC_GetTimeStamp, RTC_GetTimeStampSubSecond

Shift control

RTC_ConfigSynchroShift

Interrupt and flag management

RTC_ConfigInt, RTC_GetFlagStatus, RTC_ClrFlag, RTC_GetITStatus, RTC_ClrIntPendingBit

ErrorStatus RTC_DeInit(void)Deinitializes the RTC registers to their default reset values.
Source comment
name    RTC_DeInit.
fun     Deinitializes the RTC registers to their default reset values.
param   none
return  ErrorStatus
            - SUCCESS: RTC registers are deinitialized
            - ERROR: RTC registers are not deinitialized

Use note: The implementation first unlocks the write protection with 0xCA and 0x53, enters initialization mode and resets the time, date, prescaler, alarm A and B, calibration and interrupt status registers, then waits for the registers to synchronize and locks the registers again.

ErrorStatus RTC_Init(const RTC_InitType *RTC_InitStruct)Initializes the RTC registers according to the specified parameters in RTC_InitStruct.
Source comment
name    RTC_Init.
fun     Initializes the RTC registers according to the specified parameters
        in RTC_InitStruct.
param   RTC_InitStruct : pointer to a RTC_InitType structure that contains
        the configuration information for the RTC peripheral.
            - RTC_HourFormat
                - RTC_24HOUR_FORMAT
                - RTC_12HOUR_FORMAT
            - RTC_AsynchPrediv  the value must not be greater than 0x7F
                (7 bit field RTC_PRE.DIVA[6:0])
            - RTC_SynchPrediv   the value must not be greater than 0x7FFF
                (15 bit field RTC_PRE.DIVS[14:0])
return  ErrorStatus
            - SUCCESS: RTC registers are initialized
            - ERROR: RTC registers are not initialized

Use note: The implementation writes RTC_SynchPrediv into RTC_PRE.DIVS[14:0] and RTC_AsynchPrediv into RTC_PRE.DIVA[6:0], then writes RTC_HourFormat into RTC_CTRL.HFMT.

void RTC_StructInit(RTC_InitType *RTC_InitStruct)Fills each RTC_InitStruct member with its default value.
Source comment
name    RTC_StructInit.
fun     Fills each RTC_InitStruct member with its default value.
param   RTC_InitStruct : pointer to a RTC_InitType structure which will be
        initialized.
            - RTC_HourFormat
                - RTC_24HOUR_FORMAT
                - RTC_12HOUR_FORMAT
            - RTC_AsynchPrediv  the value must not be greater than 0x7F
                (7 bit field RTC_PRE.DIVA[6:0])
            - RTC_SynchPrediv   the value must not be greater than 0x7FFF
                (15 bit field RTC_PRE.DIVS[14:0])
return  none
void RTC_EnableWriteProtection(FunctionalState Cmd)Enable or disable the RTC registers write protection.
Source comment
name    RTC_EnableWriteProtection.
fun     Enable or disable the RTC registers write protection.
param   Cmd : new state of the RTC registers write protection
          - ENABLE: write protection enabled (a wrong key is written to RTC_WRP)
          - DISABLE: write protection disabled (0xCA then 0x53 unlocks the registers)
return  none

Use note: When Cmd is DISABLE the implementation writes 0xCA and then 0x53 to RTC_WRP to unlock the registers; any other value writes a non-key value to lock them again, and every other function that changes an RTC register performs the same unlock and lock.

ErrorStatus RTC_EnterInitMode(void)Enters the RTC Initialization mode.
Source comment
name    RTC_EnterInitMode.
fun     Enters the RTC Initialization mode.
param   none
return   ErrorStatus
            - SUCCESS: RTC is in Init mode
            - ERROR: RTC is not in Init mode

Use note: The implementation first waits until the subsecond counter is not less than 3 and differs from the prescaler value, reads the date register once, and then sets RTC_INITSTS.INITM; a return of ERROR means initialization mode was not entered.

void RTC_ExitInitMode(void)When the initialization sequence is complete, the calendar restarts counting after 4 RTCCLK cycles.
Source comment
name    RTC_ExitInitMode.
fun     When the initialization sequence is complete, the calendar restarts counting after 4 RTCCLK cycles.
param   none
return  none
ErrorStatus RTC_WaitForSynchro(void)Waits until the RTC Time and Date registers (RTC_TSH and RTC_DATE) are synchronized with RTC APB clock.
Source comment
name    RTC_WaitForSynchro.
fun     Waits until the RTC Time and Date registers (RTC_TSH and RTC_DATE) are synchronized with RTC APB clock.
param   none
return  ErrorStatus :
            - SUCCESS:  RTC registers are synchronised
            - ERROR:    RTC registers are not synchronised
ErrorStatus RTC_EnableRefClock(FunctionalState Cmd)Enables or disables the RTC reference clock detection.
Source comment
name    RTC_EnableRefClock.
fun     Enables or disables the RTC reference clock detection.
param   Cmd : new state of the RTC reference clock detection
          - ENABLE: reference clock detection enabled
          - DISABLE: reference clock detection disabled
return  ErrorStatus
            - SUCCESS: reference clock detection configured
            - ERROR: the initialization mode could not be entered
void RTC_EnableBypassShadow(FunctionalState Cmd)When the bypass shadow is enabled the calendar values are taken directly from the calendar counters.
Source comment
name    RTC_EnableBypassShadow.
fun     When the bypass shadow is enabled the calendar values are taken
        directly from the calendar counters.
param   Cmd : new state of the bypass shadow
          - ENABLE: calendar values read directly from the counters
          - DISABLE: calendar values read from the shadow registers
return  none

Use note: Enabling sets RTC_CTRL.BYPS to 1; when the APB1 clock is lower than 7 times RTCCLK the bypass must be enabled, otherwise the calendar read values are not guaranteed to be correct.

void RTC_TimeStructInit(RTC_TimeType *RTC_TimeStruct)Fills each RTC_TimeStruct member with its default value (Time = 00h:00 min:00sec).
Source comment
name    RTC_TimeStructInit.
fun     Fills each RTC_TimeStruct member with its default value
        (Time = 00h:00 min:00sec).
param   RTC_TimeStruct : RTC_TimeStruct pointer to a RTC_TimeType structure that contains
                         the time configuration information for the RTC.
            - Hours
                - if RTC_AM_H12 is select the value in the 0-23 range
                - if RTC_PM_H12 is select the value in the 1-12 range
            - Minutes  the value set in the 0-59 range
            - Seconds  the value set in the 0-59 range
            - H12
                - RTC_AM_H12
                - RTC_PM_H12
return  none
ErrorStatus RTC_ConfigTime(uint32_t RTC_Format, const RTC_TimeType *RTC_TimeStruct)Set the RTC current Time.
Source comment
name    RTC_ConfigTime.
fun     Set the RTC current Time.
param  RTC_Format :
          - RTC_FORMAT_BIN
          - RTC_FORMAT_BCD
param   RTC_TimeStruct : RTC_TimeStruct pointer to a RTC_TimeType structure that contains
        the time configuration information for the RTC. The pointer must reference
        a valid RTC_TimeType instance, NULL is not accepted by this function.
            - Hours
                - if RTC_AM_H12 is select the value in the 0-23 range
                - if RTC_PM_H12 is select the value in the 1-12 range
            - Minutes  the value set in the 0-59 range
            - Seconds  the value set in the 0-59 range
            - H12
                - RTC_AM_H12
                - RTC_PM_H12
return  ErrorStatus
void RTC_GetTime(uint32_t RTC_Format, RTC_TimeType *RTC_TimeStruct)Get the RTC current Time.
Source comment
name    RTC_GetTime.
fun     Get the RTC current Time.
param   RTC_Format : specifies the format of the returned parameters.
            - RTC_FORMAT_BIN
            - RTC_FORMAT_BCD
param   RTC_TimeStruct : RTC_TimeStruct pointer to a RTC_TimeType structure.
return  none
uint32_t RTC_GetSubSecond(void)Gets the RTC current Calendar Subseconds value.
Source comment
name    RTC_GetSubSecond.
fun     Gets the RTC current Calendar Subseconds value.
return  RTC current Calendar Subseconds value.
void RTC_DateStructInit(RTC_DateType *RTC_DateStruct)Fills each RTC_DateStruct member with its default value (Monday, January 01 xx00).
Source comment
name    RTC_DateStructInit.
fun     Fills each RTC_DateStruct member with its default value (Monday, January 01 xx00).
param   RTC_DateStruct : RTC_DateStruct pointer to a RTC_DateType structure that contains
                       the date configuration information for the RTC.
            - WeekDay
                - RTC_WEEKDAY_MONDAY
                - RTC_WEEKDAY_TUESDAY
                - RTC_WEEKDAY_WEDNESDAY
                - RTC_WEEKDAY_THURSDAY
                - RTC_WEEKDAY_FRIDAY
                - RTC_WEEKDAY_SATURDAY
                - RTC_WEEKDAY_SUNDAY
            - Month
                - RTC_MONTH_JANUARY
                - RTC_MONTH_FEBRURY
                - RTC_MONTH_MARCH
                - RTC_MONTH_APRIL
                - RTC_MONTH_MAY
                - RTC_MONTH_JUNE
                - RTC_MONTH_JULY
                - RTC_MONTH_AUGUST
                - RTC_MONTH_SEPTEMBER
                - RTC_MONTH_OCTOBER
                - RTC_MONTH_NOVEMBER
                - RTC_MONTH_DECEMBER
            - Date    the value in the 1-31 range
            - Year    the value in the 0-99 range
return  none
ErrorStatus RTC_SetDate(uint32_t RTC_Format, RTC_DateType *RTC_DateStruct)Set RTC Calendar current date.
Source comment
name    RTC_SetDate.
fun     Set RTC Calendar current date.
param   RTC_Format : specifies the format of the returned parameters.
          - RTC_FORMAT_BIN
          - RTC_FORMAT_BCD
param   RTC_DateStruct : RTC_DateStruct pointer to a RTC_DateType structure that contains
        the date configuration information for the RTC. The pointer must reference
        a valid RTC_DateType instance, NULL is not accepted by this function.
            - WeekDay
                - RTC_WEEKDAY_MONDAY
                - RTC_WEEKDAY_TUESDAY
                - RTC_WEEKDAY_WEDNESDAY
                - RTC_WEEKDAY_THURSDAY
                - RTC_WEEKDAY_FRIDAY
                - RTC_WEEKDAY_SATURDAY
                - RTC_WEEKDAY_SUNDAY
            - Month
                - RTC_MONTH_JANUARY
                - RTC_MONTH_FEBRURY
                - RTC_MONTH_MARCH
                - RTC_MONTH_APRIL
                - RTC_MONTH_MAY
                - RTC_MONTH_JUNE
                - RTC_MONTH_JULY
                - RTC_MONTH_AUGUST
                - RTC_MONTH_SEPTEMBER
                - RTC_MONTH_OCTOBER
                - RTC_MONTH_NOVEMBER
                - RTC_MONTH_DECEMBER
            - Date    the value in the 1-31 range
            - Year    the value in the 0-99 range
return  ErrorStatus
            - SUCCESS:  RTC Date register is configured
            - ERROR:    RTCDate register is not configured
void RTC_GetDate(uint32_t RTC_Format, RTC_DateType *RTC_DateStruct)Get the RTC current date.
Source comment
name    RTC_GetDate.
fun     Get the RTC current date.
param   RTC_Format : specifies the format of the returned parameters.
            - RTC_FORMAT_BIN
            - RTC_FORMAT_BCD
param   RTC_DateStruct : RTC_DateStruct pointer to a RTC_DateType structure that will
                       contain the returned current date configuration.
return  none
void RTC_SetAlarm(uint32_t RTC_Format, uint32_t RTC_Alarm, const RTC_AlarmType *RTC_AlarmStruct)Set the specified RTC Alarm.
Source comment
name    RTC_SetAlarm.
fun     Set the specified RTC Alarm.
param   RTC_Format : specifies the format of the returned parameters.
            - RTC_FORMAT_BIN
            - RTC_FORMAT_BCD
param   RTC_Alarm : RTC_Alarm specifies the alarm to be configured.
            - RTC_A_ALARM
            - RTC_B_ALARM
param   RTC_AlarmStruct : RTC_AlarmStruct pointer to a RTC_AlarmType structure that
                          contains the alarm configuration parameters.
            - AlarmTime   RTC_TimeStruct pointer to a RTC_TimeType structure that contains
                         the time configuration information for the RTC.
            - Hours
                - if RTC_AM_H12 is select the value in the 0-23 range
                - if RTC_PM_H12 is select the value in the 1-12 range
            - Minutes  the value set in the 0-59 range
            - Seconds  the value set in the 0-59 range
            - H12
                - RTC_AM_H12
                - RTC_PM_H12
            - AlarmMask
                - RTC_ALARMMASK_NONE
                - RTC_ALARMMASK_WEEKDAY
                - RTC_ALARMMASK_HOURS
                - RTC_ALARMMASK_MINUTES
                - RTC_ALARMMASK_SECONDS
                - RTC_ALARMMASK_ALL
            - DateWeekMode
                - RTC_ALARM_SEL_WEEKDAY_DATE
                - RTC_ALARM_SEL_WEEKDAY_WEEKDAY
            - DateWeekValue
                - RTC_WEEKDAY_MONDAY
                - RTC_WEEKDAY_TUESDAY
                - RTC_WEEKDAY_WEDNESDAY
                - RTC_WEEKDAY_THURSDAY
                - RTC_WEEKDAY_FRIDAY
                - RTC_WEEKDAY_SATURDAY
                - RTC_WEEKDAY_SUNDAY
return  none
void RTC_AlarmStructInit(RTC_AlarmType *RTC_AlarmStruct)Fills each RTC_AlarmStruct member with its default value (Time = 00h:00mn:00sec / Date = 1st day of the month/Mask = no fields are masked).
Source comment
name    RTC_AlarmStructInit.
fun     Fills each RTC_AlarmStruct member with its default value
        (Time = 00h:00mn:00sec / Date = 1st day of the month/Mask =
        no fields are masked).
param   RTC_AlarmStruct : RTC_AlarmStruct pointer to a RTC_AlarmType structure that
                          contains the alarm configuration parameters.
            - AlarmTime   RTC_TimeStruct pointer to a RTC_TimeType structure that contains
                         the time configuration information for the RTC.
            - Hours
                - if RTC_AM_H12 is select the value in the 0-23 range
                - if RTC_PM_H12 is select the value in the 1-12 range
            - Minutes  the value set in the 0-59 range
            - Seconds  the value set in the 0-59 range
            - H12
                - RTC_AM_H12
                - RTC_PM_H12
            - AlarmMask
                - RTC_ALARMMASK_NONE
                - RTC_ALARMMASK_WEEKDAY
                - RTC_ALARMMASK_HOURS
                - RTC_ALARMMASK_MINUTES
                - RTC_ALARMMASK_SECONDS
                - RTC_ALARMMASK_ALL
            - DateWeekMode
                - RTC_ALARM_SEL_WEEKDAY_DATE
                - RTC_ALARM_SEL_WEEKDAY_WEEKDAY
            - DateWeekValue
                - RTC_WEEKDAY_MONDAY
                - RTC_WEEKDAY_TUESDAY
                - RTC_WEEKDAY_WEDNESDAY
                - RTC_WEEKDAY_THURSDAY
                - RTC_WEEKDAY_FRIDAY
                - RTC_WEEKDAY_SATURDAY
                - RTC_WEEKDAY_SUNDAY
return  none
void RTC_GetAlarm(uint32_t RTC_Format, uint32_t RTC_Alarm, RTC_AlarmType *RTC_AlarmStruct)Get the RTC Alarm value and masks.
Source comment
name    RTC_GetAlarm.
fun     Get the RTC Alarm value and masks.
param   RTC_Format : specifies the format of the output parameters.
            - RTC_FORMAT_BIN
            - RTC_FORMAT_BCD
param   RTC_Alarm : specifies the alarm to be read.
            - RTC_A_ALARM
            - RTC_B_ALARM
param   RTC_AlarmStruct : pointer to a RTC_AlarmType structure that will
        contains the output alarm configuration values.

return  none
ErrorStatus RTC_EnableAlarm(uint32_t RTC_Alarm, FunctionalState Cmd)Enables or disables the specified RTC Alarm.
Source comment
name    RTC_EnableAlarm.
fun     Enables or disables the specified RTC Alarm.
param   RTC_Alarm : specifies the alarm to be configured.
            - RTC_A_ALARM
            - RTC_B_ALARM
param  Cmd :
          - ENABLE
          - DISABLE
return  ErrorStatus :
            - SUCCESS: RTC Alarm set succeed
            - ERROR:   RTC Alarm set failed

Use note: When the alarm is disabled the implementation waits for the write flag ALxAWF to be set and returns ERROR if it is still clear when the wait times out.

void RTC_ConfigAlarmSubSecond(uint32_t RTC_Alarm, uint32_t RTC_AlarmSubSecondValue, uint32_t RTC_AlarmSubSecondMask)Configure the RTC AlarmA/B Subseconds value and mask
Source comment
name    RTC_ConfigAlarmSubSecond.
fun     Configure the RTC AlarmA/B Subseconds value and mask
param   RTC_Alarm : specifies the alarm to be configured.
            - RTC_A_ALARM : select Alarm A.
            - RTC_B_ALARM : select Alarm B.
param   RTC_AlarmSubSecondValue : specifies the Subseconds value, the value in the 0-0x00007FFF range
param   RTC_AlarmSubSecondMask : specifies the Subseconds Mask.
            - RTC_SUBS_MASK_ALL     : Alarm SS fields are masked There is no comparison on sub seconds for Alarm.
            - RTC_SUBS_MASK_SS14_1  : SS[14:1] are don't care in Alarm comparison Only SS[0] is compared
            - RTC_SUBS_MASK_SS14_2  : SS[14:2] are don't care in Alarm comparison Only SS[1:0] are compared
            - RTC_SUBS_MASK_SS14_3  : SS[14:3] are don't care in Alarm comparison Only SS[2:0] are compared
            - RTC_SUBS_MASK_SS14_4  : SS[14:4] are don't care in Alarm comparison Only SS[3:0] are compared
            - RTC_SUBS_MASK_SS14_5  : SS[14:5] are don't care in Alarm comparison Only SS[4:0] are compared
            - RTC_SUBS_MASK_SS14_6  : SS[14:6] are don't care in Alarm comparison Only SS[5:0] are compared
            - RTC_SUBS_MASK_SS14_7  : SS[14:7] are don't care in Alarm comparison Only SS[6:0] are compared
            - RTC_SUBS_MASK_SS14_8  : SS[14:8] are don't care in Alarm comparison Only SS[7:0] are compared
            - RTC_SUBS_MASK_SS14_9  : SS[14:9] are don't care in Alarm comparison Only SS[8:0] are compared
            - RTC_SUBS_MASK_SS14_10 : SS[14:10] are don't care in Alarm comparison Only SS[9:0] are compared
            - RTC_SUBS_MASK_SS14_11 : SS[14:11] are don't care in Alarm comparison Only SS[10:0] are compared
            - RTC_SUBS_MASK_SS14_12 : SS[14:12] are don't care in Alarm comparison Only SS[11:0] are compared
            - RTC_SUBS_MASK_SS14_13 : SS[14:13] are don't care in Alarm comparison Only SS[12:0] are compared
            - RTC_SUBS_MASK_SS14_14 : SS[14] is don't care in Alarm comparison Only SS[13:0] are compared.
            - RTC_SUBS_MASK_NONE    : SS[14:0] are compared and must match to activate alarm.
return  None
uint32_t RTC_GetAlarmSubSecond(uint32_t RTC_Alarm)Gets the RTC Alarm Subseconds value.
Source comment
name    RTC_GetAlarmSubSecond.
fun     Gets the RTC Alarm Subseconds value.
param   RTC_Alarm : specifies the alarm to be read.
            - RTC_A_ALARM : select Alarm A.
            - RTC_B_ALARM : select Alarm B.
return  RTC Alarm Subseconds value.
void RTC_ConfigWakeUpClock(RTC_WAKE_UP_CLOCK WakeUpClock)Configures the RTC Wakeup clock source.
Source comment
name    RTC_ConfigWakeUpClock.
fun     Configures the RTC Wakeup clock source.
param   WakeUpClock :  Wakeup Clock source.
            - RTC_WKUPCLK_RTCCLK_DIV16 : RTC Wakeup Counter Clock = RTCCLK/16.
            - RTC_WKUPCLK_RTCCLK_DIV8 : RTC Wakeup Counter Clock = RTCCLK/8.
            - RTC_WKUPCLK_RTCCLK_DIV4 : RTC Wakeup Counter Clock = RTCCLK/4.
            - RTC_WKUPCLK_RTCCLK_DIV2 : RTC Wakeup Counter Clock = RTCCLK/2.
            - RTC_WKUPCLK_CK_SPRE_16BITS : RTC Wakeup Counter Clock = CK_SPRE.
            - RTC_WKUPCLK_CK_SPRE_17BITS : RTC Wakeup Counter Clock = CK_SPRE,and wakeup timer count is 2^16.
return  none
void RTC_SetWakeUpCounter(uint32_t RTC_WakeUpCounter)Configures the RTC Wakeup counter.
Source comment
name    RTC_SetWakeUpCounter.
fun     Configures the RTC Wakeup counter.
param   RTC_WakeUpCounter : specifies the WakeUp counter, the value in the 0-0xFFFF range
return  none
uint32_t RTC_GetWakeUpCounter(void)Returns the RTC WakeUp timer counter value.
Source comment
name    RTC_GetWakeUpCounter.
fun     Returns the RTC WakeUp timer counter value.
param   none
return  The RTC WakeUp Counter value.
ErrorStatus RTC_EnableWakeUp(FunctionalState Cmd)Enables or disables the RTC WakeUp timer.
Source comment
name    RTC_EnableWakeUp
fun     Enables or disables the RTC WakeUp timer.
param  Cmd :
          - ENABLE
          - DISABLE
return  ErrorStatus :
            - SUCCESS: RTC wakeup timer configured successfully
            - ERROR:   RTC wakeup timer WTWF wait timed out

Use note: When the wakeup timer is disabled the implementation waits for the write flag WTWF to be set and returns ERROR if it is still clear when the wait times out.

void RTC_ConfigDayLightSaving(uint32_t RTC_DayLightSaving, uint32_t RTC_StoreOperation)Adds or subtract one hour from the current time.
Source comment
name    RTC_ConfigDayLightSaving
fun     Adds or subtract one hour from the current time.
param   RTC_DayLightSaving : the value of hour adjustment.
            - RTC_DAYLIGHT_SAVING_SUB1H : Subtract one hour (winter time).
            - RTC_DAYLIGHT_SAVING_ADD1H : Add one hour (summer time).
param   RTC_StoreOperation : Specifies the value to be written in the BAKP bit
        in CTRL register to store the operation.
            - RTC_STORE_OPERATION_RESET :  BAKP Bit Reset.
            - RTC_STORE_OPERATION_SET : BAKP Bit Set.
return  none
uint32_t RTC_GetStoreOperation(void)Returns the RTC Day Light Saving stored operation.
Source comment
name    RTC_GetStoreOperation
fun     Returns the RTC Day Light Saving stored operation.
return  RTC Day Light Saving stored operation.
            - RTC_STORE_OPERATION_RESET
            - RTC_STORE_OPERATION_SET
void RTC_ConfigOutput(uint32_t RTC_Output, uint32_t RTC_OutputPolarity)Configures the RTC output source.
Source comment
name    RTC_ConfigOutput
fun     Configures the RTC output source.
param   RTC_Output : RTC_Output Specifies which signal will be routed to the RTC output.
            - RTC_OUTPUT_DIS : No output selected
            - RTC_OUTPUT_ALA : signal of AlarmA mapped to output.
            - RTC_OUTPUT_ALB : signal of AlarmB mapped to output.
            - RTC_OUTPUT_WKUP: signal of WakeUp mapped to output.
param   RTC_OutputPolarity : Specifies the polarity of the output signal.
            - RTC_OUTPOL_HIGH: The output pin is high when the ALAF/ALBF/WTF flag is set (depending on OUTSEL[1:0]).
            - RTC_OUTPOL_LOW : The output pin is low when the ALAF/ALBF/WTF flag is set (depending on OUTSEL[1:0]).
return  none
void RTC_ConfigOutputType(uint32_t RTC_OutputType)Configures the RTC Output Pin mode.
Source comment
name    RTC_ConfigOutputType
fun     Configures the RTC Output Pin mode.
param   RTC_OutputType : specifies the RTC Output (PC13) pin mode.
            - RTC_OUTPUT_OPENDRAIN : RTC Output (PC13) is configured in  Open Drain mode.
            - RTC_OUTPUT_PUSHPULL : RTC Output (PC13) is configured in Push Pull mode.
return  none
void RTC_EnableCalibOutput(FunctionalState Cmd)Enable or disable the RTC calibration clock to be output through the relative pin.
Source comment
name    RTC_EnableCalibOutput
fun     Enable or disable the RTC calibration clock to be output through the relative pin.
param   Cmd :
          - ENABLE
          - DISABLE
return  none
void RTC_ConfigCalibOutput(uint32_t RTC_CalibOutput)Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 256Hz).
Source comment
name    RTC_ConfigCalibOutput
fun     Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 256Hz).
param   RTC_CalibOutput : Select the Calibration output Selection.
            - RTC_CALIB_OUTPUT_256HZ : A signal has a regular waveform at 256Hz.
            - RTC_CALIB_OUTPUT_1HZ   : A signal has a regular waveform at 1Hz.
return  none
ErrorStatus RTC_ConfigSmoothCalib(uint32_t RTC_SmoothCalibPeriod, uint32_t RTC_SmoothCalibPlusPulses, uint32_t RTC_SmoothCalibMinusPulsesValue)Configures the Smooth Calibration Settings.
Source comment
name    RTC_ConfigSmoothCalib
fun     Configures the Smooth Calibration Settings.
param   RTC_SmoothCalibPeriod : RTC_SmoothCalibPeriod Select the Smooth Calibration Period.
            - SMOOTH_CALIB_32SEC : The smooth calibration period is 32s.
            - SMOOTH_CALIB_16SEC : The smooth calibration period is 16s.
            - SMOOTH_CALIB_8SEC  : The smooth calibration period is 8s.
param   RTC_SmoothCalibPlusPulses : Set or reset the CP bit.
            - RTC_SMOOTH_CALIB_PLUS_PULSES_SET : Add one RTCCLK pulse every 2**11 pulses.
            - RTC_SMOOTH_CALIB_PLUS_PULSES_RESET : No RTCCLK pulses are added.
param   RTC_SmoothCalibMinusPulsesValue : Set the value of CM[8:0] bits, the value in the 0-0x000001FF range
return  ErrorStatus
            - SUCCESS : RTC Calib registers are configured
            - ERROR   : RTC Calib registers are not configured

Use note: The implementation first waits for RECPF to be cleared and returns ERROR without writing the calibration registers if the flag is still set when the wait ends.

void RTC_EnableTimeStamp(uint32_t RTC_TimeStampEdge, FunctionalState Cmd)Enables or disables the RTC TimeStamp functionality with the specified time stamp pin stimulating edge.
Source comment
name    RTC_EnableTimeStamp
fun     Enables or disables the RTC TimeStamp functionality with the specified time stamp pin stimulating edge.
param   RTC_TimeStampEdge : Specifies the pin edge on which the TimeStamp is activated.
            - RTC_TIMESTAMP_EDGE_RISING : the Time stamp event occurs on the rising edge of the related pin.
            - RTC_TIMESTAMP_EDGE_FALLING : the Time stamp event occurs on the falling edge of the related pin.
param  Cmd :
          - ENABLE
          - DISABLE
return  none
void RTC_GetTimeStamp(uint32_t RTC_Format, RTC_TimeType *RTC_StampTimeStruct, RTC_DateType *RTC_StampDateStruct)Get the RTC TimeStamp value and masks.
Source comment
name    RTC_GetTimeStamp
fun     Get the RTC TimeStamp value and masks.
param   RTC_Format : specifies the format of the output parameters.
            - RTC_FORMAT_BIN : Binary data format
            - RTC_FORMAT_BCD : BCD data format
param   RTC_StampTimeStruct : pointer to a RTC_TimeType structure that will
        contains the TimeStamp time values.
param   RTC_StampDateStruct : pointer to a RTC_DateType structure that will
        contains the TimeStamp date values.
return  none
uint32_t RTC_GetTimeStampSubSecond(void)Get the RTC timestamp Subseconds value.
Source comment
name    RTC_GetTimeStampSubSecond
fun     Get the RTC timestamp Subseconds value.
param   none
return  RTC current timestamp Subseconds value.
ErrorStatus RTC_ConfigSynchroShift(uint32_t RTC_ShiftAdd1S, uint32_t RTC_ShiftSubFS)Configures the Synchronization Shift Control Settings.
Source comment
name    RTC_ConfigSynchroShift
fun     Configures the Synchronization Shift Control Settings.
param   RTC_ShiftAdd1S : Select to add or not 1 second to the time Calendar.
            - RTC_SHIFT_ADD1S_DISABLE : No effect.
            - RTC_SHIFT_ADD1S_ENABLE : Add one second to the clock calendar.
param   RTC_ShiftSubFS : Select the number of Second Fractions to Substitute.
            This parameter can be any value from 0 to 0x7FFF.
return  ErrorStatus :
            - SUCCESS : RTC Shift registers are configured
            - ERROR : RTC Shift registers are not configured
void RTC_ConfigInt(uint32_t RTC_INT, FunctionalState Cmd)Enables or disables the specified RTC interrupts.
Source comment
name    RTC_ConfigInt
fun     Enables or disables the specified RTC interrupts.
param   RTC_INT : specifies the RTC interrupt sources to be enabled .
            - RTC_INT_TS  : TimeStamp interrupt mask.
            - RTC_INT_WUT : WakeUp Timer interrupt mask.
            - RTC_INT_ALRB : Alarm B interrupt mask.
            - RTC_INT_ALRA : Alarm A interrupt mask.
param  Cmd :
          - ENABLE
          - DISABLE
return  none
FlagStatus RTC_GetFlagStatus(uint32_t RTC_FLAG)Checks whether the specified RTC flag is set or not.
Source comment
name    RTC_GetFlagStatus
fun     Checks whether the specified RTC flag is set or not.
param   RTC_FLAG : specifies the flag to check.
          - RTC_FLAG_RECPF  : RECPF flag.
          - RTC_FLAG_TISOVF : Time Stamp OverFlow flag.
          - RTC_FLAG_TISF   : Time Stamp event flag.
          - RTC_FLAG_WTF    : WakeUp Timer flag.
          - RTC_FLAG_ALBF   : Alarm B flag.
          - RTC_FLAG_ALAF   : Alarm A flag.
          - RTC_FLAG_INITF  : Initialization mode flag.
          - RTC_FLAG_RSYF   : Registers Synchronized flag.
          - RTC_FLAG_INITSF : Registers Configured flag.
          - RTC_FLAG_SHOPF  : Shift operation pending flag.
          - RTC_FLAG_WTWF   : WakeUp Timer Write flag.
          - RTC_FLAG_ALBWF  : Alarm B Write flag.
          - RTC_FLAG_ALAWF  : Alarm A write flag.
return  FlagStatus
          - SET   : the flag is set
          - RESET : the flag is reset
void RTC_ClrFlag(uint32_t RTC_FLAG)Clears the RTC’s flags.
Source comment
name    RTC_ClrFlag
fun     Clears the RTC's flags.
param   RTC_FLAG : RTC_FLAG specifies the RTC flag to clear.
          - RTC_FLAG_TISOVF  : Time Stamp Overflow flag.
          - RTC_FLAG_TISF    : Time Stamp event flag.
          - RTC_FLAG_WTF     : WakeUp Timer flag.
          - RTC_FLAG_ALBF    : Alarm B flag.
          - RTC_FLAG_ALAF    : Alarm A flag.
          - RTC_FLAG_RSYF    : Registers Synchronized flag.
return  none
INTStatus RTC_GetITStatus(uint32_t RTC_INT)Checks whether the specified RTC interrupt has occurred or not.
Source comment
name    RTC_GetITStatus
fun     Checks whether the specified RTC interrupt has occurred or not.
param   RTC_INT : specifies the RTC interrupt source to check.
          - RTC_INT_TS    : Timestamp interrupt.
          - RTC_INT_WUT   : WakeUp Timer interrupt.
          - RTC_INT_ALRB  : Alarm B interrupt.
          - RTC_INT_ALRA  : Alarm A interrupt.
return  INTStatus
          - SET   : the flag is set
          - RESET : the flag is reset
void RTC_ClrIntPendingBit(uint32_t RTC_INT)Clears the RTC’s interrupt pending bits.
Source comment
name    RTC_ClrIntPendingBit
fun     Clears the RTC's interrupt pending bits.
param   RTC_INT : specifies the RTC interrupt pending bit to clear.
          - RTC_INT_TS    : Timestamp interrupt.
          - RTC_INT_WUT   : WakeUp Timer interrupt
          - RTC_INT_ALRB  : Alarm B interrupt
          - RTC_INT_ALRA  : Alarm A interrupt
return  none

5.18.3 Demo descriptions

This section describes the 5 RTC examples: Alarm and AlarmSubsecond demonstrate the alarm interrupt, Calendar prints the calendar once a second from the calibration output, RtcAutoWakeUp demonstrates periodic automatic wakeup, and TimeStamp records the instant an external pin is triggered. Every example uses LSE as RTCCLK, and the shared clock configuration and date and time display helpers live in the sibling Common/ directory.

5.18.3.1 Alarm alarm interrupt

Example directory: projects/n32g41x_EVAL/examples/RTC/Alarm/

Initialize the log UART→Select LSE as the RTC clock and configure the prescaler→Write the default date, time and alarm A→Configure the PC13 alarm output and the EXTI17 interrupt→Print the current time from the interrupt when the alarm fires

Item Source analysis
Function Drives the RTC from LSE and writes the default date, time and alarm A;
when the alarm fires it raises the EXTI17 interrupt, prints the current time from the interrupt and routes the alarm A signal to PC13.
Source files src/main.c: EXTI17_RTCAlarm_Configuration and main;
src/n32g41x_it.c and inc/n32g41x_it.h: the RTC_ALARM_IRQHandler interrupt service;
inc/main.h: the function declarations;
readme.txt: the function, environment and usage notes;
MDK-ARM/ and EWARM/: the Keil and IAR projects;
the helpers that write and display the date and time are in the sibling Common/ directory.
Key configuration The RTC clock source is RTC_CLK_SRC_TYPE_LSE;
the default alarm mask is the bitwise OR of RTC_ALARMMASK_WEEKDAY, RTC_ALARMMASK_HOURS and RTC_ALARMMASK_MINUTES, so the alarm fires only when the minute and the second match;
the output type is RTC_OUTPUT_PUSHPULL and the output source is RTC_OUTPUT_ALA with RTC_OUTPOL_HIGH;
the EXTI17 trigger edge is rising and the interrupt channel is RTC_ALARM_IRQn.
Program and data path main first calls log_init and then RTC_DateAndTimeDefaultVale to prepare the default values;
after RTC_CLKSourceConfig selects LSE, and while RTC_FLAG_INITSF is not set, it calls RTC_DeInit, RTC_PrescalerConfig, RTC_DateRegulate, RTC_TimeRegulate and RTC_AlarmRegulate in turn;
it then configures the PC13 output and enters the empty while (1) loop after RTC_ClrIntPendingBit and EXTI17_RTCAlarm_Configuration.
Main APIs RTC_DateAndTimeDefaultVale, RTC_CLKSourceConfig, RTC_DeInit, RTC_GetFlagStatus, RTC_PrescalerConfig, RTC_DateRegulate, RTC_TimeRegulate, RTC_AlarmRegulate, RTC_ConfigOutputType, RTC_ConfigOutput, RTC_ClrIntPendingBit, EXTI_InitPeripheral, NVIC_Init
Verification After a reset the serial port prints RTC Init and the initialization result;
at the set moment the code enters RTC_ALARM_IRQHandler, prints the current date and time and toggles PC13.
Use note The serial port is USART1 with TX on PA9 and RX on PA10, 115200 baud, 8N1;
the system clock is HSI with PLL, 80 MHz for N32G412 and 96 MHz for N32G415;
the development environment is KEIL MDK-ARM V5.34 or IAR EWARM 8.50.1 and the chips are N32G412x8L7, N32G412xBL7, N32G415x8L7 and N32G415xBL7.
After reading the date and time, read RTC->DATE once to unfreeze the shadow register.
Core-code walkthrough and porting

The example writes the default date, time and alarm into the RTC in one go and then uses the alarm interrupt to confirm that the calendar is running.

Data path: main -> RTC_DateAndTimeDefaultVale prepares the default structures -> RTC_CLKSourceConfig selects LSE -> RTC_DeInit, RTC_PrescalerConfig, RTC_DateRegulate, RTC_TimeRegulate and RTC_AlarmRegulate write the calendar and the alarm -> RTC_ConfigOutput routes alarm A to PC13 -> the alarm fires -> RTC_ALARM_IRQHandler -> RTC_TimeShow

1. Prepare the default values before selecting the clock source. main first calls RTC_DateAndTimeDefaultVale, whose combined mask makes the alarm fire only when the minute and the second match, and then selects LSE as RTCCLK with RTC_CLKSourceConfig.

src/main.csrc/main.c · main
    /* RTC date time alarm default value*/
    RTC_DateAndTimeDefaultVale(RTC_ALARMMASK_WEEKDAY | RTC_ALARMMASK_HOURS | RTC_ALARMMASK_MINUTES);
    /* RTC clock source select */

The mask sets the trigger condition, so decide which fields should be compared before changing it.

2. Write the calendar and the alarm only on the first run. RTC_FLAG_INITSF tells whether the RTC was already configured; when it is not set, reset, prescaler, date, time and alarm are written in a fixed order.

src/main.csrc/main.c · main
        if (RTC_GetFlagStatus(RTC_FLAG_INITSF) != SET)
        {
            RTC_DeInit();
            RTC_PrescalerConfig();
            /* RTC date time and alarm regulate*/
            RTC_DateRegulate();
            RTC_TimeRegulate();
            RTC_AlarmRegulate(RTC_A_ALARM);

RTC_PrescalerConfig divides LSE down to a 1 Hz counting tick, and RTC_AlarmRegulate returns SUCCESS or ERROR so the caller can tell whether the alarm was written.

3. Configure the alarm output and open the interrupt. Once initialization is done the code configures PC13 as a push-pull output, routes alarm A to it, clears the alarm A interrupt pending bit and then enables the EXTI17 interrupt.

src/main.csrc/main.c · main
    /* Alarm output I/O config */
    RTC_ConfigOutputType(RTC_OUTPUT_PUSHPULL);
    /* Alarm output I/O polarity */
    RTC_ConfigOutput(RTC_OUTPUT_ALA, RTC_OUTPOL_HIGH);

    /* Alarm out select option*/
    RTC_ClrIntPendingBit(RTC_INT_ALRA);
    EXTI17_RTCAlarm_Configuration(ENABLE);

Corresponding source files: src/main.c, src/n32g41x_it.c, inc/main.h

5.18.3.2 AlarmSubsecond subsecond alarm

Example directory: projects/n32g41x_EVAL/examples/RTC/AlarmSubsecond/

Initialize the log UART→Select LSE and write the default date and time→Configure the alarm A subsecond value and mask→Enable the alarm A interrupt and route the output to PC13→Print the 500 ms notice when the main loop sees the flag

Item Source analysis
Function Compares the subsecond as well on alarm A, so the alarm fires every 500 ms;
the interrupt sets a boolean flag and the main loop clears it and prints 500ms Alarm Wakeup over the serial port, while the alarm A signal is routed to PC13.
Source files src/main.c: EXTI17_RTCAlarm_Configuration and main;
src/n32g41x_it.c and inc/n32g41x_it.h: the RTC_ALARM_IRQHandler interrupt service that sets the global flag;
inc/main.h: the function declarations;
readme.txt: the function, environment and usage notes;
MDK-ARM/ and EWARM/: the Keil and IAR projects;
the shared helpers are in the sibling Common/ directory.
Key configuration The RTC clock source is RTC_CLK_SRC_TYPE_LSE;
the default mask is RTC_ALARMMASK_ALL, which compares every field;
the subsecond value is 128 with the mask RTC_SUBS_MASK_SS14_7, giving the 500 ms tick 1 / (32768 / 128);
the output type is RTC_OUTPUT_PUSHPULL and the output source is RTC_OUTPUT_ALA with RTC_OUTPOL_HIGH.
Program and data path main calls log_init and then selects LSE with RTC_CLKSourceConfig;
on the first run it calls RTC_DeInit and RTC_PrescalerConfig, writes the subsecond value and mask with RTC_ConfigAlarmSubSecond and then writes the calendar with RTC_DateRegulate, RTC_TimeRegulate and RTC_AlarmRegulate;
the main loop polls the global flag RTC_Time_Out_Flag, clears it and prints.
Main APIs RTC_DateAndTimeDefaultVale, RTC_CLKSourceConfig, RTC_DeInit, RTC_PrescalerConfig, RTC_ConfigAlarmSubSecond, RTC_DateRegulate, RTC_TimeRegulate, RTC_AlarmRegulate, RTC_ConfigOutputType, RTC_ConfigOutput, RTC_ClrIntPendingBit
Verification After a reset the serial port prints 500ms Alarm Wakeup periodically and the PC13 output toggles every 500 ms;
changing the subsecond value and mask changes the print rate.
Use note The subsecond mask RTC_SUBS_MASK_SS14_7 compares only SS[6:0], so the comparison resolution is limited;
the serial port is USART1 with TX on PA9 and RX on PA10, 115200 baud, 8N1;
the system clock is HSI with PLL.
Core-code walkthrough and porting

The example adds a subsecond comparison on top of the minute alarm, shortens the alarm period to 500 ms and uses a global flag to hand the interrupt event to the main loop.

Data path: main -> RTC_ConfigAlarmSubSecond writes the subsecond value and mask -> alarm A fires every 500 ms -> RTC_ALARM_IRQHandler sets RTC_Time_Out_Flag -> the main loop clears the flag and prints with log_info

1. Use default values that compare every field. Unlike the Alarm example the default mask is RTC_ALARMMASK_ALL, so the hour, minute, second and other fields are all compared and the trigger instant is refined by the subsecond value.

src/main.csrc/main.c · main
    /* RTC date time alarm default value*/
    RTC_DateAndTimeDefaultVale(RTC_ALARMMASK_ALL);

2. Add the subsecond configuration to the initialization. Between the reset and prescaler steps and the calendar write, RTC_ConfigAlarmSubSecond writes the subsecond value 128 and the mask RTC_SUBS_MASK_SS14_7 into the alarm A subsecond register in one call.

src/main.csrc/main.c · main
            RTC_DeInit();
            RTC_PrescalerConfig();
            /* ALRMASS Value(128) = 500ms / (1 / (32768/128)) */
            RTC_ConfigAlarmSubSecond(RTC_A_ALARM, 128, RTC_SUBS_MASK_SS14_7);

The comment gives the conversion: with RTCCLK at 32768 Hz, dividing by 128 makes each subsecond tick equal to 500 ms of 1 / (32768 / 128).

3. Consume the interrupt flag in the main loop. The interrupt service only sets the flag, and the actual print runs in the main loop so that no serial output is produced inside the interrupt.

src/main.csrc/main.c · main
    while (1)
    {
        if(RTC_Time_Out_Flag)
        {
            RTC_Time_Out_Flag=false;
            log_info("\r\n 500ms Alarm Wakeup \r\n");
        }
    }

Corresponding source files: src/main.c, src/n32g41x_it.c, inc/main.h

5.18.3.3 Calendar calendar print

Example directory: projects/n32g41x_EVAL/examples/RTC/Calendar/

Initialize the log UART→Select LSE and write the default date and time→Configure PA7 as an input with the EXTI7 interrupt→Enable the 1 Hz calibration output on PC13→Print the date and time once per second from the interrupt

Item Source analysis
Function Produces a 1 Hz square wave on PC13 from the RTC calibration output, wires PC13 externally to PA7, and prints the current date and time from the PA7 EXTI7 interrupt that fires once a second.
Source files src/main.c: EXTI_PA7_Configuration and main;
src/n32g41x_it.c and inc/n32g41x_it.h: the EXTI5_9_IRQHandler interrupt service;
inc/main.h: the function declarations;
readme.txt: the function, environment and usage notes;
MDK-ARM/ and EWARM/: the Keil and IAR projects;
the shared helpers are in the sibling Common/ directory.
Key configuration The RTC clock source is RTC_CLK_SRC_TYPE_LSE;
PA7 is initialized as GPIO_MODE_INPUT and mapped to EXTI7 with a rising trigger edge and the EXTI5_9_IRQn channel at preemption and sub priority 0x01;
the calibration output is RTC_CALIB_OUTPUT_1HZ and the output type is RTC_OUTPUT_PUSHPULL.
Program and data path main calls log_init, selects LSE with RTC_CLKSourceConfig and, while RTC_FLAG_INITSF is not set, calls RTC_DeInit, RTC_PrescalerConfig, RTC_DateRegulate and RTC_TimeRegulate;
it then configures the PA7 interrupt with EXTI_ClrITPendBit and EXTI_PA7_Configuration, turns on the PC13 1 Hz output with RTC_ConfigCalibOutput, RTC_ConfigOutputType and RTC_EnableCalibOutput, and enters while (1).
Main APIs RTC_DateAndTimeDefaultVale, RTC_CLKSourceConfig, RTC_DeInit, RTC_PrescalerConfig, RTC_DateRegulate, RTC_TimeRegulate, RTC_ConfigCalibOutput, RTC_ConfigOutputType, RTC_EnableCalibOutput, GPIO_InitPeripheral, GPIO_ConfigEXTILine, EXTI_InitPeripheral
Verification Wire PC13 to PA7 first and then run the example after a reset;
the serial port prints the date and time once a second and stops printing when the wire is removed.
Use note The interrupt service prints the calendar and clears the pending bit after it sees EXTI_LINE7;
the example depends on a physical wire between PC13 and PA7, so a different board needs its own connection.
The serial port is USART1 with TX on PA9 and RX on PA10, 115200 baud, 8N1.
Core-code walkthrough and porting

The example uses the RTC calibration output as a one-second pulse source and prints the calendar once a second from the PA7 external interrupt, which is a low-frequency time base that does not occupy a timer.

Data path: main -> EXTI_PA7_Configuration sets up PA7 and EXTI7 -> RTC_ConfigCalibOutput and RTC_EnableCalibOutput drive PC13 at 1 Hz -> the PC13 signal reaches PA7 over an external wire -> EXTI5_9_IRQHandler -> RTC_DateShow and RTC_TimeShow print

1. Clear the pending bit and configure the PA7 interrupt. The EXTI7 pending bit is cleared before the interrupt is armed, and EXTI_PA7_Configuration then sets up the pin, the EXTI line and the NVIC in one call.

src/main.csrc/main.c · main
    /* Configure the PA7 pin to generate an EXTI interrupt
       in which the calendar value is printed (externally feed
       the 1HZ signal output on PC13 to PA7 to produce a 1s EXTI interrupt)*/
    EXTI_ClrITPendBit(EXTI_LINE7);
    EXTI_PA7_Configuration();

2. Select the 1 Hz calibration output and make it push-pull. There are two calibration output rates and 1 Hz is used here; the output type must be set explicitly to push-pull or open-drain, otherwise the expected square wave does not appear on PC13.

src/main.csrc/main.c · main
    /* Calibrate output 1Hz signal */
    RTC_ConfigCalibOutput(RTC_CALIB_OUTPUT_1HZ);
    /* Calibrate output config,push pull */
    RTC_ConfigOutputType(RTC_OUTPUT_PUSHPULL);

3. Enable the calibration output. The last step calls RTC_EnableCalibOutput, which is what actually routes the calibration clock to PC13, and then the serial port prints a configuration-done message.

src/main.csrc/main.c · main
    /* Calibrate output enable*/
    RTC_EnableCalibOutput(ENABLE);
    log_info("\r\n RTC Config end....");

Corresponding source files: src/main.c, src/n32g41x_it.c, inc/main.h

5.18.3.4 RtcAutoWakeUp automatic wakeup

Example directory: projects/n32g41x_EVAL/examples/RTC/RtcAutoWakeUp/

Initialize the log UART→Select LSE and write the default date and time→Configure the wakeup clock source and counter→Enable the wakeup interrupt and route the wakeup signal to PC13→Print the current time from the interrupt on every wakeup

Item Source analysis
Function Wakes the device periodically with the RTC automatic wakeup timer;
each wakeup raises the EXTI19 interrupt, which prints the current time, and the wakeup signal is also routed to PC13.
Source files src/main.c: EXTI19_RTCWKUP_Configuration and main;
src/n32g41x_it.c and inc/n32g41x_it.h: the RTC_WKUP_IRQHandler interrupt service;
inc/main.h: the function declarations;
readme.txt: the function, environment and usage notes;
MDK-ARM/ and EWARM/: the Keil and IAR projects;
the shared helpers are in the sibling Common/ directory.
Key configuration The RTC clock source is RTC_CLK_SRC_TYPE_LSE;
the wakeup clock source is RTC_WKUPCLK_CK_SPRE_16BITS and the wakeup counter is 4, that is one wakeup every 5 seconds;
the output type is RTC_OUTPUT_PUSHPULL and the output source is RTC_OUTPUT_WKUP with RTC_OUTPOL_HIGH;
the EXTI19 interrupt channel is RTC_WKUP_IRQn.
Program and data path After the RTC initialization main sets the period with RTC_ConfigWakeUpClock and RTC_SetWakeUpCounter;
it then arms the wakeup interrupt with EXTI_ClrITPendBit, EXTI19_RTCWKUP_Configuration, RTC_ClrIntPendingBit and RTC_ConfigInt, and enables the wakeup and its output with RTC_ConfigOutputType, RTC_ConfigOutput and RTC_EnableWakeUp.
Main APIs RTC_DateAndTimeDefaultVale, RTC_CLKSourceConfig, RTC_DeInit, RTC_PrescalerConfig, RTC_DateRegulate, RTC_TimeRegulate, RTC_ConfigWakeUpClock, RTC_SetWakeUpCounter, RTC_ClrIntPendingBit, RTC_ConfigInt, RTC_EnableWakeUp, RTC_ConfigOutput
Verification After a reset the serial port prints the current time every 5 seconds and the PC13 output toggles with it;
changing the value passed to RTC_SetWakeUpCounter changes the observed period.
Use note With the wakeup clock source set to RTC_WKUPCLK_CK_SPRE_16BITS the counting tick matches the RTC second tick;
writing 0 to the wakeup counter raises a wakeup event immediately.
The serial port is USART1 with TX on PA9 and RX on PA10, 115200 baud, 8N1.
Core-code walkthrough and porting

The example turns the RTC wakeup timer into a periodic time base and prints the time from the EXTI19 interrupt on every wakeup, which suits a periodic task trigger in a low-power state.

Data path: main -> RTC_ConfigWakeUpClock and RTC_SetWakeUpCounter set the wakeup period -> RTC_ConfigInt arms the WUT interrupt -> the period elapses -> RTC_WKUP_IRQHandler clears EXTI19 and the pending bit -> RTC_TimeShow prints; RTC_ConfigOutput routes the wakeup signal to PC13

1. Select the wakeup clock source and counter value. The wakeup clock source is the second tick and the counter is 4, so the timer fires when it reaches 4, which is one wakeup every 5 seconds together with the second tick.

src/main.csrc/main.c · main
            /* wake up clock select */
            RTC_ConfigWakeUpClock(RTC_WKUPCLK_CK_SPRE_16BITS);
            /* wake up timer value */
            RTC_SetWakeUpCounter(4);

2. Clear the pending bit, arm the interrupt and start the wakeup. When the interrupt is armed the WUT pending bit is cleared first, the interrupt is enabled next and RTC_EnableWakeUp starts the wakeup timer last.

src/main.csrc/main.c · main
    EXTI_ClrITPendBit(EXTI_LINE19);
    EXTI19_RTCWKUP_Configuration(ENABLE);
    /* Enable the RTC Wakeup Interrupt */
    RTC_ClrIntPendingBit(RTC_INT_WUT);
    RTC_ConfigInt(RTC_INT_WUT, ENABLE);
    RTC_EnableWakeUp(ENABLE);

3. Route the wakeup signal to PC13. With a push-pull output type PC13 can drive an external observation point directly, while switching to open-drain needs a pull-up resistor on PC13.

src/main.csrc/main.c · main
    /* Set the output type (open-drain output + push-pull output).
       When setting OD, external  should be added pull-up resistor to PC13*/
    RTC_ConfigOutputType(RTC_OUTPUT_PUSHPULL);

    RTC_ConfigOutput(RTC_OUTPUT_WKUP, RTC_OUTPOL_HIGH);
    RTC_EnableWakeUp(ENABLE);

Corresponding source files: src/main.c, src/n32g41x_it.c, inc/main.h

5.18.3.5 TimeStamp timestamp

Example directory: projects/n32g41x_EVAL/examples/RTC/TimeStamp/

Initialize the log UART→Select LSE and write the default date and time→Configure PB8 as an input wired to the timestamp trigger→Enable the falling-edge timestamp and its interrupt→Print the captured instant from the interrupt on every trigger

Item Source analysis
Function Wires the RTC timestamp trigger to PB8 with a falling-edge trigger, so that every falling edge on PB8 makes the RTC capture the current instant and raise an interrupt that prints the date and time of the triggering moment.
Source files src/main.c: RTC_TimeStampShow, EXTI_PB8_TimeStamp_Configuration, EXTI18_STAMP_IRQn_Configuration and main;
src/n32g41x_it.c and inc/n32g41x_it.h: the RTC_STAMP_LSECSS_IRQHandler interrupt service;
inc/main.h: the function declarations;
readme.txt: the function, environment and usage notes;
MDK-ARM/ and EWARM/: the Keil and IAR projects;
the shared helpers are in the sibling Common/ directory.
Key configuration The RTC clock source is RTC_CLK_SRC_TYPE_LSE;
PB8 is initialized as GPIO_MODE_INPUT and connected to the timestamp through EXTI_RTCTimeStampSel and GPIO_ConfigEXTILine;
the timestamp trigger edge is RTC_TIMESTAMP_EDGE_FALLING;
the EXTI_LINE18 trigger edge is rising and the interrupt channel is RTC_STAMP_LSECSS_IRQn;
the calibration output is RTC_CALIB_OUTPUT_1HZ.
Program and data path After the RTC initialization main turns on the PC13 1 Hz calibration output;
EXTI_PB8_TimeStamp_Configuration then configures PB8, EXTI_ClrITPendBit and EXTI18_STAMP_IRQn_Configuration arm the interrupt, and after clearing RTC_FLAG_TISF and RTC_FLAG_TISOVF the timestamp is enabled with RTC_EnableTimeStamp and RTC_ConfigInt.
Main APIs RTC_DateAndTimeDefaultVale, RTC_CLKSourceConfig, RTC_DeInit, RTC_PrescalerConfig, RTC_DateRegulate, RTC_TimeRegulate, RTC_ConfigCalibOutput, RTC_ConfigOutputType, RTC_EnableCalibOutput, RTC_GetTimeStamp, RTC_ClrFlag, RTC_EnableTimeStamp, RTC_ConfigInt
Verification Wire PC13 to PB8 first and then run the example after a reset;
the serial port prints the date and time captured by the timestamp once a second and stops triggering when the wire is removed.
Use note The interrupt service checks RTC_INT_TS, reads the timestamp and then clears RTC_FLAG_TISF and RTC_FLAG_TISOVF;
read the timestamp with RTC_GetTimeStamp(RTC_FORMAT_BIN, ...). The serial port is USART1 with TX on PA9 and RX on PA10, 115200 baud, 8N1.
Core-code walkthrough and porting

The example uses the RTC timestamp to record the instant an event occurs on an external pin, with the PC13 1 Hz output acting as the trigger source and a binary format for the read-out.

Data path: main -> EXTI_PB8_TimeStamp_Configuration connects PB8 to the timestamp -> RTC_EnableTimeStamp and RTC_ConfigInt enable the falling-edge timestamp -> the PC13 signal reaches PB8 over an external wire -> a falling edge triggers -> RTC_STAMP_LSECSS_IRQHandler -> RTC_GetTimeStamp -> RTC_TimeStampShow prints

1. Connect PB8 to the timestamp trigger. PB8 is first initialized in input mode, then EXTI_RTCTimeStampSel selects EXTI8 as the timestamp source and EXTI8 is finally mapped to PB8.

src/main.csrc/main.c · EXTI_PB8_TimeStamp_Configuration
    /* Connect EXTI8 to RTC_TimeStamp */
    EXTI_RTCTimeStampSel(EXTI_TSSEL_LINE8);
    /* Connect EXTI8 Line to PB8 pin */
    GPIO_ConfigEXTILine(GPIOB_PORT_SOURCE, GPIO_PIN_SOURCE8);

2. Enable the falling-edge timestamp and its interrupt. Both RTC_FLAG_TISF and RTC_FLAG_TISOVF are cleared before enabling, and the timestamp and the RTC_INT_TS interrupt are then enabled in turn.

src/main.csrc/main.c · main
    EXTI_ClrITPendBit(EXTI_LINE18);
    EXTI18_STAMP_IRQn_Configuration(ENABLE, 1);
    /* clear RTC time stamp flag  */
    RTC_ClrFlag(RTC_FLAG_TISF);
    RTC_ClrFlag(RTC_FLAG_TISOVF);
    RTC_EnableTimeStamp(RTC_TIMESTAMP_EDGE_FALLING, ENABLE);
    RTC_ConfigInt(RTC_INT_TS, ENABLE);

3. Use the PC13 1 Hz output as the trigger source. Enabling the PC13 1 Hz calibration output and running one wire to PB8 triggers a timestamp once a second.

src/main.csrc/main.c · main
    RTC_ConfigCalibOutput(RTC_CALIB_OUTPUT_1HZ);
    /* Calibrate output config,push pull */
    RTC_ConfigOutputType(RTC_OUTPUT_PUSHPULL);
    /* Calibrate output enable*/
    RTC_EnableCalibOutput(ENABLE);

Corresponding source files: src/main.c, src/n32g41x_it.c, inc/main.h

5.18.4 Notes and troubleshooting

Scenario Check & action Source
Changes to the RTC registers have no effect The RTC registers are write-protected by default, so 0xCA and then 0x53 must be written to RTC_WRP to unlock them and a non-key value must be written afterwards to lock them again;
every function in the driver that changes an RTC register performs this unlock and lock sequence internally.
User manual
Choosing the RTC clock source The RTC clock source can be LSE, LSI or HSE/128, all selected through the RTC clock selection bits of the RCC;
when HSE/128 is chosen the APB1 frequency must not be lower than HSE.
User manual
The calendar reads are not accurate When the APB1 clock is lower than 7 times RTCCLK and the bypass shadow register is not enabled (BYPS is 0), reading the calendar requires reading the time register before the date register in the order given by the manual to freeze the shadow registers, otherwise the values read may be inconsistent. User manual
Initialization mode cannot be entered Before setting INITM the hardware requires the subsecond register and the prescaler to satisfy the comparison condition given by the manual, and the date register must be read once;
initialization mode does not take effect when the condition is not met.
User manual
The second field takes part in the alarm comparison When the second field of the alarm is selected for comparison (its mask bit is reset) the prescaler RTC_PRE.DIVS[14:0] must be greater than 3, otherwise the alarm does not behave as expected. User manual
Writing 0 to the wakeup counter Writing 0 to the wakeup counter raises a wakeup event immediately;
the wakeup counter must be changed inside the wakeup interrupt or after the wakeup timer has been disabled first.
User manual
Read and clear order of the timestamp flags Before reading the timestamp, read RTC_FLAG_TISF to detect the event and RTC_FLAG_TISOVF to detect a subsecond overflow, and clear both flags after the read completes. User manual
Limits of the calibration feature The smooth calibration CM[8:0] only takes effect when DIVA is not less than 3;
the calibration output can be 1 Hz or 256 Hz and must be mapped to PC13 with the calibration output enabled.
User manual

The N32G412 and N32G415 series errata sheet V1.0.0 (2026.6.30) lists a single row for revision A chips with an empty errata link column, and gives no RTC-related entries.

Nations Technologies DevKit Docs

Datasheets, SDK, driver APIs and demo guides for Nations Technologies MCU development kits, organized by chip series.

© 2026 Nations Technologies Inc. All rights reserved.粤ICP备11069485号This site uses cookie-free anonymous analytics.