]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KLXX/rtc_api.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / mbed / targets / hal / TARGET_Freescale / TARGET_KLXX / rtc_api.c
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2013 ARM Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "rtc_api.h"
17 #include "PeripheralPins.h"
18
19 static void init(void) {
20     // enable RTC clock
21     SIM->SCGC6 |= SIM_SCGC6_RTC_MASK;
22
23     pinmap_pinout(PinMap_RTC[0].pin, PinMap_RTC);        //Map RTC clk input (if not NC)
24
25     // select RTC clock source
26     SIM->SOPT1 &= ~SIM_SOPT1_OSC32KSEL_MASK;
27     SIM->SOPT1 |= SIM_SOPT1_OSC32KSEL(PinMap_RTC[0].peripheral);
28 }
29
30 void rtc_init(void) {
31     init();
32
33     //Configure the TSR. default value: 1
34     RTC->TSR = 1;
35     
36     if (PinMap_RTC[0].pin == NC) {        //Use OSC32K
37         RTC->CR |= RTC_CR_OSCE_MASK;
38         //delay for OSCE stabilization
39         for(int i=0; i<0x1000; i++) __NOP();
40     }
41
42     // enable counter
43     RTC->SR |= RTC_SR_TCE_MASK;
44 }
45
46 void rtc_free(void) {
47     // [TODO]
48 }
49
50 /*
51  * Little check routine to see if the RTC has been enabled
52  * 0 = Disabled, 1 = Enabled
53  */
54 int rtc_isenabled(void) {
55     // even if the RTC module is enabled,
56     // as we use RTC_CLKIN and an external clock,
57     // we need to reconfigure the pins. That is why we
58     // call init() if the rtc is enabled
59
60     // if RTC not enabled return 0
61     SIM->SCGC5 |= SIM_SCGC5_PORTA_MASK;
62     SIM->SCGC6 |= SIM_SCGC6_RTC_MASK;
63     if ((RTC->SR & RTC_SR_TCE_MASK) == 0)
64         return 0;
65
66     init();
67     return 1;
68 }
69
70 time_t rtc_read(void) {
71     return RTC->TSR;
72 }
73
74 void rtc_write(time_t t) {
75     // disable counter
76     RTC->SR &= ~RTC_SR_TCE_MASK;
77
78     // we do not write 0 into TSR
79     // to avoid invalid time
80     if (t == 0)
81         t = 1;
82
83     // write seconds
84     RTC->TSR = t;
85
86     // re-enable counter
87     RTC->SR |= RTC_SR_TCE_MASK;
88 }