5.23 RTC 使用说明

本章说明 N32H49x 标准外设库中 RTC 驱动的文件组成、56 个公开函数,以及 Alarm、AlarmSubsecond、Calendar、RtcAutoWakeUp、RtcBKP、Tamper、TimeStamp 7 个示例。RTC 位于备份域,配置前需使能 PWR 与 BKP 时钟并打开备份域写访问;寄存器位定义、影子寄存器与备份域操作请配合用户手册的“实时时钟(RTC)”章节阅读。

5.23.1 相关文件

相对路径 作用
firmware/n32h49x_std_periph_driver/inc/n32h49x_rtc.h 定义 RTC_InitType、RTC_TimeType、RTC_DateType、RTC_AlarmType 等结构体,以及时钟源、小时格式、闹钟掩码、唤醒时钟、校准、篡改触发等宏;
按 14 个区段声明 56 个公开函数,覆盖复位、初始化与配置直至篡改检测与备份寄存器
firmware/n32h49x_std_periph_driver/src/n32h49x_rtc.c 实现上述 56 个函数:初始化模式与预分频配置,时间、日期与亚秒访问,闹钟与唤醒定时器配置,输出与校准,时间戳与篡改检测,中断与标志管理,备份寄存器访问
projects/n32h49x_EVAL/examples/RTC/ RTC 示例根目录,含 Alarm、AlarmSubsecond、Calendar、RtcAutoWakeUp、RtcBKP、Tamper、TimeStamp 7 个示例
projects/n32h49x_EVAL/examples/RTC/Alarm/ 该示例的工程目录组成:MDK-ARM/、EWARM/、inc/、src/、readme.txt
projects/n32h49x_EVAL/bsp/ 多个示例共用的板级支持文件:串口日志打印与毫秒延时

5.23.2 API 参考

搜索 API共 56 个函数

以下 56 个公开函数按 n32h49x_rtc.h 的声明顺序分为 14 组;每个条目给出功能摘要与 n32h49x_rtc.c 中该函数正上方的注释原文。

复位

RTC_DeInit

初始化与配置

RTC_Init、RTC_StructInit、RTC_EnableWriteProtection、RTC_EnterInitMode、RTC_ExitInitMode、RTC_WaitForSynchro、RTC_EnableRefClock、RTC_EnableBypassShadow

时间与日期

RTC_TimeStructInit、RTC_ConfigTime、RTC_GetTime、RTC_GetSubSecond、RTC_DateStructInit、RTC_SetDate、RTC_GetDate

输出类型

RTC_ConfigOutputType

闹钟

RTC_SetAlarm、RTC_AlarmStructInit、RTC_GetAlarm、RTC_EnableAlarm、RTC_ConfigAlarmSubSecond、RTC_GetAlarmSubSecond

唤醒定时器

RTC_ConfigWakeUpClock、RTC_SetWakeUpCounter、RTC_GetWakeUpCounter、RTC_EnableWakeUp

夏时令

RTC_ConfigDayLightSaving、RTC_GetStoreOperation

输出引脚

RTC_ConfigOutput、RTC_EnableOutput2、RTC_EnableTampOutput

校准

RTC_EnableCalibOutput、RTC_ConfigCalibOutput、RTC_ConfigSmoothCalib

时间戳

RTC_EnableTimeStamp、RTC_GetTimeStamp、RTC_GetTimeStampSubSecond

同步移位

RTC_ConfigSynchroShift

中断与标志

RTC_ConfigInt、RTC_GetFlagStatus、RTC_ClrFlag、RTC_GetITStatus、RTC_ClrIntPendingBit

篡改检测

RTC_TamperTriggerConfig、RTC_TamperCmd、RTC_TamperFilterConfig、RTC_TamperSamplingFreqConfig、RTC_TamperPinsPrechargeDuration、RTC_TimeStampOnTamperDetectionCmd、RTC_TamperPullUpCmd、RTC_TamperIECmd、RTC_TamperTAMPTSCmd、RTC_EnableTampErase

备份寄存器

RTC_BKUPRgWrite、RTC_BKUPRgRead

ErrorStatus RTC_DeInit(void)将 RTC 寄存器恢复为默认复位值。
源码注释
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
ErrorStatus RTC_Init(RTC_InitType* RTC_InitStruct)指向 RTC_InitType 结构的 RTC_InitStruct 指针,包含 RTC 外设的配置信息。
源码注释
name    RTC_Init.
fun     RTC_InitStruct pointer to a RTC_InitType structure that contains
        the configuration information for the RTC peripheral
param   RTC_InitStruct
            - RTC_HourFormat
                - RTC_24HOUR_FORMAT
                - RTC_12HOUR_FORMAT
            - RTC_AsynchPrediv  the value must lower than 0x7F
            - RTC_SynchPrediv   the value must lower than 0x7FFF
return  ErrorStatus
            - SUCCESS: RTC registers are deinitialized
            - ERROR: RTC registers are not deinitialized
void RTC_StructInit(RTC_InitType* RTC_InitStruct)将 RTC_InitStruct 的每个成员填充为默认值。
源码注释
name    RTC_StructInit.
fun     Fills each RTC_InitStruct member with its default value.
param   RTC_InitStruct :    RTC_InitStruct pointer to a RTC_InitType structure which will beinitialized.
            - RTC_HourFormat
                - RTC_24HOUR_FORMAT
                - RTC_12HOUR_FORMAT
            - RTC_AsynchPrediv  the value must lower than 0x7F
            - RTC_SynchPrediv   the value must lower than 0x7FFF
return  none
void RTC_EnableWriteProtection(FunctionalState Cmd)使能或禁止 RTC 寄存器写保护。
源码注释
name    RTC_EnableWriteProtection.
fun     Enable or disable the RTC registers write protection.
param  Cmd :
          - ENABLE
          - DISABLE
return  none
ErrorStatus RTC_EnterInitMode(void)进入 RTC 初始化模式。
源码注释
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
void RTC_ExitInitMode(void)初始化序列完成后,日历在 4 个 RTCCLK 周期后重新开始计数。
源码注释
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)等待 RTC 时间和日期寄存器(RTC_TSH 与 RTC_DATE)与 RTC APB 时钟同步。
源码注释
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)使能或禁止 RTC 参考时钟检测。
源码注释
name    RTC_EnableRefClock.
fun     Enables or disables the RTC reference clock detection.
param  Cmd :
          - ENABLE
          - DISABLE
return  none
void RTC_EnableBypassShadow(FunctionalState Cmd)使能旁路影子寄存器后,日历值直接取自日历计数器。
源码注释
name    RTC_EnableBypassShadow.
fun     When the Bypass Shadow is enabled the calendar value are taken directly from the Calendar counter
param  Cmd :
          - ENABLE
          - DISABLE
return  none
void RTC_TimeStructInit(RTC_TimeType* RTC_TimeStruct)将 RTC_TimeStruct 的每个成员填充为默认值(时间 = 00h:00 min:00sec)。
源码注释
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, RTC_TimeType* RTC_TimeStruct)读取影子寄存器中的日历值。
源码注释
name    RTC_ConfigTime.
fun     Calendar value read from Shadow register.
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.When the user does not need to configure this
        parameter, note that NULL can be passed in.
            - 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
void RTC_GetTime(uint32_t RTC_Format, RTC_TimeType* RTC_TimeStruct)获取 RTC 当前时间。
源码注释
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)获取 RTC 当前日历亚秒值。
源码注释
name    RTC_GetSubSecond.
fun     Gets the RTC current Calendar Subseconds value.
return  RTC current Calendar Subseconds value.
void RTC_DateStructInit(RTC_DateType* RTC_DateStruct)将 RTC_DateStruct 的每个成员填充为默认值(星期一,1 月 01 日 xx00)。
源码注释
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)设置 RTC 日历当前日期。
源码注释
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,note that NULL can be passed in.
            - 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)获取 RTC 当前日期。
源码注释
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_DateType : RTC_DateStruct pointer to a RTC_DateType structure that will
                       contain the returned current date configuration.
return  none
void RTC_ConfigOutputType(uint32_t RTC_OutputType)配置 RTC 输出引脚模式。
源码注释
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_SetAlarm(uint32_t RTC_Format, uint32_t RTC_Alarm, RTC_AlarmType* RTC_AlarmStruct)设置指定的 RTC 闹钟。
源码注释
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)将 RTC_AlarmStruct 的每个成员填充为默认值(时间 = 00h:00mn:00sec / 日期 = 当月第 1 天 / 掩码 = 所有字段均被屏蔽)。
源码注释
name    RTC_AlarmStructInit.
fun     Fills each RTC_AlarmStruct member with its default value
        (Time = 00h:00mn:00sec / Date = 1st day of the month/Mask =
        all 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)获取 RTC 闹钟值与掩码。
源码注释
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)使能或禁止指定的 RTC 闹钟。
源码注释
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
void RTC_ConfigAlarmSubSecond(uint32_t RTC_Alarm, uint32_t RTC_AlarmSubSecondValue, uint32_t RTC_AlarmSubSecondMask)配置 RTC 闹钟 A/B 的亚秒值与掩码。
源码注释
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)获取 RTC 闹钟亚秒值。
源码注释
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(uint32_t RTC_WakeUpClock)配置 RTC 唤醒时钟源。
源码注释
name    RTC_ConfigWakeUpClock.
fun     Configures the RTC Wakeup clock source.
param   RTC_WakeUpClock : RTC_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)配置 RTC 唤醒计数器。
源码注释
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)返回 RTC 唤醒定时器计数值。
源码注释
name    RTC_GetWakeUpCounter.
fun     Returns the RTC WakeUp timer counter value.
param   none
return  The RTC WakeUp Counter value.
ErrorStatus RTC_EnableWakeUp(FunctionalState Cmd)使能或禁止 RTC 唤醒定时器。
源码注释
name    RTC_EnableWakeUp
fun     Enables or disables the RTC WakeUp timer.
param  Cmd :
          - ENABLE
          - DISABLE
return  ErrorStatus :
            - SUCCESS: RTC wakeup configured succeed
            - ERROR:   RTC wakeup configured failed
void RTC_ConfigDayLightSaving(uint32_t RTC_DayLightSaving, uint32_t RTC_StoreOperation)在当前时间上增加或减少一小时。
源码注释
name    RTC_ConfigDayLightSaving
fun     Adds or substract one hour from the current time.
param   RTC_DayLightSaving : the value of hour adjustment.
            - RTC_DAYLIGHT_SAVING_SUB1H : Substract one hour (winter time).
            - RTC_DAYLIGHT_SAVING_ADD1H : Add one hour (summer time).
param   RTC_StoreOperation : Specifies the value to be written in the BCK bit
        in CTRL register to store the operation.
            - RTC_STORE_OPERATION_RESET :  BCK Bit Reset.
            - RTC_STORE_OPERATION_SET : BCK Bit Set.
return  none
uint32_t RTC_GetStoreOperation(void)返回 RTC 夏令时存储操作。
源码注释
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)配置 RTC 输出源。
源码注释
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 ALRAF/ALRBF/WUTF is high (depending on OSEL).
            - RTC_OUTPOL_LOW : The output pin is low when the ALRAF/ALRBF/WUTF is high (depending on OSEL).
return  none
void RTC_EnableOutput2(FunctionalState Cmd)使能或禁止 RTC 输出 2。
源码注释
name    RTC_EnableOutput2
fun     Enable or disable the RTC output2 .
param   Cmd :
          - ENABLE
          - DISABLE
return  none
void RTC_EnableTampOutput(FunctionalState Cmd)使能或禁止 RTC 篡改输出。
源码注释
name    RTC_EnableTampOutput
fun     Enable or disable the RTC tamper output .
param   Cmd :
          - ENABLE
          - DISABLE
return  none
void RTC_EnableCalibOutput(FunctionalState Cmd)使能或禁止通过相应引脚输出 RTC 校准时钟。
源码注释
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)配置校准引脚输出(RTC_CALIB)的选择(1Hz 或 256Hz)。
源码注释
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_SmouthCalibMinusPulsesValue)配置平滑校准设置。
源码注释
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 periode is 32s.
            - SMOOTH_CALIB_16SEC : The smooth calibration periode is 16s.
            - SMOOTH_CALIB_8SEC  : The smooth calibartion periode is 8s.
param   RTC_SmoothCalibPlusPulses : Set or reset the CALP bit.
            - RTC_SMOOTH_CALIB_PLUS_PULSES_SET : Add one RTCCLK puls every 2**11 pulses.
            - RTC_SMOOTH_CALIB_PLUS_PULSES_RESET : No RTCCLK pulses are added.
param   RTC_SmouthCalibMinusPulsesValue : Set the value of CALM[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
void RTC_EnableTimeStamp(uint32_t RTC_TimeStampEdge, FunctionalState Cmd)按指定的时间戳引脚触发边沿使能或禁止 RTC 时间戳功能。
源码注释
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)获取 RTC 时间戳值与掩码。
源码注释
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)获取 RTC 时间戳亚秒值。
源码注释
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)配置同步移位控制设置。
源码注释
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_SUB1S_DISABLE : Add one second to the clock calendar.
            - RTC_SHIFT_SUB1S_ENABLE : No effect.
param   RTC_ShiftSubFS : Select the number of Second Fractions to Substitute.
          This parameter can be one 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)使能或禁止指定的 RTC 中断。
源码注释
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)检查指定的 RTC 标志是否置位。
源码注释
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  : RECALPF event flag.
          - RTC_FLAG_TAMP3F  : Tamp3 detect flag.
          - RTC_FLAG_TAMP2F  : Tamp2 detect flag.
          - RTC_FLAG_TAMP1F  : Tamp1 detect 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)清除 RTC 的标志。
源码注释
name    RTC_ClrFlag
fun     Clears the RTC's flags.
param   RTC_FLAG : RTC_FLAG specifies the RTC flag to clear.
          - RTC_FLAG_TAMP3F  : Tamp3 detect flag.
          - RTC_FLAG_TAMP2F  : Tamp2 detect flag.
          - RTC_FLAG_TAMP1F  : Tamp1 detect 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_RSYF    : Registers Synchronized flag.
return  none
INTStatus RTC_GetITStatus(uint32_t RTC_INT)检查指定的 RTC 中断是否发生。
源码注释
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_TAMP3 : Tamper3 interrupt.
          - RTC_INT_TAMP2 : Tamper2 interrupt.
          - RTC_INT_TAMP1 : Tamper1 interrupt.
          - 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)清除 RTC 的中断挂起位。
源码注释
name    RTC_ClrIntPendingBit
fun     Clears the RTC's interrupt pending bits.
param   RTC_INT : specifies the RTC interrupt pending bit to clear.
          - RTC_INT_TAMP3 : Tamper3 interrupt.
          - RTC_INT_TAMP2 : Tamper2 interrupt.
          - RTC_INT_TAMP1 : Tamper1 interrupt.
          - 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
void RTC_TamperTriggerConfig(uint32_t RTC_Tamper, uint32_t RTC_TamperTrigger)配置所选篡改引脚的边沿。
源码注释
name    RTC_TamperTriggerConfig
fun     Configures the select Tamper pin edge.
param   RTC_Tamper: Selected tamper pin.
          - RTC_TAMPER_1: Select Tamper 1.
          - RTC_TAMPER_2: Select Tamper 2.
          - RTC_TAMPER_3: Select Tamper 3.
param   RTC_TamperTrigger: Specifies the trigger on the tamper pin that stimulates tamper event.
          - RTC_TamperTrigger_RisingEdge: Rising Edge of the tamper pin causes tamper event.
          - RTC_TamperTrigger_FallingEdge: Falling Edge of the tamper pin causes tamper event.
          - RTC_TamperTrigger_LowLevel: Low Level of the tamper pin causes tamper event.
          - RTC_TamperTrigger_HighLevel: High Level of the tamper pin causes tamper event.
return  none
void RTC_TamperCmd(uint32_t RTC_Tamper, FunctionalState NewState)使能或禁止指定的篡改检测。
源码注释
name    RTC_TamperCmd
fun     Enables or disables the specified Tamper detection.
param   RTC_Tamper: Selected tamper pin.
          - RTC_TAMPER_1: Select Tamper 1.
          - RTC_TAMPER_2: Select Tamper 2.
          - RTC_TAMPER_3: Select Tamper 3.
param  NewState :
          - ENABLE
          - DISABLE
return  none
void RTC_TamperFilterConfig(uint32_t RTC_TamperFilter)配置篡改滤波。
源码注释
name    RTC_TamperFilterConfig
fun     Configures the Tampers Filter.
param   RTC_TamperFilter: Selected tamper pin.
            - RTC_TamperFilter_Disable: Tamper filter is disabled.
            - RTC_TamperFilter_2Sample: Tamper is activated after 2 consecutive samples at the active level.
            - RTC_TamperFilter_4Sample: Tamper is activated after 4 consecutive samples at the active level.
            - RTC_TamperFilter_8Sample: Tamper is activated after 8 consecutive samples at the active level.
return  none
void RTC_TamperSamplingFreqConfig(uint32_t RTC_TamperSamplingFreq)配置篡改采样频率。
源码注释
name    RTC_TamperSamplingFreqConfig
fun     Configures the Tampers Sampling Frequency.
param   RTC_TamperSamplingFreq: Selected tamper pin.
            - RTC_TamperSamplingFreq_RTCCLK_Div32768
            - RTC_TamperSamplingFreq_RTCCLK_Div16384
            - RTC_TamperSamplingFreq_RTCCLK_Div8192
            - RTC_TamperSamplingFreq_RTCCLK_Div4096
            - RTC_TamperSamplingFreq_RTCCLK_Div2048
            - RTC_TamperSamplingFreq_RTCCLK_Div1024
            - RTC_TamperSamplingFreq_RTCCLK_Div512
            - RTC_TamperSamplingFreq_RTCCLK_Div256
return  none
void RTC_TamperPinsPrechargeDuration(uint32_t RTC_TamperPrechargeDuration)配置篡改引脚输入预充电时长。
源码注释
name    RTC_TamperPinsPrechargeDuration
fun     Configures the Tampers Pins input Precharge Duration.
param   RTC_TamperPrechargeDuration: Selected tamper pin.
            - RTC_TamperPrechargeDuration_1RTCCLK
            - RTC_TamperPrechargeDuration_2RTCCLK
            - RTC_TamperPrechargeDuration_4RTCCLK
            - RTC_TamperPrechargeDuration_8RTCCLK
return  none
void RTC_TimeStampOnTamperDetectionCmd(FunctionalState NewState)即使篡改控制寄存器中的 TSEN 位被复位,时间戳仍然有效或无效。
源码注释
name    RTC_TimeStampOnTamperDetectionCmd
fun     The timestamp is valid or invalid even the TSEN bit in tamper control register is reset.
param   NewState :
          - ENABLE
          - DISABLE
return  none
void RTC_TamperPullUpCmd(FunctionalState NewState)使能或禁止篡改引脚预充电。
源码注释
name    RTC_TamperPullUpCmd
fun     Enables or disables the Precharge of Tamper pin.
param   NewState :
          - ENABLE
          - DISABLE
return  none
void RTC_TamperIECmd(uint32_t TAMPxIE, FunctionalState NewState)使能或禁止篡改中断。
源码注释
name    RTC_TamperIECmd
fun     Enables or disables the Tamper interrupt.
param   TAMPxIE: Selected tamper number.
            - RTC_TAMPER1_INT
            - RTC_TAMPER2_INT
            - RTC_TAMPER3_INT
param  NewState :
          - ENABLE
          - DISABLE
return  none
void RTC_TamperTAMPTSCmd(FunctionalState NewState)即使篡改控制寄存器中的 TSEN 位被复位,时间戳仍然有效或无效。
源码注释
name    RTC_TamperTAMPTSCmd
fun     The timestamp is valid or invalid even the TSEN bit in tamper control register is reset.
param   NewState :
          - ENABLE
          - DISABLE
return  none
void RTC_EnableTampErase(uint32_t RTC_Tamper_Erase, FunctionalState NewState)使能或禁止篡改事件擦除备份寄存器。
源码注释
name    RTC_EnableTampErase
fun     Enables or disables the tamper event erase backup register.
param   RTC_Tamper: Selected tamper pin.
          - RTC_TAMPER_ERASE_1: Select Tamper 1 erase backup register.
          - RTC_TAMPER_ERASE_2: Select Tamper 2 erase backup register.
          - RTC_TAMPER_ERASE_3: Select Tamper 3 erase backup register.
param  NewState :
          - ENABLE
          - DISABLE
return  none
void RTC_BKUPRgWrite(uint8_t register_num, uint32_t Data)向备份寄存器写入数据。
源码注释
name    RTC_BKUPRgWrite
fun     Write data to backup register.
param   register_num: register_num value can be from 1 to 20
param   Data : Data write to backup register
return  none
uint32_t RTC_BKUPRgRead(uint8_t register_num)从备份寄存器读取数据。
源码注释
name    RTC_BKUPRgRead
fun     Read data from backup register.
param   register_num: register_num value can be from 1 to 20
param   Data : Data write to backup register
return  none

5.23.3 Demo 示例说明

本节说明 RTC 的 7 个示例:Alarm、AlarmSubsecond、Calendar、RtcAutoWakeUp、RtcBKP、Tamper、TimeStamp;每个示例给出工程目录、数据流向、说明表与核心代码解读。

5.23.3.1 Alarm 闹钟中断

工程目录: projects/n32h49x_EVAL/examples/RTC/Alarm/

初始化串口→写入默认日期、时间与闹钟 A→选择 LSE 并配置预分频→使能闹钟 A 与 EXTI17→闹钟到时由中断服务程序打印时间并翻转 PC13

项目 源码解读
功能 使用 RTC 闹钟 A,在配置的星期、日期、小时与分钟匹配时产生中断;
中断服务程序打印当前时间并翻转 PC13 输出电平。
源码组成 src/main.c:主流程与首次配置分支;
src/User_RTC_Config.c:时钟源、日历、闹钟配置与显示函数;
inc/User_RTC_Config.h:上述函数与结构体的声明;
src/n32h49x_it.c、inc/n32h49x_it.h:闹钟中断服务程序 RTCAlarm_IRQHandler;
readme.txt:功能与使用说明;
MDK-ARM/、EWARM/:Keil 与 IAR 工程。
关键配置 RTC 时钟源为 LSE;
同步预分频 SynchPrediv=0xFF、异步预分频 AsynchPrediv=0x7F,24 小时格式;
默认时间 4:22:55,日期为星期 4、11 月 16 日、年份 23;
闹钟 A 为 4:23:00,RTC_ALARM_SEL_WEEKDAY_DATE,DateWeekValue=16,掩码 RTC_ALARMMASK_WEEKDAY、RTC_ALARMMASK_HOURS 与 RTC_ALARMMASK_MINUTES;
闹钟输出为推挽、RTC_OUTPUT_ALA、高电平有效;
串口 USART1(PA9/PA10,115200)。
程序与数据路径 main 调用 RTC_DateAndTimeDefaultVale 填入默认值,并使能 PWR 时钟与备份域访问;
RTC_CLKSourceConfig 选择 LSE 并配置 RTC 时钟;
备份寄存器 1 若不是哨兵值 0xA5A5,依次调用 RTC_PrescalerConfig、RTC_DateRegulate、RTC_TimeRegulate 与 RTC_AlarmRegulate 并写回哨兵值;
随后配置闹钟输出并调用 EXTI17_RTCAlarm_Configuration;
闹钟到时后 RTCAlarm_IRQHandler 清标志并调用 RTC_TimeShow。
主要 API RTC_CLKSourceConfig、RTC_PrescalerConfig、RTC_Init、RTC_SetDate、RTC_ConfigTime、RTC_SetAlarm、RTC_ConfigInt、RTC_EnableAlarm、RTC_ConfigOutput、RTC_BKUPRgWrite
验证方法 烧录并复位后串口打印初始化与闹钟配置信息;
到达配置时间(默认间隔 1 分钟)时打印当前时间并翻转 PC13。
使用提示 本示例用备份寄存器 1 中的 0xA5A5 哨兵值避免每次复位都重新配置时间;
需要重写默认时间与闹钟时,先清除该备份寄存器;
闹钟输出引脚为 PC13,只有在打开备份域访问后才能配置;
开发环境为 N32H497ZGL7_EVB V1.0 上的 KEIL MDK-ARM V5.34 或 IAR EWARM 8.50.1。
核心代码解读与移植

示例用备份寄存器作为“首次配置”标志:只在首次上电时写入日期、时间与闹钟,复位后沿用备份域中正在运行的数值。

数据路径: RTC_DateAndTimeDefaultVale -> RTC_CLKSourceConfig -> RTC_PrescalerConfig -> RTC_DateRegulate/RTC_TimeRegulate -> RTC_AlarmRegulate -> EXTI17_RTCAlarm_Configuration -> RTCAlarm_IRQHandler

1. 用备份寄存器作首次配置标志。 main 读取备份寄存器 1,仅当其内容不是 0xA5A5 时才重新配置日历与闹钟,随后把哨兵值写回。

src/main.csrc/main.c · main
    if(SUCCESS==RTC_CLKSourceConfig(RTC_CLK_SRC_TYPE_LSE, true, false))
    {
        if (USER_WRITE_BKP_DAT1_DATA != RTC_BKUPRgRead(1))
        {
           RTC_PrescalerConfig();
           /* RTC date time and alarm regulate*/
           RTC_DateRegulate();
           RTC_TimeRegulate();
           RTC_AlarmRegulate(RTC_A_ALARM);
           RTC_BKUPRgWrite(1, USER_WRITE_BKP_DAT1_DATA);
           log_info("\r\n RTC Init Success\r\n");
        }
    }

2. 配置预分频与 24 小时格式。 RTC_PrescalerConfig 把异步预分频、同步预分频与小时格式写入 RTC_InitType 后调用 RTC_Init;LSE 下的预分频取值在时钟配置函数中给出。

src/User_RTC_Config.csrc/User_RTC_Config.c · RTC_PrescalerConfig
void RTC_PrescalerConfig(void)
{
    /* Configure the RTC data register and RTC prescaler */
    RTC_InitStructure.RTC_AsynchPrediv = AsynchPrediv;
    RTC_InitStructure.RTC_SynchPrediv  = SynchPrediv;
    RTC_InitStructure.RTC_HourFormat   = RTC_24HOUR_FORMAT;
    /* Check on RTC init */
    if (RTC_Init(&RTC_InitStructure) == ERROR)
    {
        log_info("\r\n //******* RTC Prescaler Config failed **********// \r\n");
    }
}
src/User_RTC_Config.csrc/User_RTC_Config.c · RTC_CLKSourceConfig
        SynchPrediv  = 0xFF; // 32.768KHz
        AsynchPrediv = 0x7F; // value range: 0-7F

3. 写入闹钟并使能其中断。 RTC_AlarmRegulate 先失能闹钟,写入时间、日期模式与掩码,调用 RTC_SetAlarm,再使能 RTC_INT_ALRA 并重新使能闹钟。

src/User_RTC_Config.csrc/User_RTC_Config.c · RTC_AlarmRegulate
    RTC_AlarmStructure.DateWeekValue = RTC_AlarmDefault.DateWeekValue;
    RTC_AlarmStructure.DateWeekMode = RTC_AlarmDefault.DateWeekMode;
    RTC_AlarmStructure.AlarmMask = RTC_AlarmDefault.AlarmMask;
    /* Configure the RTC Alarm A register */
    RTC_SetAlarm(RTC_FORMAT_BIN, RTC_Alarm, &RTC_AlarmStructure);
    printf("\n\r>> !! RTC Set Alarm_X success. !! <<\n\r");
    if (RTC_Alarm == RTC_A_ALARM)
    {
        /* Enable the RTC Alarm A Interrupt */
        RTC_ConfigInt(RTC_INT_ALRA, ENABLE);
        RTC_AlarmShow(1);
    }
    else
    {
        /* Enable the RTC Alarm B Interrupt */
        RTC_ConfigInt(RTC_INT_ALRB, ENABLE);
        RTC_AlarmShow(2);
    }
    /* Enable the alarm   */
    RTC_EnableAlarm(RTC_Alarm, ENABLE);
    return SUCCESS;

4. 中断服务程序打印时间。 闹钟到时后 RTCAlarm_IRQHandler 清除 EXTI17 与 RTC_INT_ALRA 挂起位并打印当前时间。

src/n32h49x_it.csrc/n32h49x_it.c · RTCAlarm_IRQHandler
void RTCAlarm_IRQHandler(void)
{
    EXTI_ClrITPendBit(EXTI_LINE17);
    if (RTC_GetITStatus(RTC_INT_ALRA) != RESET)
    {
       RTC_ClrIntPendingBit(RTC_INT_ALRA);
       RTC_TimeShow();
    }
}

对应源码: src/main.c、src/User_RTC_Config.c、src/n32h49x_it.c

5.23.3.2 AlarmSubsecond 亚秒闹钟

工程目录: projects/n32h49x_EVAL/examples/RTC/AlarmSubsecond/

初始化串口→写入默认日期、时间与闹钟 A→配置闹钟 A 亚秒掩码→使能闹钟中断与 EXTI17→亚秒匹配时中断服务程序置标志并翻转 PC13

项目 源码解读
功能 在闹钟 A 基础上增加亚秒比较:RTC_ConfigAlarmSubSecond 设置亚秒值与掩码,亚秒匹配时中断触发并打印时间。
源码组成 src/main.c:主流程、亚秒配置与主循环标志判断;
src/User_RTC_Config.c:时钟源、日历与闹钟配置函数;
inc/User_RTC_Config.h:上述函数与结构体的声明;
src/n32h49x_it.c、inc/n32h49x_it.h:中断服务程序 RTCAlarm_IRQHandler;
readme.txt:功能与使用说明;
MDK-ARM/、EWARM/:Keil 与 IAR 工程。
关键配置 RTC 时钟源为 LSE,同步/异步预分频 0xFF/0x7F,24 小时格式;
闹钟 A 为 4:23:00;
RTC_ConfigAlarmSubSecond(RTC_A_ALARM, 128, RTC_SUBS_MASK_SS14_7) 把亚秒比较放在 SS[14:7];
闹钟输出为推挽、RTC_OUTPUT_ALA、高电平有效;
串口 USART1(PA9/PA10,115200)。
程序与数据路径 main 与 Alarm 示例相同,但首次配置分支额外调用 RTC_ConfigAlarmSubSecond 设置亚秒值与掩码;
使能 EXTI17 后进入 while(1) 轮询 RTC_Time_Out_Flag;
中断服务程序打印时间并置位 RTC_Time_Out_Flag,主循环见到标志后打印 “500ms Alarm Wakeup”。
主要 API RTC_CLKSourceConfig、RTC_PrescalerConfig、RTC_SetAlarm、RTC_ConfigAlarmSubSecond、RTC_ConfigInt、RTC_EnableAlarm、RTC_ConfigOutput、RTC_BKUPRgWrite
验证方法 复位后串口打印配置信息;
亚秒匹配时约每 500ms 打印一次当前时间并翻转 PC13;
主循环见到标志后打印 “500ms Alarm Wakeup”。
使用提示 亚秒匹配要求预分频配置满足用户手册对亚秒字段有效性的规定;
亚秒值 128 对应 500ms,由 (32768/128) 的计数频率推算;
其余首次配置与显示逻辑与 Alarm 示例相同。
核心代码解读与移植

在闹钟 A 之上,RTC_ConfigAlarmSubSecond 决定亚秒比较使用哪段位域,把闹钟从秒级细化到亚秒级。

数据路径: RTC_ConfigAlarmSubSecond -> RTC_DateRegulate/RTC_TimeRegulate -> RTC_AlarmRegulate -> EXTI17_RTCAlarm_Configuration -> RTCAlarm_IRQHandler 置位 RTC_Time_Out_Flag -> 主循环打印

1. 首次配置时写入亚秒比较值。 除时、分、秒外,闹钟 A 还配置亚秒值与掩码;注释给出 128 与 500ms 的关系。

src/main.csrc/main.c · main
        if (USER_WRITE_BKP_DAT1_DATA != RTC_BKUPRgRead(1))
        {
           RTC_PrescalerConfig();
           /* ALRMASS Value(128) = 500ms / (1 / (32768/128)) */
           RTC_ConfigAlarmSubSecond(RTC_A_ALARM, 128, RTC_SUBS_MASK_SS14_7);
           /* RTC date time and alarm regulate*/
           RTC_DateRegulate();
           RTC_TimeRegulate();
           RTC_AlarmRegulate(RTC_A_ALARM);
           RTC_BKUPRgWrite(1, USER_WRITE_BKP_DAT1_DATA);
           log_info("\r\n RTC Init Success\r\n");
        }

2. 主循环等待中断服务程序置起的标志。 中断服务程序只置标志,打印放在主循环中完成,避免在中断里长时间输出。

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");
        }
    }

3. 中断服务程序置起软件标志。 与 Alarm 示例相比,中断服务程序在打印时间后额外置位 RTC_Time_Out_Flag。

src/n32h49x_it.csrc/n32h49x_it.c · RTCAlarm_IRQHandler
void RTCAlarm_IRQHandler(void)
{
    EXTI_ClrITPendBit(EXTI_LINE17);
    if (RTC_GetITStatus(RTC_INT_ALRA) != RESET)
    {
        RTC_ClrIntPendingBit(RTC_INT_ALRA);
        RTC_TimeShow();
        RTC_Time_Out_Flag = true;
    }
}

对应源码: src/main.c、src/n32h49x_it.c

5.23.3.3 Calendar 日历

工程目录: projects/n32h49x_EVAL/examples/RTC/Calendar/

初始化串口→写入默认日期与时间→在 PC13 输出 1Hz 校准信号→用外部连线把 1Hz 信号回灌到 PA7→EXTI7 中断服务程序打印日期与时间

项目 源码解读
功能 配置日历并输出 1Hz 校准信号;
该信号由外部回灌到 PA7,EXTI7 中断服务程序每秒打印一次当前日期与时间。
源码组成 src/main.c:EXTI_PA7_Configuration 与主流程;
src/User_RTC_Config.c:时钟源、日历与预分频配置函数;
inc/User_RTC_Config.h:上述函数与结构体的声明;
src/n32h49x_it.c、inc/n32h49x_it.h:中断服务程序 EXTI9_5_IRQHandler;
readme.txt:功能与使用说明;
MDK-ARM/、EWARM/:Keil 与 IAR 工程。
关键配置 RTC 时钟源为 LSE;
首次配置分支在配置预分频、日期与时间前调用 RTC_DeInit;
校准输出为 RTC_CALIB_OUTPUT_1HZ、推挽、已使能;
PA7 配置为输入并映射到 EXTI_LINE7,上升沿,NVIC 通道 EXTI9_5_IRQn;
串口 USART1(PA9/PA10,115200)。
程序与数据路径 main 调用 RTC_DateAndTimeDefaultVale 并使能 PWR 与 BKP 时钟;
首次配置分支依次执行 RTC_DeInit、RTC_PrescalerConfig、RTC_DateRegulate 与 RTC_TimeRegulate,并写入备份寄存器 1;
随后调用 RTC_ConfigCalibOutput、RTC_ConfigOutputType 与 RTC_EnableCalibOutput 输出 1Hz;
EXTI_PA7_Configuration 使能 EXTI7;
EXTI9_5_IRQHandler 判断 EXTI_LINE7 后打印日期与时间。
主要 API RTC_DeInit、RTC_CLKSourceConfig、RTC_PrescalerConfig、RTC_SetDate、RTC_ConfigTime、RTC_ConfigCalibOutput、RTC_ConfigOutputType、RTC_EnableCalibOutput、RTC_GetDate、RTC_GetTime
验证方法 复位后串口打印初始化信息;
把 PC13 上的 1Hz 校准信号接到 PA7,串口每秒打印一次日期与时间。
使用提示 本示例需要在 PC13 与 PA7 之间外接导线以产生秒中断;
首次配置分支在配置日历前调用 RTC_DeInit,与 Alarm 示例的增量配置方式不同;
EXTI 中断服务程序读取后需清除 EXTI_LINE7 挂起位。
核心代码解读与移植

示例把 RTC 的 1Hz 校准输出引到 PA7,用普通 EXTI 中断实现“每秒打印”,不占用 RTC 中断。

数据路径: RTC_DeInit -> RTC_PrescalerConfig -> RTC_DateRegulate/RTC_TimeRegulate -> RTC_ConfigCalibOutput/RTC_EnableCalibOutput -> EXTI_PA7_Configuration -> EXTI9_5_IRQHandler -> RTC_DateShow/RTC_TimeShow

1. 把 PA7 配置为 EXTI 输入。 PA7 设为输入并映射到 EXTI7,上升沿,NVIC 通道 EXTI9_5_IRQn。

src/main.csrc/main.c · EXTI_PA7_Configuration
void EXTI_PA7_Configuration(void)
{
    GPIO_InitType GPIO_InitStructure;
    EXTI_InitType EXTI_InitStructure;
    NVIC_InitType NVIC_InitStructure;
    GPIO_InitStruct(&GPIO_InitStructure);
    /* Enable the AFIO Clock */
    RCC_EnableAHB1PeriphClk(RCC_AHB_PERIPHEN_GPIOA | RCC_APB2_PERIPHEN_AFIO, ENABLE);
    /* Select the GPIO - configuration used for floating in */
    GPIO_InitStructure.Pin        = GPIO_PIN_7;
    GPIO_InitStructure.GPIO_Mode  = GPIO_MODE_INPUT;
    GPIO_InitPeripheral(GPIOA, &GPIO_InitStructure);
    GPIO_ConfigEXTILine(EXTI_LINE_SOURCE7, GPIOA_PORT_SOURCE, GPIO_PIN_SOURCE7);
    /* Configure Button EXTI line */
    EXTI_InitStructure.EXTI_Line    = EXTI_LINE7;
    EXTI_InitStructure.EXTI_Mode    = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_InitPeripheral(&EXTI_InitStructure);

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    /* Enable and set Button EXTI Interrupt to the lowest priority */
    NVIC_InitStructure.NVIC_IRQChannel                   = EXTI9_5_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 0x01;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

2. 首次配置与校准输出。 首次配置分支用 RTC_DeInit 复位并写入日历,然后把校准输出设为 1Hz 并使能。

src/main.csrc/main.c · main
        if (USER_WRITE_BKP_DAT1_DATA != RTC_BKUPRgRead(1))
        {
           RTC_DeInit();
           RTC_PrescalerConfig();
           log_info("\r\n RTC configured....");
           /* Adjust time by values entered by the user on the hyperterminal */
           RTC_DateRegulate();
           RTC_TimeRegulate();
           RTC_BKUPRgWrite(1, USER_WRITE_BKP_DAT1_DATA);
           log_info("\r\n RTC Init Success\r\n");
       }
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);
    /* Calibrate output enable*/
    RTC_EnableCalibOutput(ENABLE);

3. EXTI7 中断服务程序打印日期与时间。 中断服务程序判断 EXTI_LINE7 后打印日期与时间,再清除挂起位。

src/n32h49x_it.csrc/n32h49x_it.c · EXTI9_5_IRQHandler
void EXTI9_5_IRQHandler(void)
{
    if (EXTI_GetStatusFlag(EXTI_LINE7) != RESET)
    {
       /* Display the current Date on the Hyperterminal */
       RTC_DateShow();
       RTC_TimeShow();
       /* Clear the UP Button EXTI line pending bit */
       EXTI_ClrITPendBit(EXTI_LINE7);
    }
}

对应源码: src/main.c、src/n32h49x_it.c

5.23.3.4 RtcAutoWakeUp 周期唤醒

工程目录: projects/n32h49x_EVAL/examples/RTC/RtcAutoWakeUp/

初始化串口→写入默认日期与时间→选择唤醒时钟与计数器→使能唤醒中断与 EXTI20→每个唤醒周期由中断服务程序打印时间并驱动 PC13

项目 源码解读
功能 使用 RTC 唤醒定时器按固定周期自动唤醒;
每个周期 RTC_WKUP_IRQHandler 打印当前时间。
源码组成 src/main.c:delay、主流程与唤醒配置;
src/User_RTC_Config.c:时钟源、日历与预分频配置函数;
inc/User_RTC_Config.h:上述函数与结构体的声明;
src/n32h49x_it.c、inc/n32h49x_it.h:中断服务程序 RTC_WKUP_IRQHandler;
readme.txt:功能与使用说明;
MDK-ARM/、EWARM/:Keil 与 IAR 工程。
关键配置 RTC 时钟源为 LSE;
唤醒时钟为 RTC_WKUPCLK_CK_SPRE_16BITS,唤醒计数器为 4;
唤醒输出为 RTC_OUTPUT_WKUP、推挽、高电平有效;
EXTI20 为上升沿并映射到 RTC_WKUP_IRQn;
串口 USART1(PA9/PA10,115200)。
程序与数据路径 在 main 中,首次配置分支写入日历后调用 RTC_ConfigWakeUpClock 与 RTC_SetWakeUpCounter;
随后调用 EXTI20_RTCWKUP_Configuration 使能 EXTI20,调用 RTC_ConfigInt(RTC_INT_WUT, ENABLE) 使能唤醒中断,再调用 RTC_EnableWakeUp(ENABLE) 启动唤醒定时器;
最后配置 RTC_OUTPUT_WKUP 输出;
每个唤醒周期 RTC_WKUP_IRQHandler 清除 EXTI20 与 RTC_INT_WUT 并打印时间。
主要 API RTC_CLKSourceConfig、RTC_PrescalerConfig、RTC_ConfigWakeUpClock、RTC_SetWakeUpCounter、RTC_EnableWakeUp、RTC_ConfigInt、RTC_ConfigOutput、RTC_GetTime
验证方法 复位后串口打印初始化信息;
随后按唤醒周期定时打印当前时间,并在 PC13 输出唤醒脉冲。
使用提示 唤醒计数器为 4,与 CK_SPRE_16BITS 一起决定唤醒周期;
改变周期需同时调整唤醒时钟与计数器;
主流程无按键或外部激励,由唤醒定时器自行驱动;
RTC_EnableWakeUp 在主流程中调用两次,第二次调用确保中断与输出均保持使能。
核心代码解读与移植

示例不依赖外部激励:只配置唤醒时钟与计数器,让 RTC 唤醒定时器周期性产生中断。

数据路径: RTC_ConfigWakeUpClock -> RTC_SetWakeUpCounter -> EXTI20_RTCWKUP_Configuration -> RTC_ConfigInt -> RTC_EnableWakeUp -> RTC_WKUP_IRQHandler -> RTC_TimeShow

1. 提供一个毫秒延时函数。 示例自带一个循环计数延时,用于等待时钟稳定等场合。

src/main.csrc/main.c · delay
void delay(vu32 nCount)
{
    vu32 index = 0;
    for (index = (34000 * nCount); index != 0; index--)
    {
    }
}

2. 配置唤醒时钟与计数器。 首次配置分支写入日历后设置唤醒时钟与计数器,并写回备份寄存器哨兵值。

src/main.csrc/main.c · main
        if (USER_WRITE_BKP_DAT1_DATA != RTC_BKUPRgRead(1))
        {
           RTC_PrescalerConfig();
           /* Adjust time by values entered by the user on the hyperterminal */
           RTC_DateRegulate();
           RTC_TimeRegulate();
           /* wake up clock select */
           RTC_ConfigWakeUpClock(RTC_WKUPCLK_CK_SPRE_16BITS);
           /* wake up timer value */
           RTC_SetWakeUpCounter(4);
           RTC_BKUPRgWrite(1, USER_WRITE_BKP_DAT1_DATA);
           log_info("\r\n RTC Init Success\r\n");
        }

3. 使能唤醒中断与输出。 清除 EXTI20 与 RTC_INT_WUT 后使能 EXTI20、唤醒中断与唤醒定时器,并在 PC13 上输出唤醒信号。

src/main.csrc/main.c · main
    EXTI_ClrITPendBit(EXTI_LINE20);
    EXTI20_RTCWKUP_Configuration(ENABLE);
    /* Enable the RTC Wakeup Interrupt */
    RTC_ClrIntPendingBit(RTC_INT_WUT);
    RTC_ConfigInt(RTC_INT_WUT, ENABLE);
    RTC_EnableWakeUp(ENABLE);
src/main.csrc/main.c · main
    RTC_ConfigOutputType(RTC_OUTPUT_PUSHPULL);
src/main.csrc/main.c · main
    RTC_ConfigOutput(RTC_OUTPUT_WKUP, RTC_OUTPOL_HIGH);
    RTC_EnableWakeUp(ENABLE);

对应源码: src/main.c、src/User_RTC_Config.c

5.23.3.5 RtcBKP 备份寄存器

工程目录: projects/n32h49x_EVAL/examples/RTC/RtcBKP/

使能 PWR 时钟与备份域访问→配置 LSE 与 RTC 时钟→依次写入 20 个备份寄存器→读回并打印以作比较

项目 源码解读
功能 演示 RTC 备份寄存器的读与写:向 20 个备份寄存器写入初始数据,再逐个读回并打印,以验证备份域数据保持。
源码组成 src/main.c:User_RTCBKP_Init 与写入、读回循环;
inc/User_RTCBKP_Config.h:BKP_DAT1~BKP_DAT20、BACKUP_REGISTER_SIZE 与 extern 数组声明;
inc/main.h、inc/n32h49x_it.h:公共声明;
readme.txt:功能与使用说明;
MDK-ARM/、EWARM/:Keil 与 IAR 工程。
关键配置 使能 PWR 时钟并调用 PWR_BackupAccessEnable(ENABLE) 打开备份域访问;
配置 LSE 作为 RTC 时钟源,写入前关闭 LSI,确保只开启一个时钟;
备份寄存器个数 BACKUP_REGISTER_SIZE 为 20;
串口 USART1(PA9/PA10,115200)。
程序与数据路径 main 先调用 User_RTCBKP_Init 配置时钟与备份域访问;
第一个循环用 RTC_BKUPRgWrite(i+1, Write_Backup_Datas[i]) 写入全部 20 个寄存器的测试数据;
第二个循环用 RTC_BKUPRgRead(i+1) 读回并用 printf 打印 BKP_DAT%u=%x;
打印结果与写入值人工比对。
主要 API RTC_BKUPRgWrite、RTC_BKUPRgRead、RTC_WaitForSynchro
验证方法 复位后串口打印 20 行 BKP_DATn=value;
把打印值与 Write_Backup_Datas 中的初值比对。
使用提示 断电期间备份寄存器保持需要 VBAT 供电;
只有完全断电内容才会丢失;
写入前必须执行 PWR_BackupAccessEnable(ENABLE),否则写入无效;
本示例无 RTC 中断,仅通过串口打印验证。
核心代码解读与移植

示例做两件事:打开备份域写访问并配置 RTC 时钟,然后成批写入并读回备份寄存器。

数据路径: User_RTCBKP_Init -> PWR_BackupAccessEnable -> RCC_ConfigRtcClk/RTC_WaitForSynchro -> RTC_BKUPRgWrite -> RTC_BKUPRgRead -> printf

1. 打开备份域并配置 RTC 时钟。 User_RTCBKP_Init 使能 PWR 时钟、打开备份域写访问,关闭 LSI,使能 LSE,并在其稳定后选作 RTC 时钟。

src/main.csrc/main.c · User_RTCBKP_Init
void User_RTCBKP_Init(void)
{
    RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPHEN_PWR, ENABLE);
    /* Allow access to RTC */
    PWR_BackupAccessEnable(ENABLE);
    RCC_EnableRtcClk(DISABLE);
    /* Enable the LSE OSC32_IN PC14
       LSI is turned off here to ensure that only one clock is turned on */
    RCC_EnableLsi(DISABLE);
    RCC_ConfigLse(RCC_LSE_ENABLE);
    while (RCC_GetFlagStatus(RCC_FLAG_LSERDF) == RESET){}
    RCC_ConfigRtcClk(RCC_RTCCLK_SRC_LSE);
    /* Enable the RTC Clock */
    RCC_EnableRtcClk(ENABLE);
    RTC_WaitForSynchro();
}

2. 成批写入并读回备份寄存器。 两个循环分别完成写入与读回,并把寄存器序号与内容标为 BKP_DAT%u=%x。

src/main.csrc/main.c · main
    uint8_t i =0;
    User_RTCBKP_Init();
    /* Initialize USART */
    log_init();
    log_info("\r\n RTC Init \r\n");
    for(i=0;i<BACKUP_REGISTER_SIZE;i++)
    {
       RTC_BKUPRgWrite(i+1, Write_Backup_Datas[i]);
    }
    for(i=0;i<BACKUP_REGISTER_SIZE;i++)
    {
       Read_Backup_Datas[i]=RTC_BKUPRgRead(i+1);
       printf("\r\n BKP_DAT%u=%x\r\n",i+1,(unsigned int)Read_Backup_Datas[i]);
    }

3. 备份寄存器个数与初值定义。 User_RTCBKP_Config.h 定义 20 个 BKP_DATn 序号宏与写入、读回循环使用的备份寄存器个数。

inc/User_RTCBKP_Config.hinc/User_RTCBKP_Config.h
#define  BKP_DAT1     ((uint16_t)0x0000)
#define  BKP_DAT2     ((uint16_t)0x0004)
#define  BKP_DAT3     ((uint16_t)0x0008)
#define  BKP_DAT4     ((uint16_t)0x000C)
#define  BKP_DAT5     ((uint16_t)0x0010)
#define  BKP_DAT6     ((uint16_t)0x0014)
#define  BKP_DAT7     ((uint16_t)0x0018)
#define  BKP_DAT8     ((uint16_t)0x001C)
#define  BKP_DAT9     ((uint16_t)0x0020)
#define  BKP_DAT10    ((uint16_t)0x0024)
inc/User_RTCBKP_Config.hinc/User_RTCBKP_Config.h
#define  BACKUP_REGISTER_SIZE        20

对应源码: src/main.c、inc/User_RTCBKP_Config.h

5.23.3.6 Tamper 篡改检测

工程目录: projects/n32h49x_EVAL/examples/RTC/Tamper/

初始化串口→配置 LSE 与预分频→配置 PC13 为篡改输入→设置触发、滤波、采样与预充电→使能篡改中断→篡改发生时由中断服务程序打印信息

项目 源码解读
功能 配置 RTC 篡改通道 1:以 PC13 作为篡改输入,设置触发方式、滤波、采样频率与预充电时长;
篡改事件发生时中断打印信息。
源码组成 src/main.c:TamperInputIoInit、TAMPER_INT_Configuration 与主流程;
src/User_RTC_Config.c:时钟源与预分频配置函数;
inc/User_RTC_Config.h:上述函数与结构体的声明;
src/n32h49x_it.c、inc/n32h49x_it.h:中断服务程序 RTC_TAMPER_IRQHandler;
readme.txt:功能与使用说明;
MDK-ARM/、EWARM/:Keil 与 IAR 工程。
关键配置 RTC 时钟源为 LSE;
篡改输入为 PC13,配置为浮空输入;
触发方式 RTC_TamperTrigger_HighLevel,滤波 RTC_TamperFilter_2Sample;
采样频率 RTC_TamperSamplingFreq_RTCCLK_Div256,预充电 RTC_TamperPrechargeDuration_1RTCCLK;
EXTI19 上升沿映射到 RTC_TAMPER_IRQn;
串口 USART1(PA9/PA10,115200)。
程序与数据路径 main 使能 PWR 与 BKP 时钟并打开备份域访问,然后选择 LSE 后设置 RTC_PrescalerConfig 与备份寄存器哨兵值;
TamperInputIoInit 随后把 PC13 设为输入;
调用 RTC_TamperTriggerConfig 等函数设置触发、滤波、采样频率与预充电参数;
TAMPER_INT_Configuration 使能 EXTI19,清除 RTC_INT_TAMP1 后调用 RTC_TamperIECmd 与 RTC_TamperCmd 使能检测。
主要 API RTC_TamperTriggerConfig、RTC_TamperCmd、RTC_TamperFilterConfig、RTC_TamperSamplingFreqConfig、RTC_TamperPinsPrechargeDuration、RTC_TamperIECmd、RTC_GetITStatus、RTC_ClrIntPendingBit
验证方法 复位后串口打印初始化信息;
向 PC13 施加高电平触发篡改,串口打印 “RTC Tamper Interrupt”。
使用提示 边沿或电平触发需要外部上拉或下拉,避免浮空引脚误触发;
使能篡改检测前先清除 RTC_INT_TAMP1 挂起位;
中断服务程序读取状态后同时清除 EXTI19 与 RTC_INT_TAMP1。
核心代码解读与移植

篡改检测需先设置输入引脚与触发参数,再同时使能 EXTI 与 RTC 内部篡改中断;两条中断路径都要处理。

数据路径: TamperInputIoInit -> RTC_TamperTriggerConfig -> RTC_TamperFilterConfig/RTC_TamperSamplingFreqConfig/RTC_TamperPinsPrechargeDuration -> TAMPER_INT_Configuration -> RTC_TamperIECmd/RTC_TamperCmd -> RTC_TAMPER_IRQHandler

1. 配置篡改输入引脚。 TamperInputIoInit 使能 GPIOC 时钟并把 PC13 配置为输入。

src/main.csrc/main.c · TamperInputIoInit
void TamperInputIoInit(void)
{
    GPIO_InitType GPIO_InitStructure;
    GPIO_InitStruct(&GPIO_InitStructure);
    /* Enable the GPIO Clock */
    RCC_EnableAHB1PeriphClk(RCC_AHB_PERIPHEN_GPIOC, ENABLE);
    /* Configure the GPIO pin */
    GPIO_InitStructure.Pin        = GPIO_PIN_13;
    GPIO_InitStructure.GPIO_Mode  = GPIO_MODE_INPUT;
    GPIO_InitPeripheral(GPIOC, &GPIO_InitStructure);
}

2. 配置篡改参数并使能检测。 依次设置触发方式、滤波采样次数、采样频率与预充电时长,再使能 EXTI 与篡改中断。

src/main.csrc/main.c · main
    /*Configure Tamper GPIO trigger mode*/
    RTC_TamperTriggerConfig(RTC_TAMPER_1, RTC_TamperTrigger_HighLevel);
    /*Configure the valib number of scanning times*/
    RTC_TamperFilterConfig(RTC_TamperFilter_2Sample);
    /*Configure scanning frequence*/
    RTC_TamperSamplingFreqConfig(RTC_TamperSamplingFreq_RTCCLK_Div256);
    /*Configure precharge duration time*/
    RTC_TamperPinsPrechargeDuration(RTC_TamperPrechargeDuration_1RTCCLK);
src/main.csrc/main.c · main
    EXTI_ClrITPendBit(EXTI_LINE19);
    /*Configure tamper interruput,EXTI_LINE19*/
    TAMPER_INT_Configuration(ENABLE);
    RTC_ClrIntPendingBit(RTC_INT_TAMP1);
    /*Enable tamper interruput*/
    RTC_TamperIECmd(RTC_TAMPER1_INT, ENABLE);
    /*Enable tamper1 */
    RTC_TamperCmd(RTC_TAMPER_1, ENABLE);

3. 中断服务程序打印篡改信息。 在 RTC_INT_TAMP1 上,中断服务程序清除 EXTI19 与 RTC_INT_TAMP1 并打印信息。

src/n32h49x_it.csrc/n32h49x_it.c · RTC_TAMPER_IRQHandler
void RTC_TAMPER_IRQHandler(void)
{
    if (RTC_GetITStatus(RTC_INT_TAMP1) != RESET)
    {
       RTC_ClrIntPendingBit(RTC_INT_TAMP1);
       EXTI_ClrITPendBit(EXTI_LINE19);
       log_info("RTC Tamper Interrupt");
    }
}

对应源码: src/main.c、src/n32h49x_it.c

5.23.3.7 TimeStamp 时间戳

工程目录: projects/n32h49x_EVAL/examples/RTC/TimeStamp/

初始化串口→写入默认日期与时间→在 PC13 输出 1Hz 校准信号→把 1Hz 信号接入 PB8 触发时间戳→中断服务程序打印日期、时间与时间戳

项目 源码解读
功能 以 EXTI8 作为 RTC 时间戳触发源:1Hz 校准信号由 PC13 回灌到 PB8,每次触发记录并打印日期、时间与时间戳寄存器内容。
源码组成 src/main.c:EXTI_PB8_TimeStamp_Configuration、EXTI19_TAMPER_IRQn_Configuration 与主流程;
src/User_RTC_Config.c:时钟源、日历与预分频配置函数;
inc/User_RTC_Config.h:上述函数与结构体的声明;
src/n32h49x_it.c、inc/n32h49x_it.h:中断服务程序 RTC_TAMPER_IRQHandler;
readme.txt:功能与使用说明;
MDK-ARM/、EWARM/:Keil 与 IAR 工程。
关键配置 RTC 时钟源为 LSE;
校准输出为 RTC_CALIB_OUTPUT_1HZ、推挽、已使能;
时间戳触发源为 EXTI8(EXTI_RTCTimeStampSel(EXTI_TSSEL_LINE8)),PB8 为输入;
时间戳边沿为 RTC_TIMESTAMP_EDGE_FALLING;
EXTI19 上升沿映射到 RTC_TAMPER_IRQn,用于时间戳中断;
串口 USART1(PA9/PA10,115200)。
程序与数据路径 在 main 中首次配置写入日历与备份寄存器哨兵值;
随后配置 1Hz 校准输出;
EXTI_PB8_TimeStamp_Configuration 把 PB8 映射到时间戳触发源;
清除 RTC_FLAG_TISF 与 RTC_FLAG_TISOVF 后调用 RTC_EnableTimeStamp 与 RTC_ConfigInt(RTC_INT_TS, ENABLE);
时间戳中断服务程序 RTC_TAMPER_IRQHandler 打印日期、时间与时间戳并清除溢出标志。
主要 API RTC_CLKSourceConfig、RTC_PrescalerConfig、RTC_ConfigCalibOutput、RTC_EnableTimeStamp、RTC_ConfigInt、RTC_GetTimeStamp、RTC_GetTimeStampSubSecond、RTC_GetDate、RTC_GetTime
验证方法 复位后串口打印初始化信息;
把 PC13 上的 1Hz 校准信号接到 PB8,串口每秒打印一次日期、时间与时间戳并报告时间戳有效。
使用提示 时间戳溢出标志要与时间戳标志一起检查并清除,避免误读陈旧数据;
改变触发边沿前先复位时间戳使能位;
本示例用 EXTI8 作时间戳源、EXTI19 作中断线,需分别配置。
核心代码解读与移植

示例选择 EXTI8 作为时间戳触发源,从 PB8 的外部脉冲记录当前日历,并通过 EXTI19 中断读取时间戳寄存器。

数据路径: EXTI_PB8_TimeStamp_Configuration -> EXTI_RTCTimeStampSel -> RTC_EnableTimeStamp -> RTC_ConfigInt -> RTC_TAMPER_IRQHandler -> RTC_GetTimeStamp/RTC_GetTimeStampSubSecond

1. 把 PB8 映射到时间戳触发源。 EXTI_PB8_TimeStamp_Configuration 把 PB8 配置为输入,并把 EXTI8 连到 RTC 时间戳。

src/main.csrc/main.c · EXTI_PB8_TimeStamp_Configuration
void EXTI_PB8_TimeStamp_Configuration()
{
    GPIO_InitType GPIO_InitStructure;
    GPIO_InitStruct(&GPIO_InitStructure);
    RCC_EnableAHB1PeriphClk(RCC_AHB_PERIPHEN_GPIOB , ENABLE);
    /* Configure PB8 in input mode */
    GPIO_InitStructure.Pin = GPIO_PIN_8;
    GPIO_InitStructure.GPIO_Mode  = GPIO_MODE_INPUT;
    GPIO_InitPeripheral(GPIOB, &GPIO_InitStructure);
    /* Connect EXTI8 to RTC_TimeStamp */
    EXTI_RTCTimeStampSel(EXTI_TSSEL_LINE8);
    /* Connect EXTI8 Line to PB8 pin */
    GPIO_ConfigEXTILine(EXTI_LINE_SOURCE8, GPIOB_PORT_SOURCE, GPIO_PIN_SOURCE8);
}

2. 配置校准输出并使能时间戳。 主流程先输出 1Hz 校准信号,把 PB8 连到时间戳源,清除标志后在下降沿使能时间戳及其中断。

src/main.csrc/main.c · main
    /* Adjust time by values entered by the user on the hyperterminal */
    RTC_ConfigCalibOutput(RTC_CALIB_OUTPUT_1HZ);
    /* Calibrate output config,push pull */
    RTC_ConfigOutputType(RTC_OUTPUT_PUSHPULL);
    /* Calibrate output enable*/
    RTC_EnableCalibOutput(ENABLE);
    /* Configure EXTI PB8 pin  connected to RTC TimeStamp
    (while externally feeding PB8 with 1HZ signal output from PC13)
    */
    EXTI_PB8_TimeStamp_Configuration();
    EXTI_ClrITPendBit(EXTI_LINE19);
    EXTI19_TAMPER_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. 中断服务程序读取时间戳寄存器。 在 RTC_INT_TS 上,中断服务程序打印日期、时间与时间戳,并清除时间戳标志与溢出标志。

src/n32h49x_it.csrc/n32h49x_it.c · RTC_TAMPER_IRQHandler
void RTC_TAMPER_IRQHandler(void)
{
    EXTI_ClrITPendBit(EXTI_LINE19);
    if (RTC_GetITStatus(RTC_INT_TS) != RESET)
    {
        /* Every interval delay (1s) displays calendar and clock stamp register contents*/
        RTC_DateShow();
        RTC_TimeShow();
        RTC_TimeStampShow();
        RTC_ClrFlag(RTC_FLAG_TISF);
        RTC_ClrFlag(RTC_FLAG_TISOVF);
    }
}

对应源码: src/main.c、src/n32h49x_it.c

5.23.4 注意与排障

场景 检查与建议 来源
备份域写保护 必须在打开备份域写访问后写 RTC 寄存器,否则写入不生效;
调用 PWR_BackupAccessEnable(ENABLE) 置位 PWR 控制寄存器的 DBKP 位。
用户手册
进入初始化模式 进入初始化模式前要求 RTC_SUBS 的 SS[15:0] 不小于 2 且不等于预分频 DIVS[14:0];
进入初始化模式前先读一次 RTC_DATE 寄存器。
用户手册
BYPS 与预分频 BYPS 为 0 时 APB1 时钟必须不小于 RTC 时钟的 7 倍;
fAPB1 低于 7 倍 fRTCCLK 时必须把 BYPS 置 1。
用户手册
闹钟秒字段 仅当预分频 DIVS[14:0] 大于 3 时,闹钟秒字段才能比较并触发。 用户手册
唤醒定时器 唤醒计数器写入 0 会立即置位唤醒标志并产生一次唤醒事件,切勿误写 0。 用户手册
时间戳溢出 检测到时间戳标志 TISF 后,还要检查并清除溢出标志 TISOVF,避免使用陈旧的溢出时间戳数据。 用户手册
篡改中断 篡改标志 TPxMF 已置位时不得使能对应篡改中断,否则会立即进入中断。 用户手册
篡改引脚 采用边沿检测的篡改引脚需外接上拉或下拉,避免浮空引脚误触发。 用户手册
篡改与备份寄存器 篡改检测与 RTC 备份寄存器写入不应同时发生;
先完成备份寄存器写入再启动篡改检测。
用户手册
参考时钟检测 使用参考时钟检测时应把预分频 DIVS 配置为 0x00FF。 用户手册
时间戳触发边沿 改变时间戳触发边沿前必须先复位控制寄存器中的时间戳使能位 TSEN。 用户手册
STANDBY 唤醒 用 RTC 事件从 STANDBY 模式唤醒时,需使能 PWR 控制/状态寄存器的 WKUPRTCEN 位。 用户手册
国民技术开发套件文档中心

按芯片系列在线查阅国民技术 MCU 开发套件的芯片资料、SDK、驱动 API 与 Demo 示例说明。

© 2026 国民技术股份有限公司 版权所有粤ICP备11069485号本站使用不含 Cookie 的匿名访问统计