/******************** (C) COPYRIGHT 2003 STMicroelectronics ********************
* File Name          : timers.c
* Author             : jrl
* Date First Issued  : 1/1/04
* Description        : functions for using the wdog as a gp timer
*********************************************************************************
* History:
* 2/8/04: first issued
*
*********************************************************************************/
#include "71x_lib.h"

void wait_us (u32 Time)
	// wait Time(in uS) 
  {
	//WDG_ECFlagClear();
	WDG_PeriodValueConfig ( Time );  
	
	//WDG->CR = 2;
	//WDG->PR = 0;
	//WDG->VR = Time *3;
	/*if (Time > 2)
		WDG->VR = (Time /3) * 100;
	else if (Time ==2)
	  	WDG->VR = 66;
	else if (Time ==1)
		WDG->VR = 33;  */
	WDG_CntOnOffConfig ( ENABLE );
	while (WDG_ECStatus( ) < 1);
	//while ((WDG->SR & 1) < 1);
	WDG_CntOnOffConfig ( DISABLE );
	WDG_ECFlagClear ( );
	
  }

void wait_ms (u32 Time)
  {
  	u32 i;
	
	for (i=0; i < Time; i++)
	  {
		wait_us (1000);
		
          }
  }

void wait_s (u32 Time)
  {
  	u32 i;
	
	for (i=0; i < Time; i++)
	  {
		wait_ms (1000);
		
          }
  }


void rtcinit (void)
{
  u32 Myprescaler;

  
// Configure RTC prescaler
  Myprescaler = 0x00007d00;  //prescaler for  1 clock per second
  RTC_PrescalerConfig ( Myprescaler );

// Clear Pending Flags
  RTC_FlagClear ( RTC_OWIR );
  RTC_FlagClear ( RTC_AIR  );
  RTC_FlagClear ( RTC_SIR  );
  RTC_FlagClear ( RTC_GIR  );

// Enable RTC IRQ channel
//  EIC_IRQChannelConfig( RTC_IRQChannel, ENABLE );
//  EIC_IRQChannelPriorityConfig( RTC_IRQChannel, 3);
//  EIC_IRQConfig( ENABLE );


/////////
/* Initialize the XTI */
  XTI_Init();
  /* Set Line 15 edge */
  XTI_LineModeConfig(XTI_Line15, XTI_RisingEdge);
  /* Enable the External interrupts on line 15 */
  XTI_LineConfig(XTI_Line15, ENABLE);
  /* Set the XTI mode */
  XTI_ModeConfig(XTI_WakeUp, ENABLE);

  /* Configure the XTI IRQ channel */
  /*  Set the XTI IRQ Channel priority to 1*/
  //EIC_IRQChannelPriorityConfig(XTI_IRQChannel,1);
  /* Enable XTI IRQ Interrupts */
  //EIC_IRQChannelConfig(XTI_IRQChannel,ENABLE);
  /* Enable IRQ interrupts on EIC */
  //EIC_IRQConfig(ENABLE);  
  
  /* Configure the P0.15 in INOUT-WeakPP mode */
  GPIO_Config(GPIO0,0x0001<<0x0F,GPIO_IPUPD_WP);

  /* Configure the P0.0 in Push-Pull Output mode */
  //GPIO_Config(GPIO0,0x0001,GPIO_OUT_PP);



///////////////

RTC_AlarmConfig ( RTC_CounterValue () + 65); //wait 65 seconds for alarm


// Enable alarm Interrupt
  RTC_ITConfig( RTC_AIR | RTC_GIR, ENABLE );

// Configure Port 2 pins
 GPIO_Config (GPIO0, 0x1000, GPIO_OUT_PP);
 GPIO0->PD = 0x0000;

// never-ending loop
 // while (1);
}
	
u32 uptime (void)
// return the contents of the rtc in hours assumes rtc clock = 1/second
  {

   u32 hours;

   hours = (RTC_CounterValue ()/3600);

   return (hours);

  }

void delay(u32 clocks)
  {
	u32 i;
	
	for (i=0; i < clocks; i++);

  }
