Cab Jones

RTC Module doesn't work well

Discussion created by Cab Jones on Jun 25, 2012
Latest reply on Jun 25, 2012 by bigmac

CW 10.2 (1.0.0) Win7x64 MC9S08LG32


I want to create a real-time clock with ms resolution.  Tried using the RTC module, but the register functions are less than ideal.  I would not like to have an interrupt every ms--how about every 150 ms?  That seems reasonable but not without flaws for my MCU.


This looks like a reasonable try:

void startRTC() {  SCGC1_RTC= 1; RTCSC_RTCLKS= 0; //binary 00 RTCSC_RTCPS=  8; //binary 1000, ms resolution RTCMOD= 250;            //250ms rollover  RTCSC_RTIE= 1;  //enable RTC rrupts} //--------------------------------------------startRTC()
ulong rtcMs=0;

interrupt VectorNumber_Vrtc void Vrtc_isr(void) {//every 250 ms. RTCSC_RTIF= 1; //Clear interrupt rtcMs+= 250;        //Update} //--------------------------------------------Vrtc_isr()ulong getMs(void) { //ms since power-up (1yr rollover) ulong ms; RTCSC_RTIE= 0; ms= rtcMs + RTCCNT; RTCSC_RTIE= 1; return ms;} //-------------------------------------------getMs()


The problem is, what happens when RTCMOD is reached?  The interrupt occurs sometime later, but BAM! as soon as RTCMOD=250, RTCCNT is zeroed--but rtcMs has not been increased.  So until the interrupt occurs, getMs() has lost 250ms.  No way to avoid occasional mistakes--the user could be -reading- rtcMs when RTCMOD rolls over.


A solution would be an option to not zero RTCCNT when RTCMOD is reached--let the isr clear RTCCNT, that would work.  I don't see that option.  The example in the manual shows a 1-sec interrupt, but the resolution is only one second.  Am I missing a feasible way to use the RTC module and create a ms-timer without getting interrupted every ms?

- Well perhaps getMs() could look at the RTIF flag and call the isr.  But this looks like a race condition as well.  The manual is silent.