/*
	MGCHRGER.C

	BL14xx/MicroG and BL15xx/MicroG2

	Use function Charger1302() to charge a large cap or battery on VBAT (H3-21).
	Connect + pin to VBAT and - pin to GND. Run program until the capacitor or
	battery is charged.

	Power down and see that data is preserved in the MicroG.
	
	If you are using the MicroG Prototyping Board, the on-board 0.1 uF supercap
	is charged. It takes 20-30 minutes to fully charge the capacitor. When fully
	charged, the supercap can retain data in the DS1302 for 2 to 3 days.
*/

void showtime(struct tm thistime);
void loadtime(struct tm *thistime, int hour, int min, int sec,
					int mon, int mday,int year, int wday);
main()
{
struct tm thistime;
struct tm thattime;
int i,j,k;
char old_sec;

	hitwd();
	printf("Reading time from the DS1302.\n");
	tm_rd(&thistime);          // read time from the DS1302
	showtime(thistime);

	printf("Reading ram data from the DS1302.\n");  
	for(i=0;i<=30;i++)
	{
		printf("DS1302 RAM[%d] = %d\n", i, ReadRam1302(i));
		hitwd();
	}

	Charger1302(1, 2, 4);      // set on the trigger charger
										// 2 diode and 4K resistance
	printf("Writing data to the DS1302 ram area.\n");
	for(i=0;i<=30;i++)
	{
		WriteRam1302(i,i);
	}

	if(mktime(&thistime) == 0L)
	{
		loadtime(&thattime, 8, 0, 0, 4, 1, 95, 6);
		tm_wr(&thattime);
	}
	
	hitwd();
	printf("Wait for capacitor or battery to charge up \n");
	printf("before powering system down.\n");
	printf("The DS1302 will retains its data if a capacitor\n");
	printf("or a chargeable battery is connected to VBAT and GND.\n");

	old_sec = 0;

	while(1)
	{
		hitwd();
		runwatch();
		tm_rd(&thistime);
		if( old_sec != thistime.tm_sec)
		{
			showtime(thistime);
			old_sec = thistime.tm_sec;
		}
	}  
}

void showtime(struct tm thistime)
{
	printf("%02d:%02d:%02d  %02d-%02d-%02d-%1d\n",
				thistime.tm_hour,
				thistime.tm_min,
				thistime.tm_sec,
				thistime.tm_mon,
				thistime.tm_mday,
				thistime.tm_year,
				thistime.tm_wday);
}

void loadtime(struct tm *thistime, int hour, int min, int sec,
					int mon, int mday,int year, int wday)
{
	thistime->tm_hour = hour;
	thistime->tm_min = min;
	thistime->tm_sec = sec;
	thistime->tm_mon = mon;
	thistime->tm_mday = mday;
	thistime->tm_year = year;
	thistime->tm_wday = wday;
}
