Does anybody have any traps for young players that would be likely to cause an intermittent long pulse from TMR2 and/or the non-blocking delay function written below?
My program is purely interrupt driven except for a hearbeat signal I thought I would add as an afterthought. I set up TMR2 to generate approximately 1ms system interrupts, and increment an unsigned long 'currentSystemTime' at each tick. I have a generic delay function:
void delayMilliseconds(unsigned long ms) { // ms: duration
unsigned long start = currentSystemTime; // start: timestamp
for (;;) {
unsigned long now = currentSystemTime; // now: timestamp
unsigned long elapsed = now - start; // elapsed: duration
if (elapsed >= ms) // comparing durations: OK
return;
}
}
And I use it in a heartbeat function. My ISR decides if it's been 1000 counts since the last heartbeat. If so, it sets a flag which triggers the following code to run:
if (statusFlag){
for(int i=0; i<2; i++){
STATUS_LED_SetLow();
delayMilliseconds(100);
//__delay_ms(100);
STATUS_LED_SetHigh();
delayMilliseconds(100);
//__delay_ms(100);
}
statusFlag = 0;
lastTime = currentSystemTime;
I get several pulses that look perfectly fine, but I get random intervals where a particularly long pulse is followed by a short pulse... the sum of which is still less than what a "good" period should be. Take a look at the screenshots below to see what I mean:
"Good" Pulse
"Bad" Pulse
Processor is a PIC18F47K40
TMR2 not used for anything else besides 1ms tick.
TMR0 is used in oneshot mode for firing a triac. (not during screencaps)
EUSART1 is used to received 9600 baud data. (no data being received during screencaps)
This is pretty vexing behavior to me, although I'm a mostly self-taught, fairly unseasoned mcu programmer. Any ideas where to look?