Hi all. I need to implement delays of a few milliseconds on a PIC32MX microcontroller, and would just like some feedback on a possible method I plan to try.
I plan to use the Timer1 interrupt, opening and configuring it as follows.
The relevant interrupt service routine is this.
.
The delay routine itself is
.
The above routines used global variables defined as
One of my concerns is that - with the above code - Timer1 is being opened and closed every time the delay routine is called. I'm just wondering if this could be a problem.
Note: I would prefer to use interrupts than just loop constructs by themselves - as, according to my understanding, this will yield more reliable and precise time durations. I invite correction on that however. (E.g. the delays are required for the handshake in a serial communications protocol. Maybe the delays don't need to be so accurate?)
The code is compiling fine, but I'm still waiting for a PIC32 starter kit to arrive so haven't tried this on the actual hardware yet. (And even if it does "work" that doesn't necessarily mean it's the preferred solution.)
I plan to use the Timer1 interrupt, opening and configuring it as follows.
Rich (BB code):
#define FOSC 40e6
#define PRESCALE 256
/*
Set the tick period.
The timers are clocked by the peripheral bus. By default, the PBCLK (Peripheral Bus Clock) frequency is the SYSCLK frequency divided by 8
*/
#define PB_DIV 8
#define TICK_PERIOD_MSECS 1 /* tick period in milliseconds */
#define TICK_PERIOD ((FOSC/PB_DIV/PRESCALE) * TICK_PERIOD_MSECS/1000)
void start_timer() {
OpenTimer1(T1_ON | T1_SOURCE_INT | T1_PS_1_256, TICK_PERIOD);
ConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_2);
}
Rich (BB code):
void __ISR(_TIMER_1_VECTOR, ipl2) _Timer1Handler(void) {
// clear the interrupt flag
mT1ClearIntFlag();
period_elapsed++;
if (period_elapsed == delay_period) {
delay_over = 1;
CloseTimer1();
}
}
The delay routine itself is
Rich (BB code):
void delay_ms(UINT8 ms) {
delay_period = ms;
period_elapsed = 0;
delay_over = 0;
start_timer();
while (!delay_over) {
asm("nop"); // do nothing
}
}
The above routines used global variables defined as
Rich (BB code):
UINT8 delay_period; // delay period in milliseconds
UINT8 period_elapsed = 0; // period elapsed
UINT8 delay_over = 0;
Note: I would prefer to use interrupts than just loop constructs by themselves - as, according to my understanding, this will yield more reliable and precise time durations. I invite correction on that however. (E.g. the delays are required for the handshake in a serial communications protocol. Maybe the delays don't need to be so accurate?)
The code is compiling fine, but I'm still waiting for a PIC32 starter kit to arrive so haven't tried this on the actual hardware yet. (And even if it does "work" that doesn't necessarily mean it's the preferred solution.)