microcontrollerstm32f1

stm32f1 RTC Alarm


I'm using stm32f103RBT6 and I want to set RTC alarm event every one hour by using codes below

RTC_Alarm_Time.Alarm = 1;
HAL_RTC_GetTime(&hrtc,&RTC_Time,RTC_FORMAT_BIN);
RTC_Alarm_Time.AlarmTime.Hours=RTC_Time.Hours+1;
if(RTC_Alarm_Time.AlarmTime.Hours>23)
{                                           
    RTC_Alarm_Time.AlarmTime.Hours=0;   
}   
RTC_Alarm_Time.AlarmTime.Minutes=RTC_Time.Minutes;                       
RTC_Alarm_Time.AlarmTime.Seconds=RTC_Time.Seconds;  
HAL_RTC_SetAlarm_IT(&hrtc, &RTC_Alarm_Time, RTC_FORMAT_BIN);                

my problem is after hour 23 alarm comes at hour 1 and it skips hour 0. I think its because when i set alarm hour to 0 RTC date is still previous day. does anyone has any example of codes that i can make this Independent of date or any other way. Thankyou.


Solution

  • Updated Answer:

    There is a bug in your code. Your code sets RTC_Alarm_Time.AlarmTime.Hours=RTC_Time.Hours+1, and then checks for the hour rollover with if(RTC_Time.Hours>23). Note that RTC_Time.Hours was not incremented, rather RTC_Alarm_Time.AlarmTime.Hours was incremented. So when RTC_Time.Hours == 23, RTC_Alarm_Time.AlarmTime.Hours = 24, and RTC_Alarm_Time.AlarmTime.Hours will not be rolled over to 0 because RTC_Time.Hours is not greater than 23. Then the call to HAL_RTC_SetAlarm_IT() will fail because Hours = 24. You would have caught this if you were checking the return value of HAL_RTC_SetAlarm_IT().

    You can fix your code by changing the conditional like this.

    if(RTC_Alarm_Time.AlarmTime.Hours>23)
    

    Original Answer (would address the suspected problem on a STM32F4):

    I think you're right about it skipping hour 0 because the date is the previous day. You should ignore the date/day because you want an hourly alarm. And I think you can ignore the date/day by setting RTC_Alarm_Time.AlarmMask = RTC_ALARMMASK_DATEWEEKDAY. This should mask (i.e., ignore) the date/day so that the alarm will occur based upon only the hour, minute, and second.