I am currently working with S32k142 microcontroller. I would like to configure a 1ms delay using the RTC clock. I have an external RTC clock(32.768KHz) which has been configured to drive the RTC module of the microcontroller. I have programmed the following:
void wait_1ms_RTC(void)
{
UINT32 tpr = (UINT32)RTC->TPR; // RTC Time Prescaler Register: increments at a freq of 32.768KHz
UINT32 tsr = (UINT32)RTC->TSR; // RTC Time Seconds Register: increments every second
tpr = tpr + (UINT32)32; // 32->1ms(32*30.51us=976.32us)
if (tpr <= 32767)
{
while (((UINT32)RTC->TPR <= tpr)&& ((UINT32)RTC->TSR <= tsr));
}
else
{
while (((UINT32)RTC->TPR <= (tpr - 32768))&& ((UINT32)RTC->TSR <= tsr+1));
}
}
This code simply reads the TPR and TSR register, and waits till the TPR register and TSR register reached certain value that corresponds to 1ms. This works most of the time except in few occasions where it does not create a delay of 1ms ,I am assuming it is happening during the roll over, but still cannot figure out where exactly is the issue in the code.
Any ideas on how this can be solved?