Page 248 - Mechatronics with Experiments
P. 248
234 MECHATRONICS
(timer or counter), and so on. When a timer overflows, interrupt is generated. The timer
operation is controlled by a set of registers:
1. The INTCON register is used to configure interrupts in the microcontroller.
2. The TxCON register is used to configure TIMERx, where “x” is 0, 1, 2, or 3 for
the corresponding timer. Configuration of a timer involves the selection of the timer
source signal (internal or external), pre- or post-scaling of the source signal, source
signal edge selection, enable/disable timer.
3. The TRISA register port may be used to select an external source for the TIMER at
port A pin 4 (RA4).
4. The TMRxL and TMRxH are 8-bit register pairs that make up the 16-bit timer/counter
data register.
TIMER2 sets the interrupt status flag when its data register is equal to the PR2 register,
whereas TIMER0, TIMER1 and TIMER3 set the interrupt status flag when there is overflow
from maximum count to zero (from FFh to 00h in 8-bit mode, and from FFFFh to 0000h in
16-bit mode). The registers used to indicate the interrupt status are INTCON, PIR1, PIR2.
The interrupt can be masked by clearing the appropriate timer interrupt mask bit of the
timer interrupt control registers.
Counter mode is selected by setting the T0CON register bit 5 to 1. In counter mode,
TIMER0 increments on every state transition (on either falling or rising edge) at pin
RA4/T0CKI.
C library functions used to setup and operate timers are (the following functions are
available for all timers on the PIC microcontroller, TIMER0, TIMER1, TIMER2, TIMER3),
#include <timers.h>
OpenTimer0(char config) ; /∗ Open and configure timer 0: enable interrupt,
select 8/16-bit mode, clock source, prescale value ∗/
...
result = ReadTimer0() ; /∗ read the timer 0∗/
...
WriteTimer0(data) ; /∗ write to timer register 0 ∗/
...
CloseTimer0() ; /∗ close (disable) timer 0 and its interrupts ∗/
Often, a certain amount of time delay is needed in the program logic. C-library func-
tions provide programmable time delay where the minimum delay unit is one instruction
cycle. Therefore, the actual real-time delay accomplished by these functions depends on
the processor operating speed.
#include <delays.h>
....
Delay1TCY(); /∗ Delay 1 instruction cycle ∗/
Delay10TCYx(unsigned char unit);
/∗ unit=[1, 255], Delay period = 10∗unit instruction cycle ∗/
Delay100TCYx(unsigned char unit);
/∗ unit=[1, 255], Delay period = 100∗unit instruction cycle ∗/
Delay1KTCY(unsigned char unit);
/∗ unit=[1, 255], Delay period = 1000∗unit instruction cycle ∗/
Delay10KTCY(unsigned char unit);
/∗ unit=[1, 255], Delay period = 10000∗unit instruction cycle ∗/
....