fsl_rtc.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. * Copyright (c) 2015, Freescale Semiconductor, Inc.
  3. * Copyright 2016-2017 NXP
  4. *
  5. * Redistribution and use in source and binary forms, with or without modification,
  6. * are permitted provided that the following conditions are met:
  7. *
  8. * o Redistributions of source code must retain the above copyright notice, this list
  9. * of conditions and the following disclaimer.
  10. *
  11. * o Redistributions in binary form must reproduce the above copyright notice, this
  12. * list of conditions and the following disclaimer in the documentation and/or
  13. * other materials provided with the distribution.
  14. *
  15. * o Neither the name of the copyright holder nor the names of its
  16. * contributors may be used to endorse or promote products derived from this
  17. * software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  20. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  23. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  25. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  26. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include "fsl_rtc.h"
  31. /*******************************************************************************
  32. * Definitions
  33. ******************************************************************************/
  34. #define SECONDS_IN_A_DAY (86400U)
  35. #define SECONDS_IN_A_HOUR (3600U)
  36. #define SECONDS_IN_A_MINUTE (60U)
  37. #define DAYS_IN_A_YEAR (365U)
  38. #define YEAR_RANGE_START (1970U)
  39. #define YEAR_RANGE_END (2099U)
  40. /*******************************************************************************
  41. * Prototypes
  42. ******************************************************************************/
  43. /*!
  44. * @brief Checks whether the date and time passed in is valid
  45. *
  46. * @param datetime Pointer to structure where the date and time details are stored
  47. *
  48. * @return Returns false if the date & time details are out of range; true if in range
  49. */
  50. static bool RTC_CheckDatetimeFormat(const rtc_datetime_t *datetime);
  51. /*!
  52. * @brief Converts time data from datetime to seconds
  53. *
  54. * @param datetime Pointer to datetime structure where the date and time details are stored
  55. *
  56. * @return The result of the conversion in seconds
  57. */
  58. static uint32_t RTC_ConvertDatetimeToSeconds(const rtc_datetime_t *datetime);
  59. /*!
  60. * @brief Converts time data from seconds to a datetime structure
  61. *
  62. * @param seconds Seconds value that needs to be converted to datetime format
  63. * @param datetime Pointer to the datetime structure where the result of the conversion is stored
  64. */
  65. static void RTC_ConvertSecondsToDatetime(uint32_t seconds, rtc_datetime_t *datetime);
  66. /*******************************************************************************
  67. * Code
  68. ******************************************************************************/
  69. static bool RTC_CheckDatetimeFormat(const rtc_datetime_t *datetime)
  70. {
  71. assert(datetime);
  72. /* Table of days in a month for a non leap year. First entry in the table is not used,
  73. * valid months start from 1
  74. */
  75. uint8_t daysPerMonth[] = {0U, 31U, 28U, 31U, 30U, 31U, 30U, 31U, 31U, 30U, 31U, 30U, 31U};
  76. /* Check year, month, hour, minute, seconds */
  77. if ((datetime->year < YEAR_RANGE_START) || (datetime->year > YEAR_RANGE_END) || (datetime->month > 12U) ||
  78. (datetime->month < 1U) || (datetime->hour >= 24U) || (datetime->minute >= 60U) || (datetime->second >= 60U))
  79. {
  80. /* If not correct then error*/
  81. return false;
  82. }
  83. /* Adjust the days in February for a leap year */
  84. if ((((datetime->year & 3U) == 0) && (datetime->year % 100 != 0)) || (datetime->year % 400 == 0))
  85. {
  86. daysPerMonth[2] = 29U;
  87. }
  88. /* Check the validity of the day */
  89. if ((datetime->day > daysPerMonth[datetime->month]) || (datetime->day < 1U))
  90. {
  91. return false;
  92. }
  93. return true;
  94. }
  95. static uint32_t RTC_ConvertDatetimeToSeconds(const rtc_datetime_t *datetime)
  96. {
  97. assert(datetime);
  98. /* Number of days from begin of the non Leap-year*/
  99. /* Number of days from begin of the non Leap-year*/
  100. uint16_t monthDays[] = {0U, 0U, 31U, 59U, 90U, 120U, 151U, 181U, 212U, 243U, 273U, 304U, 334U};
  101. uint32_t seconds;
  102. /* Compute number of days from 1970 till given year*/
  103. seconds = (datetime->year - 1970U) * DAYS_IN_A_YEAR;
  104. /* Add leap year days */
  105. seconds += ((datetime->year / 4) - (1970U / 4));
  106. /* Add number of days till given month*/
  107. seconds += monthDays[datetime->month];
  108. /* Add days in given month. We subtract the current day as it is
  109. * represented in the hours, minutes and seconds field*/
  110. seconds += (datetime->day - 1);
  111. /* For leap year if month less than or equal to Febraury, decrement day counter*/
  112. if ((!(datetime->year & 3U)) && (datetime->month <= 2U))
  113. {
  114. seconds--;
  115. }
  116. seconds = (seconds * SECONDS_IN_A_DAY) + (datetime->hour * SECONDS_IN_A_HOUR) +
  117. (datetime->minute * SECONDS_IN_A_MINUTE) + datetime->second;
  118. return seconds;
  119. }
  120. static void RTC_ConvertSecondsToDatetime(uint32_t seconds, rtc_datetime_t *datetime)
  121. {
  122. assert(datetime);
  123. uint32_t x;
  124. uint32_t secondsRemaining, days;
  125. uint16_t daysInYear;
  126. /* Table of days in a month for a non leap year. First entry in the table is not used,
  127. * valid months start from 1
  128. */
  129. uint8_t daysPerMonth[] = {0U, 31U, 28U, 31U, 30U, 31U, 30U, 31U, 31U, 30U, 31U, 30U, 31U};
  130. /* Start with the seconds value that is passed in to be converted to date time format */
  131. secondsRemaining = seconds;
  132. /* Calcuate the number of days, we add 1 for the current day which is represented in the
  133. * hours and seconds field
  134. */
  135. days = secondsRemaining / SECONDS_IN_A_DAY + 1;
  136. /* Update seconds left*/
  137. secondsRemaining = secondsRemaining % SECONDS_IN_A_DAY;
  138. /* Calculate the datetime hour, minute and second fields */
  139. datetime->hour = secondsRemaining / SECONDS_IN_A_HOUR;
  140. secondsRemaining = secondsRemaining % SECONDS_IN_A_HOUR;
  141. datetime->minute = secondsRemaining / 60U;
  142. datetime->second = secondsRemaining % SECONDS_IN_A_MINUTE;
  143. /* Calculate year */
  144. daysInYear = DAYS_IN_A_YEAR;
  145. datetime->year = YEAR_RANGE_START;
  146. while (days > daysInYear)
  147. {
  148. /* Decrease day count by a year and increment year by 1 */
  149. days -= daysInYear;
  150. datetime->year++;
  151. /* Adjust the number of days for a leap year */
  152. if (datetime->year & 3U)
  153. {
  154. daysInYear = DAYS_IN_A_YEAR;
  155. }
  156. else
  157. {
  158. daysInYear = DAYS_IN_A_YEAR + 1;
  159. }
  160. }
  161. /* Adjust the days in February for a leap year */
  162. if (!(datetime->year & 3U))
  163. {
  164. daysPerMonth[2] = 29U;
  165. }
  166. for (x = 1U; x <= 12U; x++)
  167. {
  168. if (days <= daysPerMonth[x])
  169. {
  170. datetime->month = x;
  171. break;
  172. }
  173. else
  174. {
  175. days -= daysPerMonth[x];
  176. }
  177. }
  178. datetime->day = days;
  179. }
  180. void RTC_Init(RTC_Type *base, const rtc_config_t *config)
  181. {
  182. assert(config);
  183. uint32_t reg;
  184. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  185. CLOCK_EnableClock(kCLOCK_Rtc0);
  186. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  187. /* Issue a software reset if timer is invalid */
  188. if (RTC_GetStatusFlags(RTC) & kRTC_TimeInvalidFlag)
  189. {
  190. RTC_Reset(RTC);
  191. }
  192. reg = base->CR;
  193. /* Setup the update mode and supervisor access mode */
  194. reg &= ~(RTC_CR_UM_MASK | RTC_CR_SUP_MASK);
  195. reg |= RTC_CR_UM(config->updateMode) | RTC_CR_SUP(config->supervisorAccess);
  196. #if defined(FSL_FEATURE_RTC_HAS_WAKEUP_PIN_SELECTION) && FSL_FEATURE_RTC_HAS_WAKEUP_PIN_SELECTION
  197. /* Setup the wakeup pin select */
  198. reg &= ~(RTC_CR_WPS_MASK);
  199. reg |= RTC_CR_WPS(config->wakeupSelect);
  200. #endif /* FSL_FEATURE_RTC_HAS_WAKEUP_PIN */
  201. base->CR = reg;
  202. /* Configure the RTC time compensation register */
  203. base->TCR = (RTC_TCR_CIR(config->compensationInterval) | RTC_TCR_TCR(config->compensationTime));
  204. }
  205. void RTC_GetDefaultConfig(rtc_config_t *config)
  206. {
  207. assert(config);
  208. /* Wakeup pin will assert if the RTC interrupt asserts or if the wakeup pin is turned on */
  209. config->wakeupSelect = false;
  210. /* Registers cannot be written when locked */
  211. config->updateMode = false;
  212. /* Non-supervisor mode write accesses are not supported and will generate a bus error */
  213. config->supervisorAccess = false;
  214. /* Compensation interval used by the crystal compensation logic */
  215. config->compensationInterval = 0;
  216. /* Compensation time used by the crystal compensation logic */
  217. config->compensationTime = 0;
  218. }
  219. status_t RTC_SetDatetime(RTC_Type *base, const rtc_datetime_t *datetime)
  220. {
  221. assert(datetime);
  222. /* Return error if the time provided is not valid */
  223. if (!(RTC_CheckDatetimeFormat(datetime)))
  224. {
  225. return kStatus_InvalidArgument;
  226. }
  227. /* Set time in seconds */
  228. base->TSR = RTC_ConvertDatetimeToSeconds(datetime);
  229. return kStatus_Success;
  230. }
  231. void RTC_GetDatetime(RTC_Type *base, rtc_datetime_t *datetime)
  232. {
  233. assert(datetime);
  234. uint32_t seconds = 0;
  235. seconds = base->TSR;
  236. RTC_ConvertSecondsToDatetime(seconds, datetime);
  237. }
  238. status_t RTC_SetAlarm(RTC_Type *base, const rtc_datetime_t *alarmTime)
  239. {
  240. assert(alarmTime);
  241. uint32_t alarmSeconds = 0;
  242. uint32_t currSeconds = 0;
  243. /* Return error if the alarm time provided is not valid */
  244. if (!(RTC_CheckDatetimeFormat(alarmTime)))
  245. {
  246. return kStatus_InvalidArgument;
  247. }
  248. alarmSeconds = RTC_ConvertDatetimeToSeconds(alarmTime);
  249. /* Get the current time */
  250. currSeconds = base->TSR;
  251. /* Return error if the alarm time has passed */
  252. if (alarmSeconds < currSeconds)
  253. {
  254. return kStatus_Fail;
  255. }
  256. /* Set alarm in seconds*/
  257. base->TAR = alarmSeconds;
  258. return kStatus_Success;
  259. }
  260. void RTC_GetAlarm(RTC_Type *base, rtc_datetime_t *datetime)
  261. {
  262. assert(datetime);
  263. uint32_t alarmSeconds = 0;
  264. /* Get alarm in seconds */
  265. alarmSeconds = base->TAR;
  266. RTC_ConvertSecondsToDatetime(alarmSeconds, datetime);
  267. }
  268. void RTC_ClearStatusFlags(RTC_Type *base, uint32_t mask)
  269. {
  270. /* The alarm flag is cleared by writing to the TAR register */
  271. if (mask & kRTC_AlarmFlag)
  272. {
  273. base->TAR = 0U;
  274. }
  275. /* The timer overflow flag is cleared by initializing the TSR register.
  276. * The time counter should be disabled for this write to be successful
  277. */
  278. if (mask & kRTC_TimeOverflowFlag)
  279. {
  280. base->TSR = 1U;
  281. }
  282. /* The timer overflow flag is cleared by initializing the TSR register.
  283. * The time counter should be disabled for this write to be successful
  284. */
  285. if (mask & kRTC_TimeInvalidFlag)
  286. {
  287. base->TSR = 1U;
  288. }
  289. }
  290. #if defined(FSL_FEATURE_RTC_HAS_MONOTONIC) && (FSL_FEATURE_RTC_HAS_MONOTONIC)
  291. void RTC_GetMonotonicCounter(RTC_Type *base, uint64_t *counter)
  292. {
  293. assert(counter);
  294. *counter = (((uint64_t)base->MCHR << 32) | ((uint64_t)base->MCLR));
  295. }
  296. void RTC_SetMonotonicCounter(RTC_Type *base, uint64_t counter)
  297. {
  298. /* Prepare to initialize the register with the new value written */
  299. base->MER &= ~RTC_MER_MCE_MASK;
  300. base->MCHR = (uint32_t)((counter) >> 32);
  301. base->MCLR = (uint32_t)(counter);
  302. }
  303. status_t RTC_IncrementMonotonicCounter(RTC_Type *base)
  304. {
  305. if (base->SR & (RTC_SR_MOF_MASK | RTC_SR_TIF_MASK))
  306. {
  307. return kStatus_Fail;
  308. }
  309. /* Prepare to switch to increment mode */
  310. base->MER |= RTC_MER_MCE_MASK;
  311. /* Write anything so the counter increments*/
  312. base->MCLR = 1U;
  313. return kStatus_Success;
  314. }
  315. #endif /* FSL_FEATURE_RTC_HAS_MONOTONIC */