Q3 Provide code that implements an interrupt service routine every 20 millisecon
ID: 3661448 • Letter: Q
Question
Q3 Provide code that implements an interrupt service routine every 20 milliseconds using timer 1. You may assume that the microcontroller is using a 40MHz SYS_FREQ and that PB_DIV=2. Provide comments to explain what each line does. Your ISR need only clear the interrupt flag and set a variable called tick_flag that has already been declared and initialised to zero. Provide code that initialises the timer and interrupt systems. The ISR has a function prototype of type:
void __ISR(_TIMER_1_VECTOR, ipl2) yourhandler(void);
should be used to contain the code for your interrupt service routine.
Provide code for an interrupt service routine and an initialisation routine that allows use of timer2 and timer 3 to provide a 5 second interrupt.
Explanation / Answer
When you want to use the interrupt service routine,
the prototype must be declared first.
void timer1_isr(void); //interrupt service routine
Prototype for timer1
Add this prototype after the library declaration.
when the timer0 is set as 8 bit mode, lower bits wi
ll be used only.
In the following parts, we take the timer1 as an ex
ample to see how it can be set.
OpenTimer1( TIMER_INT_ON & // I
nterrupt enabled
T1_8BIT_RW &
//set timer1 as two 8-bit registers
T1_SOURCE_INT &
//choose internal clock source (TOSC)
T1_PS_1_8 &
// Prescale Value: 1:8
T1_OSC1EN_OFF &
//Disable Timer1 oscillator
T1_SYNC_EXT_OFF
//Don’t sync external clock input
);
The interrupt is enabled; select the timer as two 8
-bit-register mode. And the timer uses
an internal clock source, the Prescale Value is cho
sen as 1:8. See the schematic of timer1
below.
Before you enable the interrupts, you should set th
e priority of the interrupts you used.
RCONbits.IPEN = 1; //Enable priority levels
on interrupts
RCONbits.SBOREN = 0; //Disable BOR
Then, enable the high or low priority interrupts fr
om the register INTCON,
INTCON = 0b10000000; //enable the high priority int
errupts
, bit7 and 6 are
concerned to high and low priority.
Last step will be that the corresponding timer inte
rrupt priority should be set and to
enable the interrupt.
These settings for the different timers are located
in different registers; you can find them
in datasheet. (TMRxIP: interrupt priority bit, TMRx
IE: interrupt enable bit)
IPR1bits.TMR1IP = 1; //Timer1 interrupt priority hi
gh
PIE1bits.TMR1IE = 1; //Timer1 interrupt enable
Now timer1 can count from 0x8ACF, till 0xFFFF. Afte
r that overflow will happen, then
this overflow will set the interrupt flag. If the s
ystem finds there is any interrupt flag set,
then it will jump into defined interrupt service ro
utine.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.