1 | int main(void)
|
2 | {
|
3 | init_usart(&debug_uart);
|
4 | SysTick_Config(SystemCoreClock / 1000);
|
5 | if(time_rtc_init() == ERROR)
|
6 | {
|
7 | DEBUG_PUTS("RTC Error\n");
|
8 | }
|
9 | while(1);
|
10 | }
|
11 |
|
12 | ErrorStatus time_rtc_init(void)
|
13 | {
|
14 | RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
|
15 |
|
16 | PWR_RTCAccessCmd(ENABLE);
|
17 | RCC_RTCResetCmd(ENABLE);
|
18 | RCC_RTCResetCmd(DISABLE);
|
19 | // See AN 3371 (Doc ID 018624) Rev 4, p. 7
|
20 | rtc_write_enable(); // (1) Write 0xCA, 0x53 into the RTC_WPR register
|
21 | RTC->ISR |= RTC_ISR_INIT; // (2) Set INIT bit to '1' in RTC_ISR register
|
22 |
|
23 | tick1ms = 0; //wird im SysTick hochgezaehlt
|
24 | while(!(RTC->ISR & RTC_ISR_INITF)) // (3) Poll INITF bit of in RTC_ISR until it is set
|
25 | {
|
26 | if(tick1ms > 1000) return ERROR;
|
27 | }
|
28 |
|
29 | #if defined(RTC_HSE) && (RTC_HSE)
|
30 | RCC_RTCCLKConfig(RCC_RTCCLKSource_HSE_Div16); //Input = HSE_VALUE/16 -> 1 MHz
|
31 | RTC->PRER = (uint32_t)(7999); // (4) Write first the synchronous value and then write the asynchronous
|
32 | RTC->PRER |= (uint32_t)(124 << 16);
|
33 | #else
|
34 | RCC_LSEConfig(RCC_LSE_ON);
|
35 | tick1ms = 0;
|
36 | while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
|
37 | {
|
38 | if(tick1ms > 1000) return ERROR;
|
39 | }
|
40 | RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
|
41 |
|
42 | RTC->PRER = (uint32_t)(255); // (4) Write first the synchronous value and then write the asynchronous
|
43 | RTC->PRER |= (uint32_t)(127 << 16);
|
44 | #endif
|
45 |
|
46 |
|
47 | timestamp_t default_time = { 2015, 01, 01, 00, 00, 00, WDAY_SATURDAY}; //01.01.2000, 00:00:00
|
48 | rtc_store_time_int(&default_time); // (5) Set RTC_TR and RTC_DR registers
|
49 |
|
50 | RTC->CR &= ~RTC_CR_FMT; //24h // (6) Set FMT bit in RTC_CR register
|
51 | RTC->ISR &= ~RTC_ISR_INIT; // (7) Clear the INIT bit in the RTC_ISR register
|
52 | rtc_write_protect(); // (8) Write "0xFF" into the RTC_WPR register
|
53 | return SUCCESS;
|
54 | }
|
55 |
|
56 | void rtc_store_time_int(const timestamp_t* timestamp)
|
57 | {
|
58 | RTC->DR = byte_to_bcd(timestamp->year - 2000) << 16
|
59 | | timestamp->wday << 13 //always < 10, so BCD == BIN
|
60 | | byte_to_bcd(timestamp->month) << 8
|
61 | | byte_to_bcd(timestamp->day);
|
62 | RTC->TR = byte_to_bcd(timestamp->hour) << 16
|
63 | | byte_to_bcd(timestamp->minute) << 8
|
64 | | byte_to_bcd(timestamp->second);
|
65 | }
|