#include "common.h"

void init_rtc(void);
void deinit_rtc(void);

static char flag_1s;

void rtc_demo(int a,char** b)
{
    printf("****Kinets RTC Demo!****\r\n");
    printf("****Press any key to exit...****\r\n\r\n");
    init_rtc();
  
    while(!char_present())
    {
        if(flag_1s)
        {
            printf("%10d\r", RTC_TSR);
            flag_1s = 0;
        }
    }
    in_char(); //press any key to exit
    deinit_rtc();
    printf("\r\n");
}

/*
 * Initialize RTC module to count seconds
 */
void init_rtc(void)
{
    SIM_SCGC6|=SIM_SCGC6_RTC_MASK;
    printf("Initialize RTC\n");
    
    //Check to see if RTC is already enabled, meaning the RTC battery backup
    //  saved the RTC values. If not enabled, then we have to initalize RTC
    if((RTC_SR&RTC_SR_TCE_MASK)==0)
    {
        RTC_TSR = 0x00;
        // enable the oscillator and set load capacitors
        RTC_CR |=  RTC_CR_OSCE_MASK ;
        //set the Timer Alarm Register to 0 to disable RTC flag
        RTC_TAR = 0x01;  // set this register to other than 01 so set TAF
    }
    else
    {
        RTC_TAR = RTC_TSR + 1;
        printf("Already initialized\n");
    }
    enable_irq(INT_RTC-16);
    RTC_SR |= RTC_SR_TCE_MASK; // enable counter
    
    flag_1s = 0;
}

void deinit_rtc(void)
{    
    disable_irq(INT_RTC-16);
}

void int_rtc(void)
{
    uint32 rtc_sr = RTC_SR;
    
    if(rtc_sr|RTC_SR_TAF_MASK)
    {
        RTC_TAR += 1; // write new value to TAR to clear TAF
        flag_1s = 1;
    }
    else
    {
        RTC_SR &= ~RTC_SR_TCE_MASK;
        RTC_TSR = 0x00; // write to clear TOF or TIF
        RTC_SR |= RTC_SR_TCE_MASK;
    }
}
