stm32g0xx_hal_timebase_rtc_alarm_template.c 12.9 KB
Newer Older
1 2 3 4 5 6 7 8
/**
  ******************************************************************************
  * @file    stm32g0xx_hal_timebase_rtc_alarm_template.c
  * @author  MCD Application Team
  * @brief   HAL time base based on the hardware RTC_ALARM Template.
  *
  *          This file override the native HAL time base functions (defined as weak)
  *          to use the RTC ALARM for time base generation:
M
Mr.Tiger 已提交
9
  *           + Initializes the RTC peripheral to increment the seconds registers each 1ms
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  *           + The alarm is configured to assert an interrupt when the RTC reaches 1ms
  *           + HAL_IncTick is called at each Alarm event and the time is reset to 00:00:00
  *           + HSE (default), LSE or LSI can be selected as RTC clock source
 @verbatim
  ==============================================================================
                        ##### How to use this driver #####
  ==============================================================================
    [..]
    This file must be copied to the application folder and modified as follows:
    (#) Rename it to 'stm32g0xx_hal_timebase_rtc_alarm.c'
    (#) Add this file and the RTC HAL drivers to your project and uncomment
       HAL_RTC_MODULE_ENABLED define in stm32g0xx_hal_conf.h

    [..]
    (@) HAL RTC alarm and HAL RTC wakeup drivers cant be used with low power modes:
        The wake up capability of the RTC may be intrusive in case of prior low power mode
        configuration requiring different wake up sources.
        Application/Example behavior is no more guaranteed
    (@) The stm32g0xx_hal_timebase_tim use is recommended for the Applications/Examples
          requiring low power modes

  @endverbatim
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2018 STMicroelectronics. 
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the 
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "stm32g0xx_hal.h"
/** @addtogroup STM32G0xx_HAL_Driver
  * @{
  */

/** @defgroup HAL_TimeBase_RTC_Alarm_Template  HAL TimeBase RTC Alarm Template
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/

/* Uncomment the line below to select the appropriate RTC Clock source for your application:
  + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision.
  + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing
                          precision.
  + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing
                          precision.
  */
M
Mr.Tiger 已提交
66
/* #define RTC_CLOCK_SOURCE_HSE */
67
/* #define RTC_CLOCK_SOURCE_LSE */
M
Mr.Tiger 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#define RTC_CLOCK_SOURCE_LSI 

/* Minimize Asynchronous prescaler for power consumption :
  ck_apre = RTCCLK / (ASYNC prediv + 1)
  ck_spre = ck_apre/(SYNC prediv + 1) = 1 Hz */
#if defined (RTC_CLOCK_SOURCE_LSE)
/* LSE Freq = 32.768 kHz RC */
#define RTC_ASYNCH_PREDIV                   0u
#define RTC_SYNCH_PREDIV                    0x3FFFu /* (16384 - 1) */
#elif defined (RTC_CLOCK_SOURCE_LSI)
/* LSI Freq = 32 kHz RC  */
#define RTC_ASYNCH_PREDIV                   0u
#define RTC_SYNCH_PREDIV                    0x3E7Fu /* (16000 - 1) */
#elif defined (RTC_CLOCK_SOURCE_HSE)
/* HSE Freq as RTCCLK = 8 MHz / 32 = 250 kHz */
#define RTC_ASYNCH_PREDIV                   0x07u   /* (8 - 1) */
#define RTC_SYNCH_PREDIV                    0x7A11u /* (31250 -1) */
#endif
86 87 88 89


/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
M
Mr.Tiger 已提交
90
RTC_HandleTypeDef        hRTC_Handle = {.Init = {0}};
91 92 93 94 95 96

/* Private function prototypes -----------------------------------------------*/
void RTC_TAMP_IRQHandler(void);
/* Private functions ---------------------------------------------------------*/

/**
M
Mr.Tiger 已提交
97 98 99 100 101 102 103 104 105 106
  * @brief  This function configures the RTC ALARM A as a time base source. 
  *         The time source is configured to have 1ms time base with a dedicated 
  *         Tick interrupt priority. 
  *         Calendar time base is = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK
  *                               = 1s
  *         Alarm interrupt timebase is = (RTC_SYNCH_PREDIV / (1000 / uwTickFreq))
  *                                     = 1 ms when uwTickFreq is set to 1 kHz
  * @note   This function is called automatically at the beginning of program after
  *         reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). 
  * @param  TickPriority Tick interrupt priority.
107 108 109 110
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{
M
Mr.Tiger 已提交
111 112 113 114 115 116
  HAL_StatusTypeDef status = HAL_OK;
  RCC_OscInitTypeDef        RCC_OscInitStruct = {0};
  RCC_PeriphCLKInitTypeDef  PeriphClkInitStruct = {0};
  RTC_TimeTypeDef           time;
  RTC_DateTypeDef           date;
  RTC_AlarmTypeDef          alarm;
117 118


M
Mr.Tiger 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  /* Check uwTickFreq for MisraC 2012 (even if uwTickFreq is a enum type that don't take the value zero)*/
  if ((uint32_t)uwTickFreq != 0U)
  {
    /* Disable backup domeain protection */
    HAL_PWR_EnableBkUpAccess();

    /* Enable RTC APB clock gating */
    __HAL_RCC_RTCAPB_CLK_ENABLE();

    /* Disable the Alarm A */
    __HAL_RTC_ALARMA_DISABLE(&hRTC_Handle);
    /* In case of interrupt mode is used, the interrupt source must disabled */ 
    __HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
    __HAL_RTC_ALARM_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF);

    /* Get RTC clock configuration */
    HAL_RCCEx_GetPeriphCLKConfig(&PeriphClkInitStruct);

    /*In case of RTC clock already enable, make sure it's the good one */
#if defined (RTC_CLOCK_SOURCE_LSE)
    if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_LSE) && (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != 0x00u))
140
#elif defined (RTC_CLOCK_SOURCE_LSI)
M
Mr.Tiger 已提交
141
    if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_LSI) && (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != 0x00u))
142
#elif defined (RTC_CLOCK_SOURCE_HSE)
M
Mr.Tiger 已提交
143
    if ((PeriphClkInitStruct.RTCClockSelection == RCC_RTCCLKSOURCE_HSE_DIV32) && (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != 0x00u))
144 145
#else
#error Please select the RTC Clock source
M
Mr.Tiger 已提交
146 147 148 149 150
#endif
    {
      /* Do nothing */
    }
    else
151
    {
M
Mr.Tiger 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
#ifdef RTC_CLOCK_SOURCE_LSE
      /* Configure LSE as RTC clock source */
      RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
      RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
      RCC_OscInitStruct.LSEState = RCC_LSE_ON;
      PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
#elif defined (RTC_CLOCK_SOURCE_LSI)
      /* Configure LSI as RTC clock source */
      RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI;
      RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
      RCC_OscInitStruct.LSIState = RCC_LSI_ON;
      PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
#elif defined (RTC_CLOCK_SOURCE_HSE)
      /* Configure HSE as RTC clock source */
      RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
      RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
      RCC_OscInitStruct.HSEState = RCC_HSE_ON;
      PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
#endif

      /* Configure oscillator */
      status = HAL_RCC_OscConfig(&RCC_OscInitStruct);
      if (status == HAL_OK)
      {
        /* Configure RTC clock source */
        PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
        status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct);
179

M
Mr.Tiger 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192
        /* Enable RTC Clock */
        if(status == HAL_OK)
        {
          __HAL_RCC_RTC_ENABLE();
        }
      }
    }

    /* If RTC Clock configuration is ok */
    if (status == HAL_OK)
    {
      /* The time base is defined to have highest synchronous prescaler but keeping 
         a 1Hz RTC frequency. */
193 194 195 196 197 198 199
      hRTC_Handle.Instance = RTC;
      hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24;
      hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV;
      hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV;
      hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE;
      hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
      hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
M
Mr.Tiger 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
      status = HAL_RTC_Init(&hRTC_Handle);
    }

    /* HAL RTC Init is ok & calendar has never been initialized */
    if((status == HAL_OK)  && (__HAL_RTC_GET_FLAG(&hRTC_Handle, RTC_FLAG_INITS) == 0x00u))
    {
      time.Hours = 0x00u;
      time.Minutes = 0x00u;
      time.Seconds = 0x00u;
      time.TimeFormat = RTC_HOURFORMAT12_PM;
      time.SubSeconds = 0x00u;
      time.SecondFraction = 0x00u;
      time.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
      time.StoreOperation = RTC_STOREOPERATION_RESET;
      status = HAL_RTC_SetTime(&hRTC_Handle, &time, RTC_FORMAT_BCD);
      if(status == HAL_OK)
216
      {
M
Mr.Tiger 已提交
217 218 219 220 221
        date.WeekDay = RTC_WEEKDAY_MONDAY;
        date.Date = 0x01u;
        date.Month = RTC_MONTH_JANUARY;
        date.Year = 0x01u;
        status = HAL_RTC_SetDate(&hRTC_Handle, &date, RTC_FORMAT_BCD);
222
      }
M
Mr.Tiger 已提交
223
    }
224

M
Mr.Tiger 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    /* If RTC calendar is initialized */
    if (status == HAL_OK)
    {
      alarm.AlarmTime.Hours = 0x00u;
      alarm.AlarmTime.Minutes = 0x00u;
      alarm.AlarmTime.Seconds = 0x00u;
      alarm.AlarmTime.TimeFormat = RTC_HOURFORMAT12_PM;
      alarm.AlarmTime.SubSeconds = (RTC_SYNCH_PREDIV / (1000 / (uint32_t)uwTickFreq));
      alarm.AlarmTime.SecondFraction = 0x00u;
      alarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
      alarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
      alarm.AlarmMask = RTC_ALARMMASK_ALL;

      /* Depending on input frequency select Subsecond mask */
      if (uwTickFreq == HAL_TICK_FREQ_1KHZ)
240
      {
M
Mr.Tiger 已提交
241
        alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_5;
242
      }
M
Mr.Tiger 已提交
243 244 245 246 247
      else if (uwTickFreq == HAL_TICK_FREQ_100HZ)
      {
        alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_9;
      }
      else
248
      {
M
Mr.Tiger 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
#if defined (RTC_CLOCK_SOURCE_HSE)
        /* When RTCCLK = 1 MHz, need to mask Subsecond register bit 12 to 14
          to have 10 Hhz interrupt */
        alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_12;
#else
        /* When RTCCLK is around 32 kHz, need to mask Subsecond register bit 12 to 11
          to have 10 Hhz interrupt */
        alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_SS14_11;
#endif
      }
      alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
      alarm.AlarmDateWeekDay = RTC_WEEKDAY_MONDAY;
      alarm.Alarm = RTC_ALARM_A;
      status = HAL_RTC_SetAlarm_IT(&hRTC_Handle, &alarm, RTC_FORMAT_BCD);
      if(status == HAL_OK)
      {
        /* Enable the RTC global Interrupt */
        HAL_NVIC_EnableIRQ(RTC_TAMP_IRQn);

        /* Configure the SysTick IRQ priority */
        if (TickPriority < (1UL << __NVIC_PRIO_BITS))
270
        {
M
Mr.Tiger 已提交
271 272 273 274 275 276
          HAL_NVIC_SetPriority(RTC_TAMP_IRQn, TickPriority, 0U);
          uwTickPrio = TickPriority;
        }
        else
        {
          status = HAL_ERROR;
277 278 279 280
        }
      }
    }
  }
M
Mr.Tiger 已提交
281 282 283 284 285
  else
  {
    status = HAL_ERROR;
  }
  return status;
286 287 288 289
}

/**
  * @brief  Suspend Tick increment.
M
Mr.Tiger 已提交
290
  * @note   Disable the tick increment by disabling RTC_ALRA interrupt.
291 292 293 294 295 296
  * @retval None
  */
void HAL_SuspendTick(void)
{
  /* Disable the write protection for RTC registers */
  __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
M
Mr.Tiger 已提交
297
  /* Disable ALARM A Interrupt */
298 299 300 301 302 303 304 305 306 307 308 309 310 311
  __HAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
  /* Enable the write protection for RTC registers */
  __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
}

/**
  * @brief  Resume Tick increment.
  * @note   Enable the tick increment by Enabling RTC ALARM interrupt.
  * @retval None
  */
void HAL_ResumeTick(void)
{
  /* Disable the write protection for RTC registers */
  __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle);
M
Mr.Tiger 已提交
312
  /* Enable ALARM A interrupt */
313 314 315 316 317 318
  __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA);
  /* Enable the write protection for RTC registers */
  __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle);
}

/**
M
Mr.Tiger 已提交
319 320 321 322 323
  * @brief  Alarm Timer Event Callback in non blocking mode
  * @note   This function is called  when RTC Alarm takes place, inside
  *         HAL_RTC_AlarmIRQHandler(). It makes a direct call to HAL_IncTick() to increment
  *         a global variable "uwTick" used as application time base.
  * @param  hrtc  RTC handle
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  * @retval None
  */
void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
{
  HAL_IncTick();
}

/**
  * @brief  This function handles RTC ALARM interrupt request.
  * @retval None
  */
void RTC_TAMP_IRQHandler(void)
{
  HAL_RTC_AlarmIRQHandler(&hRTC_Handle);
}

/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/