CENG-336 Introduction to Embedded Systems Development Timers
Definitions A counter counts (possibly asynchronous) input pulses from an external signal A timer counts pulses of a fixed, known frequency usually the system clock for the processor A timer is basically a counter operated by the processor clock. It can count down a fixed number of clock cycles. Almost all microcontrollers have built in timers. CENG-336 Introduction to Embedded Systems Development 2
Definitions... Physically, PIC Timer is a register whose value is continually increasing to 255, and then it starts all over again: 0, 1, 2, 3, 4... 255, 0, 1, 2, 3, 4... etc. CENG-336 Introduction to Embedded Systems Development 3
Definitions... This incrementing is done in the background of everything a microcontroller does. It is up to programmer to think up a way how (s)he will take advantage of this characteristic for his needs. One of the ways is increasing some variable on each timer overflow. If we know how much time a timer needs to make one complete round, then multiplying the value of a variable by that time will yield the total amount of elapsed time. CENG-336 Introduction to Embedded Systems Development 4
Timers / Event Counters Uses of Programmable Timers and Event Counters 1. Generate real-time interrupts 2. Output precisely timed signals 3. Programmable baud rate generator 4. Measure time between events 5. Count external events 6. Generate event caused interrupts CENG-336 Introduction to Embedded Systems Development 5 III-65
Timers / Event Counters... Timer applications Frequency measurement Waveform generation (e.g. sound) time base (multi task system, sampling system,...) CENG-336 Introduction to Embedded Systems Development 6
Timer (8253 used in PC) Three identical timer elements Actually they are counters of the clock Inputs are clock and gate Output Changes or pulses when counting cycle is complete Modes Interrupt on countdown One-shot Pulse rate generator Square-wave generator Software-triggered strobe Hardware-triggered strobe Timer 0 Timer 1 Timer 2 Registers 0 - Counter 0 1 - Counter 1 2 - Counter 2 3 - Control for all clock gate output clock gate output clock gate output CENG-336 Introduction to Embedded Systems Development 7
Common Timer Applications Combinations of connection and mode Examples Internal speaker periodic interrupt using countdown from system clock and square-wave mode counter input controls frequency 18HZ interrupt 4.77 MHz clock counted down by 12, then by 64K pulse-rate generator mode Clk constant rate Gate - event Out to IRQ Time interval measurement Event counter Clk - event Gate - on Out - ignored Clk constant rate Gate - on Out to IRQ Delay or periodic interrupt CENG-336 Introduction to Embedded Systems Development 8
Available in all PICs PIC Timers May generate interrupts on timer overflow Some 8 bits, some 16 bits, some have prescalers Some can connect to external clock, some to the processor clock, some to either. Read/write a number as the current count is possible for some. CENG-336 Introduction to Embedded Systems Development 9
PIC Timers Can use external pin as clock in / clock out (i.e. for counting events) Warning: Some Peripherals shares timer resources. CENG-336 Introduction to Embedded Systems Development 10
PIC Timers The device has three readable and writeable hardware timers that can increment automatically each instruction cycle (if no prescaler is used). All timers can cause an interrupt on overflow, and then restart from zero. CENG-336 Introduction to Embedded Systems Development 11
PIC Timers Timer 0 Timer 1 timer/counter with prescale timer/counter with prescale Timer 2 timer only with prescale and postscale Watch Dog Timer (to be discussed later) CENG-336 Introduction to Embedded Systems Development 12
Timers TIMER0 is an 8-bit timer with an eight bit prescaler, which can make the timer run 2 to 256 times slower than normal TIMER1 is a 16-bit timer (two 8-bit registers) with a 1:1 to 1:8 prescaler and some other features. Used by given C code to generate soft timer and sound TIMER2 is an 8-bit timer with 1:1 to 1:16 prescaler and a 1:1 to 1:16 postscaler It also has a period register.used by given C code for PWM motor control CENG-336 Introduction to Embedded Systems Development 13
PIC Timers / Timer0 8 bit timer/counter with prescaler Readable and writeable 8-bit software programmable prescaler Internal or external clock set Interrupt on overflow from 0xFF to 0x00 Edge Select for external clock CENG-336 Introduction to Embedded Systems Development 14
Pre-Scaler Prescaler is a name for the part of a microcontroller which divides oscillator clock before it will reach logic that increases timer status. The number which divides a clock is defined through lowest-order order three bits in OPTION register. The highest divisor value is 256. This actually means that only at every 256th clock, timer value would increase by one. This provides us with the ability to measure longer time periods. CENG-336 Introduction to Embedded Systems Development 15
Input clock with frequency: f Pre-Scaler... f f/2 f/4 f/8 f/16 f/32 f/64 f/128 2 2 2 2 2 2 2 2 f/256 Input 0 Input 7 8 input to 1 output multiplexer Selects one of the inputs to connect to output Prescaler output PS2, PS1, PS0 : PreScaler select inputs: Binary number on these 3 bits determine which input (0..7) to be selected Note: if prescaler is disabled, input (f) is directly connected to the counter CENG-336 Introduction to Embedded Systems Development 16
Pre-Scaler... CENG-336 Introduction to Embedded Systems Development 17
Timers... After each count up to 255, timer resets its value to zero and starts with a new cycle of counting to 255. During each transition from 255 to zero, T0IF bit in INTCON register is set. If interrupts are allowed to occur, this can be taken advantage of in generating interrupts and in processing interrupt routine. It is up to programmer to reset T0IF bit in interrupt routine, so that new interrupt, or new overflow could be detected. CENG-336 Introduction to Embedded Systems Development 18
CENG-336 Introduction to Embedded Systems Development 19
Controlling Timers The timer is controlled by a number of bits in the Option Register. All processors are nothing more than a collection of gates. While this may be hard to tell in a very complex processor like a Pentium, the PIC is a very simple processor, and sometimes this actual simplicity makes itself obvious. The timer is one of those cases. CENG-336 Introduction to Embedded Systems Development 20
Option Register The option register is used to control a number of processor features. The least significant six bits of the option register control the timer logic. The OPTION_REG register is a readable and writable register which contains various control bits to configure the TMR0/WDT prescaler, the External INT Interrupt, TMR0, and the weak pull-ups on PORTB. CENG-336 Introduction to Embedded Systems Development 21
Selecting Parameters In order to set up the timer, it is necessary to first decide the time interval needed. The basic timer rate is one microsecond (with a 4 MHz crystal). This one microsecond clock is divided by the prescaler, which can be set to divide by 2, 4, 8, 16, 1 32, 64, 128 or 256. The timer register itself has 8 bits, so it can count to 256. Thus, it is necessary to service the timer with software at least every 256*256 microseconds, or 65.536 micro croseconds (assuming a 4 MHz clock). CENG-336 Introduction to Embedded Systems Development 22
Alternative Usage... Alternative to the internal oscillator clock, timer status can also be increased by the external clock on RA4/TOCKI pin. Choosing one of these two options is done in OPTION register through T0CS bit. If this option of external clock was selected, it would be possible to define the edge of a signal (rising or falling), on which timer would increase its value. CENG-336 Introduction to Embedded Systems Development 23
Example In practice, one of the typical example that is solved via external clock and a timer is counting full turns of an axis of some production machine, like transformer winder for instance. Let's wind four metal screws on the axis of a winder. These four screws will represent metal convexity. Let's place now the inductive sensor at a distance of 5mm from the head of a screw. CENG-336 Introduction to Embedded Systems Development 24
Example... Inductive sensor will generate the falling signal every time the head of the screw is parallel with sensor head. Each signal will represent one fourth of a full turn, and the sum of all full turns will be found in TMR0 timer. Program can easily read this data from the timer through a data bus. CENG-336 Introduction to Embedded Systems Development 25
Example... CENG-336 Introduction to Embedded Systems Development 26
Initializing the Timer CENG-336 Introduction to Embedded Systems Development 27
Initializing the Timer... Prescaler can be assigned either timer TMR0 or a watchdog. Watchdog is a mechanism which microcontroller uses to defend itself against programs getting stuck. Prescaler is accorded to timer TMR0, or to watchdog timer trough PSA bit in OPTION register. By clearing PSA bit, prescaler will be accorded to timer TMR0. When prescaler is accorded to timer TMR0, all instructions of writing to TMR0 register (CLRF TMR0, MOVWF TMR0, BSF TMR0,...) will clear prescaler. Prescaler change is completely under programmer's control, and can be changed while program is running. CENG-336 Introduction to Embedded Systems Development 28
Option Register... CENG-336 Introduction to Embedded Systems Development 29
All of the acronyms along the bottom of the diagram refer to bits in the option register, except for T0IF (Timer0 interrupt flag), which is a bit in the INTCON register. Starting at the left, the processor clock is divided by four and fed into a gate. This division by four results in a single cycle per instruction execution. In the case of a 4MHz processor crystal, this conveniently results in a 1 MHz clock. CENG-336 Introduction to Embedded Systems Development 30
When bit T0CS (Timer0 clock select) is false, the clock is fed into a prescaler. The prescaler ratio is set by bits PS2, PS1 and PS0. *Wrong* If the PSA bit is false, the output of the prescaler is then routed to the TMR0 register, after synching with other internal clocks. This causes a 2 cycle delay, which is only apparent if we load the TMR0 register with a value. CENG-336 Introduction to Embedded Systems Development 31
Every cycle of the prescaler output increments TMR0 by one. We can read as well as write the contents of TMR0. Whenever TMR0 overflows, the T0IF bit in the INTCON register is set. If the INTCON bit T0IE (Timer 0 interrupt enable) is set, this transition of the T0IF bit causes an interrupt, so we will always take care to clear T0IE. CENG-336 Introduction to Embedded Systems Development 32
CENG-336 Introduction to Embedded Systems Development 33
PIC Timers / Timer1 16-bit timer/counter with pre-scaler Readable and writeable 1, 2, 4, 8 programmable pre-scaler Internal or external clock select External clock can be syn. or asyn. Interrupt on overflow Second crystal permitted CENG-336 Introduction to Embedded Systems Development 34
PIC Timers / Timer2 8-bit timer/counter with pre-scaler and post-scaler scaler Readable and writeable 1, 4 or 16 programmable pre-scaler 4-bit programmable post-scaler scaler Interrupt on overflow Output to port pin CENG-336 Introduction to Embedded Systems Development 35
Selecting Parameters In order to set up the timer, it is necessary to first decide the time interval needed. The basic timer rate is one microsecond (with a 4 MHz crystal). This one microsecond clock is divided by the prescaler, which can be set to divide by 2, 4, 8, 16, 1 32, 64, 128 or 256. The timer register itself has 8 bits, so it can count to 256. Thus, it is necessary to service the timer with software at least every 256*256 microseconds, or 65.536 milliseconds (assuming a 4 MHz clock). CENG-336 Introduction to Embedded Systems Development 36
Selecting Parameters... The timer register itself can be used to divide by any arbitrary number by simply reloading it whenever the register overflows, and; additional software counters can be updated based on the timer, so it is possible to arrange any desired time. The catch is that, the higher the resolution needed, the more frequently software must service its counters. CENG-336 Introduction to Embedded Systems Development 37
Selecting Parameters... Consider for a moment an application that requires a 10-millisecond timer. If the prescaler is set to divide by 64, the timer register can count to 16.384 milliseconds. If the timer register is preloaded with 100, then the timer will expire in 9.984 milliseconds. (256-100)/256 = 9.984/16.384 (Check?) CENG-336 Introduction to Embedded Systems Development 38
Selecting Parameters... If one were to use a prescaler division of 16, it is possible to get a delay of exactly 10 milliseconds, however, it would require servicing the timer in software every two milliseconds and maintaining a counter in software. The programmer needs to consider how good is good enough,, balanced against the complexity and the potential that time could be taken from other tasks to watch the clock. Real-time Systems? CENG-336 Introduction to Embedded Systems Development 39
Setting up the Timer To set up the timer, one must first disable interrupts so that an interrupt doesn t occur when the timer expires. Then, enable the timer and assign the prescaler to the timer. Establish the prescaler value, and finally, load the timer register. CENG-336 Introduction to Embedded Systems Development 40
Setting up the Timer... The bits for enabling the timer, Assigning the prescaler to the timer, The bits that set the prescaler division ratio are all in the same register. Thus, these values may be set bit by bit, or by simply loading the Option register with a value (assuming it is possible to determine benign values for the other bits). CENG-336 Introduction to Embedded Systems Development 41
Setting up the Timer... Whenever the timer expires, the T0IF bit in the INTCON register will be set. We must clear this bit, reload the timer register, and then execute the code that is to be done at this time. CENG-336 Introduction to Embedded Systems Development 42
Setting up the Timer... CENG-336 Introduction to Embedded Systems Development 43
Setting up the Timer... In code, the setup portion might look something like: banksel INTCON bcf INTCON,T0IE banksel OPTION_REG bcf OPTION_REG,T0CS bcf OPTION_REG,PSA bcf OPTION_REG,PS2 ; \ bsf OPTION_REG,PS1 bsf OPTION_REG,PS0 ; / movlw D 100 movwf TMR0 ; Mask timer interrupt ; Enable timer ; Prescaler to timer ; >- 1:16 prescale ; Timer will count ; 156 (256-100) counts CENG-336 Introduction to Embedded Systems Development 44
Setting up the Timer... Clearly, the individual bits in the option register could all be set with a single store. If we didn t care about the RB0 interrupt, the weak pull-ups, or the transition of RA4, then instead of five bit manipulations we could have said: movlw B 10000011 movwf OPTION_REG ; Set up prescaler and ; timer CENG-336 Introduction to Embedded Systems Development 45
Setting up the Timer... The execution loop might look something like: main btfss INTCON,T0IF ; Did timer overflow? goto main ; No, hang around some more movlw D 100 ; Timer will count movwf TMR0 ; 156 (256-100) counts bcf INTCON,T0IF ; reset overflow flag call DoCode ; Execute main code goto main ; Go back and wait CENG-336 Introduction to Embedded Systems Development 46
Operation Timer mode is selected by clearing the T0CS bit (OPTION<5>). In timer mode, the Timer0 module will increment every instruction cycle (without prescaler). If the TMR0 register is written, the increment is inhibited for the following two instruction cycles. The user can work around this by writing an adjusted value to the TMR0 register. CENG-336 Introduction to Embedded Systems Development 47
Operation... Counter mode is selected by setting the T0CS bit (OPTION<5>). In counter mode, Timer0 will increment either on every rising or falling edge of the T0CKI pin. The incrementing edge is determined by the Timer0 Source Edge Select the T0SE bit (OPTION<4>). Clearing the T0SE bit selects the rising edge. CENG-336 Introduction to Embedded Systems Development 48
TMR0 Interrupt TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h. This overflow sets bit T0IF (INTCON<2>). Interrupt can be masked by clearing bit T0IE (INTCON<5>). Bit T0IF must be cleared in software by the Timer0 module interrupt service routine before re-enabling enabling this interrupt. TMR0 interrupt cannot awaken the processor from SLEEP since the timer is shut-off during SLEEP. CENG-336 Introduction to Embedded Systems Development 49
Timer0 & External Clock When an external clock input is used for TMR0, it must meet certain requirements These requirements ensure the external clock can be synchronized with the internal phase clock (TOSC). Also, there is a delay in the actual incrementing of TMR0 after synchronization. CENG-336 Introduction to Embedded Systems Development 50
TMR0 PreScaler An 8-bit 8 counter is available as a pre-scaler for the Timer0 module, or as a post-scaler scaler for the Watchdog Timer. For simplicity, this counter is being referred to as prescaler in the Timer0 description. Thus, a prescaler assignment for the Timer0 module means that there is no postscaler for the Watchdog Timer, and vice-versa. versa. CENG-336 Introduction to Embedded Systems Development 51
TMR0/WDT PreScaler... The PSA and PS2:PS0 bits (OPTION<3:0>) determine the prescaler assignment and prescale ratio. When assigned to the Timer0 module, all instructions writing to the TMR0 register (e.g., CLRF TMR0, MOVWF TMR0, BSF TMR0,x...etc.) will clear the prescaler. When assigned to WDT, a CLRWDT instruction will clear the prescaler along with the Watchdog Timer. The prescaler is not readable or writable. CENG-336 Introduction to Embedded Systems Development 52
Timer0 Initialization CLRF TMR0 CLRF INTCON BSF STATUS, RP0 MOVLW 0xC3 MOVWF OPTION_REG (Internal Clock Source) BCF STATUS, RP0 ; Bank0 ;** BSF INTCON, T0IE ; Enable TMR0 interrupt ;** BSF INTCON, GIE ; Enable all interrupts ; ; The TMR0 interrupt is disabled, do polling on the overflow bit ; T0_OVFL_WAIT BTFSS INTCON, T0IF GOTO T0_OVFL_WAIT ; Timer has overflowed ; Clear Timer0 register ; Disable interrupts and clear T0IF ; Bank1 ; PortB pull-ups are disabled, ; Interrupt on rising edge of RB0 ; Timer0 increment from internal clock ; with a prescaler of 1:16. CENG-336 Introduction to Embedded Systems Development 53
Watchdog Timers Watchdog timers are used to guard a system against lock-up due to software errors or soft failures in hardware. Often included in CPU supervisor circuits. Retriggering usually done in the main program loop. CENG-336 Introduction to Embedded Systems Development 54