
unsigned short MeasureClockfrequency()
{
	unsigned short TempCount;
	EA=0;
	//Make sure RTC is disabled to make it possible to write to RTCH, RTCL and other bits of RTCCON
	RTCCON = 0x00;
  	RTCCON = 0x00;
	// set reload value
  	// count frequency = clock source / 128 / RTCH,RTCL
  	RTCH = 0x00;
//  	RTCL = 0x01;
	RTCL = 0x2F;	

	//RTCPD=1;

	//First attempt, Result isn't good
	TempCount=0;
  	// select External crystal oscillator, disable interrupt source
  	RTCCON = 0x00;

	// start real time clock
	RTCCON |= 0x01;

	//Increase counter while the RTC doesn't time-out
	while (!(RTCCON & 0x80)) TempCount++;

	// clear RTCF interrupt flag and stop the real time clock
	RTCCON &= ~0x81;	

	//Try to determine frequency again, this result is good
	TempCount=0;
  	// select External crystal oscillator, disable interrupt source
  	RTCCON = 0x00;

	// start real time clock
	RTCCON |= 0x01;

	//Increase counter while the RTC doesn't time-out
	while (!(RTCCON & 0x80)) TempCount++;

	// clear RTCF interrupt flag and stop the real time clock
	RTCCON &= ~0x81;

	EA=1;

	return TempCount;
}
