-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathrtc.c
1294 lines (1207 loc) · 41 KB
/
rtc.c
1
2
3
4
5
6
7
8
9
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
******************************************************************************
* @file rtc.c
* @author Frederic Pillon
* @brief Provides a RTC driver
*
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2020 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#include "rtc.h"
#include "stm32yyxx_ll_rtc.h"
#include <string.h>
#if defined(HAL_RTC_MODULE_ENABLED) && !defined(HAL_RTC_MODULE_ONLY)
#if defined(STM32MP1xx)
/**
* Currently there is no RTC driver for STM32MP1xx. If RTC is used in the future
* the function call HAL_RCCEx_PeriphCLKConfig() shall be done under
* if(IS_ENGINEERING_BOOT_MODE()), since clock source selection is done by
* First Stage Boot Loader on Cortex-A.
*/
#error "RTC shall not be handled by Arduino in STM32MP1xx."
#endif /* STM32MP1xx */
#ifdef __cplusplus
extern "C" {
#endif
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static RTC_HandleTypeDef RtcHandle = {.Instance = RTC};
static voidCallbackPtr RTCUserCallback = NULL;
static void *callbackUserData = NULL;
#ifdef RTC_ALARM_B
static voidCallbackPtr RTCUserCallbackB = NULL;
static void *callbackUserDataB = NULL;
#endif
#ifdef ONESECOND_IRQn
static voidCallbackPtr RTCSecondsIrqCallback = NULL;
#endif
#ifdef STM32WLxx
static voidCallbackPtr RTCSubSecondsUnderflowIrqCallback = NULL;
#endif
static sourceClock_t clkSrc = LSI_CLOCK;
static uint32_t clkVal = LSI_VALUE;
static uint8_t HSEDiv = 0;
#if !defined(STM32F1xx)
/* predividers values */
static uint8_t predivSync_bits = 0xFF;
static uint32_t predivAsync = (PREDIVA_MAX + 1);
static uint32_t predivSync = (PREDIVS_MAX + 1);
static uint32_t fqce_apre;
#else
/* Default, let HAL calculate the prescaler*/
static uint32_t predivAsync = RTC_AUTO_1_SECOND;
#endif /* !STM32F1xx */
static hourFormat_t initFormat = HOUR_FORMAT_12;
static binaryMode_t initMode = MODE_BINARY_NONE;
/* Private function prototypes -----------------------------------------------*/
static void RTC_initClock(sourceClock_t source);
#if !defined(STM32F1xx)
static void RTC_computePrediv(uint32_t *asynch, uint32_t *synch);
#endif /* !STM32F1xx */
#if defined(RTC_BINARY_NONE)
static void RTC_BinaryConf(binaryMode_t mode);
#endif
static inline int _log2(int x)
{
return (x > 0) ? (sizeof(int) * 8 - __builtin_clz(x) - 1) : 0;
}
/* Exported functions --------------------------------------------------------*/
/**
* @brief Get pointer to RTC_HandleTypeDef
* @param None
* @retval pointer to RTC_HandleTypeDef
*/
RTC_HandleTypeDef *RTC_GetHandle(void)
{
return &RtcHandle;
}
/**
* @brief Set RTC clock source
* @param source: RTC clock source: LSE, LSI or HSE
* @retval None
*/
void RTC_SetClockSource(sourceClock_t source)
{
clkSrc = source;
if (source == LSE_CLOCK) {
clkVal = LSE_VALUE;
} else if (source == HSE_CLOCK) {
/* HSE division factor for RTC clock must be define to ensure that
* the clock supplied to the RTC is less than or equal to 1 MHz
*/
#if defined(STM32F1xx)
/* HSE max is 16 MHZ divided by 128 --> 125 KHz */
HSEDiv = 128;
#elif defined(RCC_RTCCLKSOURCE_HSE_DIV32) && !defined(RCC_RTCCLKSOURCE_HSE_DIV31)
HSEDiv = 32;
#elif !defined(RCC_RTCCLKSOURCE_HSE_DIV31)
if ((HSE_VALUE / 2) <= HSE_RTC_MAX) {
HSEDiv = 2;
} else if ((HSE_VALUE / 4) <= HSE_RTC_MAX) {
HSEDiv = 4;
} else if ((HSE_VALUE / 8) <= HSE_RTC_MAX) {
HSEDiv = 8;
} else if ((HSE_VALUE / 16) <= HSE_RTC_MAX) {
HSEDiv = 16;
}
#elif defined(RCC_RTCCLKSOURCE_HSE_DIV31)
/* Not defined for STM32F2xx */
#ifndef RCC_RTCCLKSOURCE_HSE_DIVX
#define RCC_RTCCLKSOURCE_HSE_DIVX 0x00000300U
#endif /* RCC_RTCCLKSOURCE_HSE_DIVX */
#if defined(RCC_RTCCLKSOURCE_HSE_DIV63)
#define HSEDIV_MAX 64
#else
#define HSEDIV_MAX 32
#endif
for (HSEDiv = 2; HSEDiv < HSEDIV_MAX; HSEDiv++) {
if ((HSE_VALUE / HSEDiv) <= HSE_RTC_MAX) {
break;
}
}
#else
#error "Could not define HSE div"
#endif /* STM32F1xx */
if ((HSE_VALUE / HSEDiv) > HSE_RTC_MAX) {
Error_Handler();
}
clkVal = HSE_VALUE / HSEDiv;
} else if (source == LSI_CLOCK) {
clkVal = LSI_VALUE;
} else {
Error_Handler();
}
}
/**
* @brief RTC clock initialization
* This function configures the hardware resources used.
* @param source: RTC clock source: LSE, LSI or HSE
* @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select
* the RTC clock source; in this case the Backup domain will be reset in
* order to modify the RTC Clock source, as consequence RTC registers (including
* the backup registers) and RCC_CSR register are set to their reset values.
* @retval None
*/
static void RTC_initClock(sourceClock_t source)
{
RCC_PeriphCLKInitTypeDef PeriphClkInit;
RTC_SetClockSource(source);
if (source == LSE_CLOCK) {
/* Enable the clock if not already set by user */
enableClock(LSE_CLOCK);
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC;
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) {
Error_Handler();
}
} else if (source == HSE_CLOCK) {
/* Enable the clock if not already set by user */
enableClock(HSE_CLOCK);
/* HSE division factor for RTC clock must be set to ensure that
* the clock supplied to the RTC is less than or equal to 1 MHz
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC;
#if defined(STM32F1xx)
/* HSE max is 16 MHZ divided by 128 --> 125 KHz */
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV128;
#elif defined(RCC_RTCCLKSOURCE_HSE_DIV32) && !defined(RCC_RTCCLKSOURCE_HSE_DIV31)
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV32;
#elif !defined(RCC_RTCCLKSOURCE_HSE_DIV31)
if ((HSE_VALUE / 2) <= HSE_RTC_MAX) {
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV2;
} else if ((HSE_VALUE / 4) <= HSE_RTC_MAX) {
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV4;
} else if ((HSE_VALUE / 8) <= HSE_RTC_MAX) {
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV8;
} else if ((HSE_VALUE / 16) <= HSE_RTC_MAX) {
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV16;
}
#elif defined(RCC_RTCCLKSOURCE_HSE_DIV31)
/* Not defined for STM32F2xx */
#ifndef RCC_RTCCLKSOURCE_HSE_DIVX
#define RCC_RTCCLKSOURCE_HSE_DIVX 0x00000300U
#endif /* RCC_RTCCLKSOURCE_HSE_DIVX */
#if defined(RCC_RTCCLKSOURCE_HSE_DIV63)
#define HSESHIFT 12
#else
#define HSESHIFT 16
#endif
PeriphClkInit.RTCClockSelection = (HSEDiv << HSESHIFT) | RCC_RTCCLKSOURCE_HSE_DIVX;
#else
#error "Could not define RTCClockSelection"
#endif /* STM32F1xx */
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) {
Error_Handler();
}
} else if (source == LSI_CLOCK) {
/* Enable the clock if not already set by user */
enableClock(LSI_CLOCK);
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC;
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) {
Error_Handler();
}
} else {
Error_Handler();
}
}
/**
* @brief set user (a)synchronous prescaler values.
* @param asynch: asynchronous prescaler value in range 0 - PREDIVA_MAX
* @note Reset value: RTC_AUTO_1_SECOND for STM32F1xx series, else (PREDIVA_MAX + 1)
* @param synch: synchronous prescaler value in range 0 - PREDIVS_MAX
* @note Reset value: (PREDIVS_MAX + 1), not used for STM32F1xx series.
* @retval None
*/
void RTC_setPrediv(uint32_t asynch, uint32_t synch)
{
#if defined(STM32F1xx)
UNUSED(synch);
/* set the prescaler for a stm32F1 (value is hold by one param) */
predivAsync = asynch;
if (!IS_RTC_ASYNCH_PREDIV(predivAsync)) {
predivAsync = RTC_AUTO_1_SECOND;
}
LL_RTC_SetAsynchPrescaler(RTC, predivAsync);
#else
if ((asynch <= PREDIVA_MAX) && (synch <= PREDIVS_MAX)) {
predivAsync = asynch;
predivSync = synch;
} else {
RTC_computePrediv(&predivAsync, &predivSync);
}
predivSync_bits = (uint8_t)_log2(predivSync) + 1;
#endif /* STM32F1xx */
}
/**
* @brief get user (a)synchronous prescaler values if set else computed ones
* for the current clock source.
* @param asynch: pointer where return asynchronous prescaler value.
* @param synch: pointer where return synchronous prescaler value,
* not used for STM32F1xx series.
* @retval None
*/
void RTC_getPrediv(uint32_t *asynch, uint32_t *synch)
{
#if defined(STM32F1xx)
UNUSED(synch);
/* get the prescaler for a stm32F1 (value is hold by one param) */
predivAsync = LL_RTC_GetDivider(RTC);
*asynch = predivAsync;
#else
if ((!IS_RTC_SYNCH_PREDIV(predivSync)) || (!IS_RTC_ASYNCH_PREDIV(predivAsync))) {
if (!LL_RTC_IsActiveFlag_INITS(RtcHandle.Instance)) {
RTC_computePrediv(&predivAsync, &predivSync);
} else {
predivAsync = LL_RTC_GetAsynchPrescaler(RtcHandle.Instance);
predivSync = LL_RTC_GetSynchPrescaler(RtcHandle.Instance);
}
}
if ((asynch != NULL) && (synch != NULL)) {
*asynch = predivAsync;
*synch = predivSync;
}
predivSync_bits = (uint8_t)_log2(predivSync) + 1;
#endif /* STM32F1xx */
}
#if !defined(STM32F1xx)
/**
* @brief Compute (a)synchronous prescaler
* RTC prescalers are compute to obtain the RTC clock to 1Hz. See AN4759.
* @param asynch: pointer where return asynchronous prescaler value.
* @param synch: pointer where return synchronous prescaler value.
* @retval None
*/
static void RTC_computePrediv(uint32_t *asynch, uint32_t *synch)
{
uint32_t predivS = PREDIVS_MAX + 1;
*asynch = PREDIVA_MAX + 1;
/* Get user predividers if manually configured */
if ((asynch == NULL) || (synch == NULL)) {
return;
}
/* Find (a)synchronous prescalers to obtain the 1Hz calendar clock */
do {
(*asynch)--;
predivS = (clkVal / (*asynch + 1)) - 1;
if (((predivS + 1) * (*asynch + 1)) == clkVal) {
break;
}
} while (*asynch != 0);
/*
* Can't find a 1Hz, so give priority to RTC power consumption
* by choosing the higher possible value for predivA
*/
if ((!IS_RTC_SYNCH_PREDIV(predivS)) || (!IS_RTC_ASYNCH_PREDIV(*asynch))) {
*asynch = PREDIVA_MAX;
predivS = (clkVal / (*asynch + 1)) - 1;
}
if (!IS_RTC_SYNCH_PREDIV(predivS)) {
Error_Handler();
}
*synch = predivS;
fqce_apre = clkVal / (*asynch + 1);
}
#endif /* !STM32F1xx */
#if defined(RTC_BINARY_NONE)
static void RTC_BinaryConf(binaryMode_t mode)
{
RtcHandle.Init.BinMode = (mode == MODE_BINARY_MIX) ? RTC_BINARY_MIX : ((mode == MODE_BINARY_ONLY) ? RTC_BINARY_ONLY : RTC_BINARY_NONE);
if (RtcHandle.Init.BinMode == RTC_BINARY_MIX) {
/* Configure the 1s BCD calendar increment */
uint32_t inc = 1 / (1.0 / ((float)clkVal / (float)(predivAsync + 1.0)));
if (inc <= 256) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_0;
} else if (inc < (256 << 1)) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_1;
} else if (inc < (256 << 2)) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_2;
} else if (inc < (256 << 3)) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_3;
} else if (inc < (256 << 4)) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_4;
} else if (inc < (256 << 5)) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_5;
} else if (inc < (256 << 6)) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_6;
} else if (inc < (256 << 7)) {
RtcHandle.Init.BinMixBcdU = RTC_BINARY_MIX_BCDU_7;
} else {
Error_Handler();
}
}
}
#endif /* RTC_BINARY_NONE */
/**
* @brief RTC Initialization
* This function configures the RTC time and calendar. By default, the
* RTC is set to the 1st January 2001
* Note: year 2000 is invalid as it is the hardware reset value and doesn't raise INITS flag
* @param format: enable the RTC in 12 or 24 hours mode
* @param mode: enable the RTC in BCD or Mix or Binary mode
* @param source: RTC clock source: LSE, LSI or HSE
* @param reset: force RTC reset, even if previously configured
* @retval True if RTC is reinitialized, else false
*/
bool RTC_init(hourFormat_t format, binaryMode_t mode, sourceClock_t source, bool reset)
{
bool reinit = false;
hourAM_PM_t period = HOUR_AM, alarmPeriod = HOUR_AM;
uint32_t subSeconds = 0, alarmSubseconds = 0;
uint8_t seconds = 0, minutes = 0, hours = 0, weekDay = 0, days = 0, month = 0, years = 0;
uint8_t alarmMask = 0, alarmDay = 0, alarmHours = 0, alarmMinutes = 0, alarmSeconds = 0;
bool isAlarmASet = false;
#ifdef RTC_ALARM_B
hourAM_PM_t alarmBPeriod = HOUR_AM;
uint8_t alarmBMask = 0, alarmBDay = 0, alarmBHours = 0, alarmBMinutes = 0, alarmBSeconds = 0;
uint32_t alarmBSubseconds = 0;
bool isAlarmBSet = false;
#endif
initFormat = format;
initMode = mode;
/* Ensure all RtcHandle properly set */
RtcHandle.Instance = RTC;
#if defined(STM32F1xx)
RtcHandle.Init.AsynchPrediv = predivAsync;
RtcHandle.Init.OutPut = RTC_OUTPUTSOURCE_NONE;
#else
RtcHandle.Init.HourFormat = (format == HOUR_FORMAT_12) ? RTC_HOURFORMAT_12 : RTC_HOURFORMAT_24;
RtcHandle.Init.OutPut = RTC_OUTPUT_DISABLE;
RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
RtcHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
#if defined(RTC_OUTPUT_PULLUP_NONE)
RtcHandle.Init.OutPutPullUp = RTC_OUTPUT_PULLUP_NONE;
#endif
#if defined(RTC_OUTPUT_REMAP_NONE)
RtcHandle.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;
#endif /* RTC_OUTPUT_REMAP_NONE */
#endif /* STM32F1xx */
/* Ensure backup domain is enabled before we init the RTC so we can use the backup registers for date retention on stm32f1xx boards */
enableBackupDomain();
if (reset) {
resetBackupDomain();
}
#ifdef __HAL_RCC_RTCAPB_CLK_ENABLE
__HAL_RCC_RTCAPB_CLK_ENABLE();
#endif
__HAL_RCC_RTC_ENABLE();
isAlarmASet = RTC_IsAlarmSet(ALARM_A);
#ifdef RTC_ALARM_B
isAlarmBSet = RTC_IsAlarmSet(ALARM_B);
#endif
#if defined(STM32F1xx)
uint32_t BackupDate;
BackupDate = getBackupRegister(RTC_BKP_DATE) << 16;
BackupDate |= getBackupRegister(RTC_BKP_DATE + 1) & 0xFFFF;
if ((BackupDate == 0) || reset) {
// RTC needs initialization
// Init RTC clock
RTC_initClock(source);
#else
if (!LL_RTC_IsActiveFlag_INITS(RtcHandle.Instance) || reset) {
// RTC needs initialization
// Init RTC clock
RTC_initClock(source);
RTC_getPrediv(&(RtcHandle.Init.AsynchPrediv), &(RtcHandle.Init.SynchPrediv));
#if defined(RTC_BINARY_NONE)
RTC_BinaryConf(mode);
#endif /* RTC_BINARY_NONE */
#endif // STM32F1xx
HAL_RTC_Init(&RtcHandle);
// Default: saturday 1st of January 2001
// Note: year 2000 is invalid as it is the hardware reset value and doesn't raise INITS flag
RTC_SetDate(1, 1, 1, 6);
reinit = true;
} else {
// RTC is already initialized
uint32_t oldRtcClockSource = __HAL_RCC_GET_RTC_SOURCE();
oldRtcClockSource = ((oldRtcClockSource == RCC_RTCCLKSOURCE_LSE) ? LSE_CLOCK :
(oldRtcClockSource == RCC_RTCCLKSOURCE_LSI) ? LSI_CLOCK :
#if defined(RCC_RTCCLKSOURCE_HSE_DIVX)
(oldRtcClockSource == RCC_RTCCLKSOURCE_HSE_DIVX) ? HSE_CLOCK :
#elif defined(RCC_RTCCLKSOURCE_HSE_DIV32)
(oldRtcClockSource == RCC_RTCCLKSOURCE_HSE_DIV32) ? HSE_CLOCK :
#elif defined(RCC_RTCCLKSOURCE_HSE_DIV)
(oldRtcClockSource == RCC_RTCCLKSOURCE_HSE_DIV) ? HSE_CLOCK :
#elif defined(RCC_RTCCLKSOURCE_HSE_DIV128)
(oldRtcClockSource == RCC_RTCCLKSOURCE_HSE_DIV128) ? HSE_CLOCK :
#endif
// default case corresponding to no clock source
0xFFFFFFFF);
#if defined(STM32F1xx)
if ((RtcHandle.DateToUpdate.WeekDay == 0)
&& (RtcHandle.DateToUpdate.Month == 0)
&& (RtcHandle.DateToUpdate.Date == 0)
&& (RtcHandle.DateToUpdate.Year == 0)) {
// After a reset for example, restore HAL handle date with values from BackupRegister date
memcpy(&RtcHandle.DateToUpdate, &BackupDate, 4);
}
#endif // STM32F1xx
if (source != oldRtcClockSource) {
// RTC is already initialized, but RTC clock source is changed
// In case of RTC source clock change, Backup Domain is reset by RTC_initClock()
// Save current config before reinit
RTC_GetDate(&years, &month, &days, &weekDay);
RTC_GetTime(&hours, &minutes, &seconds, &subSeconds, &period);
// As clock source changed, force update prediv with user or computef ones
#if defined(STM32F1xx)
RTC_setPrediv(predivAsync, 0);
#else
RTC_setPrediv(predivAsync, predivSync);
#endif
if (isAlarmASet) {
RTC_GetAlarm(ALARM_A, &alarmDay, &alarmHours, &alarmMinutes, &alarmSeconds, &alarmSubseconds, &alarmPeriod, &alarmMask);
}
#ifdef RTC_ALARM_B
if (isAlarmBSet) {
RTC_GetAlarm(ALARM_B, &alarmBDay, &alarmBHours, &alarmBMinutes, &alarmBSeconds, &alarmBSubseconds, &alarmBPeriod, &alarmBMask);
}
#endif
RTC_DeInit(false);
// Init RTC clock
RTC_initClock(source);
#if defined(STM32F1xx)
RTC_getPrediv(&(RtcHandle.Init.AsynchPrediv), NULL);
#else
RTC_getPrediv(&(RtcHandle.Init.AsynchPrediv), &(RtcHandle.Init.SynchPrediv));
#endif
/*
* TODO: RTC is already initialized, but RTC BIN mode is changed
* force the update of the BIN register in the RTC_ICSR
*/
#if defined(RTC_BINARY_NONE)
RTC_BinaryConf(mode);
#endif /* RTC_BINARY_NONE */
HAL_RTC_Init(&RtcHandle);
// Restore config
RTC_SetTime(hours, minutes, seconds, subSeconds, period);
RTC_SetDate(years, month, days, weekDay);
if (isAlarmASet) {
RTC_StartAlarm(ALARM_A, alarmDay, alarmHours, alarmMinutes, alarmSeconds, alarmSubseconds, alarmPeriod, alarmMask);
}
#ifdef RTC_ALARM_B
if (isAlarmBSet) {
RTC_StartAlarm(ALARM_B, alarmBDay, alarmBHours, alarmBMinutes, alarmBSeconds, alarmBSubseconds, alarmBPeriod, alarmBMask);
}
#endif
} else {
// RTC is already initialized, and RTC stays on the same clock source
// Init RTC clock
RTC_initClock(source);
// This initialize variables: predivAsync, predivSync and predivSync_bits
#if defined(STM32F1xx)
RTC_getPrediv(&(RtcHandle.Init.AsynchPrediv), NULL);
#else
RTC_getPrediv(&(RtcHandle.Init.AsynchPrediv), &(RtcHandle.Init.SynchPrediv));
#endif
#if defined(RTC_BINARY_NONE)
RTC_BinaryConf(mode);
#endif /* RTC_BINARY_NONE */
#if defined(STM32F1xx)
memcpy(&RtcHandle.DateToUpdate, &BackupDate, 4);
/* Update date automatically by calling HAL_RTC_GetDate */
RTC_GetDate(&years, &month, &days, &weekDay);
/* and fill the new RTC Date value */
RTC_SetDate(RtcHandle.DateToUpdate.Year, RtcHandle.DateToUpdate.Month,
RtcHandle.DateToUpdate.Date, RtcHandle.DateToUpdate.WeekDay);
#endif // STM32F1xx
}
}
#if defined(RTC_CR_BYPSHAD)
/* Enable Direct Read of the calendar registers (not through Shadow) */
HAL_RTCEx_EnableBypassShadow(&RtcHandle);
#endif
/*
* NOTE: freezing the RTC during stop mode (lowPower deepSleep)
* could inhibit the alarm interrupt and prevent the system to wakeUp
* from stop mode even if the RTC alarm flag is set.
*/
return reinit;
}
/**
* @brief RTC deinitialization. Stop the RTC.
* @param reset_cb: reset user callback
* @retval None
*/
void RTC_DeInit(bool reset_cb)
{
HAL_RTC_DeInit(&RtcHandle);
/* Peripheral clock disable */
__HAL_RCC_RTC_DISABLE();
#ifdef __HAL_RCC_RTCAPB_CLK_DISABLE
__HAL_RCC_RTCAPB_CLK_DISABLE();
#endif
HAL_NVIC_DisableIRQ(RTC_Alarm_IRQn);
#ifdef ONESECOND_IRQn
HAL_NVIC_DisableIRQ(ONESECOND_IRQn);
#endif
#ifdef STM32WLxx
HAL_NVIC_DisableIRQ(TAMP_STAMP_LSECSS_SSRU_IRQn);
#endif
if (reset_cb) {
RTCUserCallback = NULL;
callbackUserData = NULL;
#ifdef RTC_ALARM_B
RTCUserCallbackB = NULL;
callbackUserDataB = NULL;
#endif
#ifdef ONESECOND_IRQn
RTCSecondsIrqCallback = NULL;
#endif
#ifdef STM32WLxx
RTCSubSecondsUnderflowIrqCallback = NULL;
#endif
}
}
/**
* @brief Check if time is already set
* @retval True if set else false
*/
bool RTC_IsConfigured(void)
{
#if defined(STM32F1xx)
uint32_t BackupDate;
BackupDate = getBackupRegister(RTC_BKP_DATE) << 16;
BackupDate |= getBackupRegister(RTC_BKP_DATE + 1) & 0xFFFF;
return (BackupDate != 0);
#else
return LL_RTC_IsActiveFlag_INITS(RtcHandle.Instance);
#endif
}
/**
* @brief Set RTC time
* @param hours: 0-12 or 0-23. Depends on the format used.
* @param minutes: 0-59
* @param seconds: 0-59
* @param subSeconds: 0-999 (not used)
* @param period: select HOUR_AM or HOUR_PM period in case RTC is set in 12 hours mode. Else ignored.
* @retval None
*/
void RTC_SetTime(uint8_t hours, uint8_t minutes, uint8_t seconds, uint32_t subSeconds, hourAM_PM_t period)
{
RTC_TimeTypeDef RTC_TimeStruct;
UNUSED(subSeconds); /* not used (read-only register) */
/* Ignore time AM PM configuration if in 24 hours format */
if (initFormat == HOUR_FORMAT_24) {
period = HOUR_AM;
}
if ((((initFormat == HOUR_FORMAT_24) && IS_RTC_HOUR24(hours)) || IS_RTC_HOUR12(hours))
&& IS_RTC_MINUTES(minutes) && IS_RTC_SECONDS(seconds)) {
RTC_TimeStruct.Hours = hours;
RTC_TimeStruct.Minutes = minutes;
RTC_TimeStruct.Seconds = seconds;
#if !defined(STM32F1xx)
if (period == HOUR_PM) {
RTC_TimeStruct.TimeFormat = RTC_HOURFORMAT12_PM;
} else {
RTC_TimeStruct.TimeFormat = RTC_HOURFORMAT12_AM;
}
#if defined(RTC_SSR_SS)
/* subSeconds is read only, so no need to set it */
/*RTC_TimeStruct.SubSeconds = subSeconds;*/
/*RTC_TimeStruct.SecondFraction = 0;*/
#endif /* RTC_SSR_SS */
RTC_TimeStruct.DayLightSaving = RTC_STOREOPERATION_RESET;
RTC_TimeStruct.StoreOperation = RTC_DAYLIGHTSAVING_NONE;
#else
UNUSED(period);
#endif /* !STM32F1xx */
HAL_RTC_SetTime(&RtcHandle, &RTC_TimeStruct, RTC_FORMAT_BIN);
}
}
/**
* @brief Get RTC time
* @param hours: 0-12 or 0-23. Depends on the format used.
* @param minutes: 0-59
* @param seconds: 0-59
* @param subSeconds: 0-999 (optional could be NULL)
* @param period: HOUR_AM or HOUR_PM period in case RTC is set in 12 hours mode (optional could be NULL).
* @retval None
*/
void RTC_GetTime(uint8_t *hours, uint8_t *minutes, uint8_t *seconds, uint32_t *subSeconds, hourAM_PM_t *period)
{
RTC_TimeTypeDef RTC_TimeStruct = {0}; /* in BIN mode, only the subsecond is used */
if ((hours != NULL) && (minutes != NULL) && (seconds != NULL)) {
#if defined(STM32F1xx)
/* Store the date prior to checking the time, this may roll over to the next day as part of the time check,
we need to the new date details in the backup registers if it changes */
uint8_t current_date = RtcHandle.DateToUpdate.Date;
#endif
HAL_RTC_GetTime(&RtcHandle, &RTC_TimeStruct, RTC_FORMAT_BIN);
*hours = RTC_TimeStruct.Hours;
*minutes = RTC_TimeStruct.Minutes;
*seconds = RTC_TimeStruct.Seconds;
#if !defined(STM32F1xx)
if (period != NULL) {
if (RTC_TimeStruct.TimeFormat == RTC_HOURFORMAT12_PM) {
*period = HOUR_PM;
} else {
*period = HOUR_AM;
}
}
#if defined(RTC_SSR_SS)
if (subSeconds != NULL) {
/*
* The subsecond is the free-running downcounter, to be converted in milliseconds.
*/
if (initMode == MODE_BINARY_ONLY) {
*subSeconds = (((UINT32_MAX - RTC_TimeStruct.SubSeconds + 1) & UINT32_MAX)
* 1000) / fqce_apre;
} else if (initMode == MODE_BINARY_MIX) {
*subSeconds = (((UINT32_MAX - RTC_TimeStruct.SubSeconds) & predivSync)
* 1000) / fqce_apre;
} else {
/* the subsecond register value is converted in millisec on 32bit */
*subSeconds = ((predivSync - RTC_TimeStruct.SubSeconds) * 1000) / (predivSync + 1);
}
}
#else
UNUSED(subSeconds);
#endif /* RTC_SSR_SS */
#else
UNUSED(period);
UNUSED(subSeconds);
if (current_date != RtcHandle.DateToUpdate.Date) {
RTC_StoreDate();
}
#endif /* !STM32F1xx */
}
}
/**
* @brief Set RTC calendar
* @param year: 0-99
* @param month: 1-12
* @param day: 1-31
* @param wday: 1-7
* @retval None
*/
void RTC_SetDate(uint8_t year, uint8_t month, uint8_t day, uint8_t wday)
{
RTC_DateTypeDef RTC_DateStruct;
if (IS_RTC_YEAR(year) && IS_RTC_MONTH(month) && IS_RTC_DATE(day) && IS_RTC_WEEKDAY(wday)) {
RTC_DateStruct.Year = year;
RTC_DateStruct.Month = month;
RTC_DateStruct.Date = day;
RTC_DateStruct.WeekDay = wday;
HAL_RTC_SetDate(&RtcHandle, &RTC_DateStruct, RTC_FORMAT_BIN);
#if defined(STM32F1xx)
RTC_StoreDate();
#endif /* STM32F1xx */
}
}
/**
* @brief Get RTC calendar
* @param year: 0-99
* @param month: 1-12
* @param day: 1-31
* @param wday: 1-7
* @retval None
*/
void RTC_GetDate(uint8_t *year, uint8_t *month, uint8_t *day, uint8_t *wday)
{
RTC_DateTypeDef RTC_DateStruct = {0}; /* in BIN mode, the date is not used */
if ((year != NULL) && (month != NULL) && (day != NULL) && (wday != NULL)) {
HAL_RTC_GetDate(&RtcHandle, &RTC_DateStruct, RTC_FORMAT_BIN);
*year = RTC_DateStruct.Year;
*month = RTC_DateStruct.Month;
*day = RTC_DateStruct.Date;
*wday = RTC_DateStruct.WeekDay;
}
}
/**
* @brief Set RTC alarm and activate it with IT mode
* @param name: ALARM_A or ALARM_B if exists
* @param day: 1-31 (day of the month)
* @param hours: 0-12 or 0-23 depends on the hours mode.
* @param minutes: 0-59
* @param seconds: 0-59
* @param subSeconds: 0-999 milliseconds
* @param period: HOUR_AM or HOUR_PM if in 12 hours mode else ignored.
* @param mask: configure alarm behavior using alarmMask_t combination.
* See AN4579 Table 5 for possible values.
* @retval None
*/
void RTC_StartAlarm(alarm_t name, uint8_t day, uint8_t hours, uint8_t minutes, uint8_t seconds, uint32_t subSeconds, hourAM_PM_t period, uint8_t mask)
{
#if !defined(RTC_SSR_SS)
UNUSED(subSeconds);
#endif
RTC_AlarmTypeDef RTC_AlarmStructure;
/* Ignore time AM PM configuration if in 24 hours format */
if (initFormat == HOUR_FORMAT_24) {
period = HOUR_AM;
}
/* Use alarm A by default because it is common to all STM32 HAL */
RTC_AlarmStructure.Alarm = name;
if ((((initFormat == HOUR_FORMAT_24) && IS_RTC_HOUR24(hours)) || IS_RTC_HOUR12(hours))
&& IS_RTC_DATE(day) && IS_RTC_MINUTES(minutes) && IS_RTC_SECONDS(seconds)) {
/* Set RTC_AlarmStructure with calculated values*/
RTC_AlarmStructure.AlarmTime.Seconds = seconds;
RTC_AlarmStructure.AlarmTime.Minutes = minutes;
RTC_AlarmStructure.AlarmTime.Hours = hours;
#if !defined(STM32F1xx)
#if defined(RTC_SSR_SS)
if (subSeconds < 1000) {
#ifdef RTC_ALARM_B
if (name == ALARM_B) {
RTC_AlarmStructure.AlarmSubSecondMask = predivSync_bits << RTC_ALRMBSSR_MASKSS_Pos;
} else
#endif
{
RTC_AlarmStructure.AlarmSubSecondMask = predivSync_bits << RTC_ALRMASSR_MASKSS_Pos;
}
/*
* The subsecond param is a nb of milliseconds to be converted in a subsecond
* downcounter value and to be compared to the SubSecond register
*/
if ((initMode == MODE_BINARY_ONLY) || (initMode == MODE_BINARY_MIX)) {
/* the subsecond is the millisecond to be converted in a subsecond downcounter value */
RTC_AlarmStructure.AlarmTime.SubSeconds = UINT32_MAX - (subSeconds * (predivSync + 1)) / 1000;
} else {
RTC_AlarmStructure.AlarmTime.SubSeconds = predivSync - (subSeconds * (predivSync + 1)) / 1000;
}
} else {
RTC_AlarmStructure.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
}
#endif /* RTC_SSR_SS */
if (period == HOUR_PM) {
RTC_AlarmStructure.AlarmTime.TimeFormat = RTC_HOURFORMAT12_PM;
} else {
RTC_AlarmStructure.AlarmTime.TimeFormat = RTC_HOURFORMAT12_AM;
}
RTC_AlarmStructure.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
RTC_AlarmStructure.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
RTC_AlarmStructure.AlarmDateWeekDay = day;
RTC_AlarmStructure.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
/* configure AlarmMask (M_MSK and Y_MSK ignored) */
if (mask == OFF_MSK) {
RTC_AlarmStructure.AlarmMask = RTC_ALARMMASK_ALL;
} else {
RTC_AlarmStructure.AlarmMask = RTC_ALARMMASK_NONE;
if (!(mask & SS_MSK)) {
RTC_AlarmStructure.AlarmMask |= RTC_ALARMMASK_SECONDS;
}
if (!(mask & MM_MSK)) {
RTC_AlarmStructure.AlarmMask |= RTC_ALARMMASK_MINUTES;
}
if (!(mask & HH_MSK)) {
RTC_AlarmStructure.AlarmMask |= RTC_ALARMMASK_HOURS;
}
if (!(mask & D_MSK)) {
RTC_AlarmStructure.AlarmMask |= RTC_ALARMMASK_DATEWEEKDAY;
}
}
#else
UNUSED(period);
UNUSED(day);
UNUSED(mask);
#endif /* !STM32F1xx */
/* Set RTC_Alarm */
HAL_RTC_SetAlarm_IT(&RtcHandle, &RTC_AlarmStructure, RTC_FORMAT_BIN);
HAL_NVIC_SetPriority(RTC_Alarm_IRQn, RTC_IRQ_PRIO, RTC_IRQ_SUBPRIO);
HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn);
}
#if defined(RTC_SSR_SS)
else {
/* SS have to be managed*/
#if defined(RTC_ALRMASSR_SSCLR)
RTC_AlarmStructure.BinaryAutoClr = RTC_ALARMSUBSECONDBIN_AUTOCLR_NO;
#endif /* RTC_ALRMASSR_SSCLR */
RTC_AlarmStructure.AlarmMask = RTC_ALARMMASK_ALL;
#ifdef RTC_ALARM_B
if (name == ALARM_B) {
/* Expecting RTC_ALARMSUBSECONDBINMASK_NONE for the subsecond mask on ALARM B */
RTC_AlarmStructure.AlarmSubSecondMask = mask << RTC_ALRMBSSR_MASKSS_Pos;
} else
#endif
{
/* Expecting RTC_ALARMSUBSECONDBINMASK_NONE for the subsecond mask on ALARM A */
RTC_AlarmStructure.AlarmSubSecondMask = mask << RTC_ALRMASSR_MASKSS_Pos;
}
#if defined(RTC_ICSR_BIN)
if ((initMode == MODE_BINARY_ONLY) || (initMode == MODE_BINARY_MIX)) {
/* We have an SubSecond alarm to set in RTC_BINARY_MIX or RTC_BINARY_ONLY mode */
/* The subsecond in ms is converted in ticks unit 1 tick is 1000 / fqce_apre */
RTC_AlarmStructure.AlarmTime.SubSeconds = UINT32_MAX - (subSeconds * (predivSync + 1)) / 1000;
} else
#endif /* RTC_ICSR_BIN */
{
RTC_AlarmStructure.AlarmTime.SubSeconds = predivSync - subSeconds * (predivSync + 1) / 1000;
}
/* Set RTC_Alarm */
HAL_RTC_SetAlarm_IT(&RtcHandle, &RTC_AlarmStructure, RTC_FORMAT_BIN);
HAL_NVIC_SetPriority(RTC_Alarm_IRQn, RTC_IRQ_PRIO, RTC_IRQ_SUBPRIO);
HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn);
}
#endif /* RTC_SSR_SS */
}
/**
* @brief Disable RTC alarm
* @param name: ALARM_A or ALARM_B if exists
* @retval None
*/
void RTC_StopAlarm(alarm_t name)
{
/* Clear RTC Alarm Flag */
#ifdef RTC_ALARM_B
if (name == ALARM_B) {
__HAL_RTC_ALARM_CLEAR_FLAG(&RtcHandle, RTC_FLAG_ALRBF);
} else
#endif
{
__HAL_RTC_ALARM_CLEAR_FLAG(&RtcHandle, RTC_FLAG_ALRAF);
}
/* Disable the Alarm A interrupt */
HAL_RTC_DeactivateAlarm(&RtcHandle, name);
}
/**
* @brief Check whether RTC alarm is set
* @param ALARM_A or ALARM_B if exists
* @retval True if Alarm is set
*/
bool RTC_IsAlarmSet(alarm_t name)
{
bool status = false;
#if defined(STM32F1xx)
UNUSED(name);
status = LL_RTC_IsEnabledIT_ALR(RtcHandle.Instance);
#else
#ifdef RTC_ALARM_B
if (name == ALARM_B) {
status = LL_RTC_IsEnabledIT_ALRB(RtcHandle.Instance);
} else
#else
UNUSED(name);
#endif
{
status = LL_RTC_IsEnabledIT_ALRA(RtcHandle.Instance);
}
#endif
return status;
}
/**
* @brief Get RTC alarm
* @param name: ALARM_A or ALARM_B if exists
* @param day: 1-31 day of the month (optional could be NULL)
* @param hours: 0-12 or 0-23 depends on the hours mode
* @param minutes: 0-59
* @param seconds: 0-59
* @param subSeconds: 0-999 (optional could be NULL)
* @param period: HOUR_AM or HOUR_PM (optional could be NULL)
* @param mask: alarm behavior using alarmMask_t combination (optional could be NULL)
* See AN4579 Table 5 for possible values
* @retval None
*/
void RTC_GetAlarm(alarm_t name, uint8_t *day, uint8_t *hours, uint8_t *minutes, uint8_t *seconds, uint32_t *subSeconds, hourAM_PM_t *period, uint8_t *mask)
{
RTC_AlarmTypeDef RTC_AlarmStructure;
if ((hours != NULL) && (minutes != NULL) && (seconds != NULL)) {
HAL_RTC_GetAlarm(&RtcHandle, &RTC_AlarmStructure, name, RTC_FORMAT_BIN);
*seconds = RTC_AlarmStructure.AlarmTime.Seconds;
*minutes = RTC_AlarmStructure.AlarmTime.Minutes;
*hours = RTC_AlarmStructure.AlarmTime.Hours;
#if !defined(STM32F1xx)
if (day != NULL) {
*day = RTC_AlarmStructure.AlarmDateWeekDay;
}
if (period != NULL) {
if (RTC_AlarmStructure.AlarmTime.TimeFormat == RTC_HOURFORMAT12_PM) {
*period = HOUR_PM;
} else {
*period = HOUR_AM;
}
}