0% found this document useful (0 votes)
38 views

Chapter 6 Timers

Timer modules like Timer0, Timer1, and Timer2 are used in microcontrollers to generate time delays and measure time intervals. They work by counting internal clock pulses or external pulses. Timer0 and Timer1 can count internal or external pulses, while Timer2 only counts internal pulses. When the timer overflows, an interrupt can be generated. The timers allow generating accurate time-related functions rather than using software delays.

Uploaded by

ellyshacb-wp21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Chapter 6 Timers

Timer modules like Timer0, Timer1, and Timer2 are used in microcontrollers to generate time delays and measure time intervals. They work by counting internal clock pulses or external pulses. Timer0 and Timer1 can count internal or external pulses, while Timer2 only counts internal pulses. When the timer overflows, an interrupt can be generated. The timers allow generating accurate time-related functions rather than using software delays.

Uploaded by

ellyshacb-wp21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

BTEH 2223 MICROPROCESSOR SYSTEMS

CHAPTER 6: TIMERS

1
A TIMER OVERVIEW
 Many microcontroller applications, such as generating signals,
measuring the duration of a signal, and keeping date and time,
use time as their variable.

 For this reason, microcontrollers need to have internal resources


to accurately measure time. Each PIC microcontroller has at
least one basic timer module called Timer0, although the
majority of medium-end PICs can have two additional timers:
Timer1 and Timer2.

 In addition, some PICs have capture/compare/PWM (CCP)


modules that increase the possibilities of the basic timers.

INTCON
2
 These counters can be programmed as a timer to count machine cycles, or as a counter to
count the external pulses that are connected to T0CKI pin.

 The count number stored by each counter can be read or modified by accessing the
special function registers associated with that timer such as TMR0 register.

 Some of the bits in these registers are used to notify of counter overflow, being able to
generate an interrupt request to the microcontroller such as the TOIF bit and TOIE bit
in INTCON register.

 To = the overflow time for timer.


Ti = the period for the input pulses (basically is instruction cycle if the timer module
works as timer) to the internal Timer.
N = the number of pulses needed before the 8-bit or 16-bit counter (TMR0 or TMR1)
overflow.
P = the division factor for the prescaler.

3
 Highlight  In low-power mode (sleep), the main oscillator stops working, resulting in
Timer0 not working when the microcontroller is sleeping.
Block Diagram of the 16F84A TIMER0 Module
-TMR0 register (SFR memory location 01 in bank 0) stores the 8-bit data of Timer 0.
- Timer 0is configurable and controlled by a number of bits in the OPTION register.
- There are two possible sources of the clock input to the TMR0 counter , selected by bit
T0CS in OPTION register.
 internal instruction cycle frequency or external RA4 pin (i.e. pin 3 of 16F84A)
- If PSA =1, then multiplexer selects the input path that avoids the prescaler (prescaler is
controlled by PS2, PS1, PS0 to allow frequency division of incoming clock signal).

4
The 16F84A OPTION Register

5
Application 1: Object The simplest application of Timer 0 is to use it as a counter, counting pulses
entering the microcontroller through the external input. This demo program
or Event Counting configures the Timer 0 module to count paddle presses on the Ping-pong hardware.

;********************************************************************
;cntr_demo Counter Demonstration
;This program demos Timer 0 as counter, using ping-pong hardware
;TJW 15.4.05 Tested 15.4.05
;********************************************************************
...
...
list p=16F84A
#include p16f84A.inc
;
org 00
; Initialise
bsf status,rp0 ;select memory bank 1
movlw B'00011000'
movwf trisa ;port A according to above pattern
movlw 00
movwf trisb ;all port B bits output
movlw B'00101000';set up TMR0 for external input, +ve edge,
;no prescale
movwf TMR0 ;as we are in Bank 1, this addresses OPTION
bcf status,rp0 ;select bank 0
;
movlw 04 ;switch on "out of play" led to show power is on
movwf porta
loop movf TMR0,0 ;Continuously display Timer 0 on Port B
movwf portb ;every press of the right paddle causes a binary 6
;display on the play LEDs to increment by one.
goto loop
end
Application 2: Hardware-Generated Time Delays
We saw in an earlier lecture how program loops could be used to generate time delays. Here we hand over that delay
function to the Timer. The internal oscillator signal is now used as clock source. The example below shows part of
the initialisation, as well as the delay routine. How useful is this program change, compared to the previous software
loop?
...
;Initialise Clock = 800 kHz
org 0010 duty cycle = 200 kHz
Start bsf status,5 ;select memory bank 1 Prescaler = 8
movlw B'00011000' New duty cycle = 200/8 kHz
movwf trisa ;port A according to above pattern = 40 us
movlw 00
movwf trisb ;all port B bits op
movlw B'00000010' ;set up TMR0 for internal input, prescale by 8
movwf TMR0 ;as we are in Bank 1, this addresses OPTION
bcf status,5 ; select bank 0
... You want 125 Timer 0 input cycles to get 5 ms
... exact delay, so 256-125+2 = 133. If Timer0
;introduces delay of 5ms approx works as timer, it is necessary to keep in mind
delay5 movlw D’133’ that the125
;preload counter, so that counting is inhibited
cycles, eachduring two machine
cycles after writing data
;of 40us, occur before timer overflow in the TMR0 register.
movwf TMR0
del1 btfss intcon,2 ;test for Timer Overflow flag
goto del1 ;loop if not set
bcf intcon,2 ;clear Timer Overflow flag
return

- CPU can busy itself with other things if timer is used to generate accurate (only if terminated by the interrupt on 7
overflow) delay. Timer 0 maximum count up to 255.
- ‘Interrupt on overflow’ is generated as the delay ends  avoid CPU to keep checking the timer value!
- Advantage: timing now can be achieved by manipulating the Timer 0 settings, rather than by adjusting the software
routine.
Block Diagram of the TIMER1 Module

 The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H
and TMR1L) which are readable and writable.

 The TMR1 register pair (TMR1H:TMR1L) increments from 0000h to FFFFh and rolls
over to 0000h.

 The TMR1 interrupt, if enabled, is generated on overflow which is latched in interrupt


flag bit, TMR1IF (PIR1<0>). This interrupt can be enabled/disabled by setting/clearing
TMR1 interrupt enable bit, TMR1IE (PIE1<0>).

8
T1CON Register

With Timer1 programmed as an asynchronous


counter (T1SYNC# = 1) this counter continues
working even when the microcontroller is in low
power consumption mode. This makes Timer1 an
excellent candidate for a real-time clock (RTC).

9
Block Diagram of the TIMER2 Module

 Timer2 CAN ONLY work as a timer counting machine cycles.


 The prescaler can be programmed with division factors of 1, 4, or 8. The values for
the postscaler are 1, 2, 3, …, 16. When using both scalers with their maximum
values, the overflow time for Timer2 is the overflow time for a 16-bit counter.
 Timer2 is the timer that generates the time base used by the pulse width modulator
when the CCP module operates in PWM mode.
 Timer2 can also be used to generate the clock for the SSP module.
 The overflow time for Timer2 can be calculated as follows: With N being the number
stored in register PR2, P1 the division factor for the prescaler, P2 the division factor
for the postscaler, and Ti the period of the pulses entering the module, the overflow
time To for Timer2 is:

 Highlight  Timer2 does not increment while the microcontroller is in low-power


mode. It restarts counting when the microcontroller wakes up.

10
T2CON Register

11
EXAMPLE 6.1
 Program Timer2 to overflow every 1 ms using a main oscillator for the
microcontroller with a frequency of 4 MHz.
 With a 4 MHz frequency, the period of the pulses entering Timer2 is Ti = 1 μs. To
achieve an overflow time Td = 1 ms, Timer2 has to count up to 1000. This can be
seen using Equation below:

 This value can be achieved with P1 = 4, P2 = 10, and N = 24. The following
segment of code illustrates how to program Timer2 with these parameters.

12
THE CCP MODULE
 The capture/compare/PWM (CCP) modules are circuits that when used together with
Timer1 and Timer2 allow for other forms of timing signals.
 A single microcontroller can have up to two CCP modules called CCP1 and CCP2.
The SFRs used for CCPx (x can be 1 or 2) modules are as following:
- CCPRxH = used to store high byte of a 16-bit number
- CCPRxL = used to store low byte of a 16-bit number
- CCPxCON = register for CCP control,
- PIR register = bit CCPxIF in the PIR register used to indicate the presence
of an event.
- PIE register = the interrupt can be enabled with the bit CCPxIE in the PIE
register, it produces an interrupt request when CCPxIF is
set to 1.
  Capture mode = The CCP module captures the value of Timer1 when an external
event occurs in pin CCPx. CCPx pin is configured as input.
  Compare mode = The register in the CCP module stores a 16-bit number that is
compared with the value in Timer1. The result of the compare process may generate
an event that may include a change in the CCPx pin. CCPx pin is configured as
output. 13
  Pulse width modulation (PWM) mode = The CCP module and Timer2 make up a
PWM modulator whose output is located in pin CCPx. CCPx pin is configured as
output.
CCPxCON Register

 The CCPxCON register can be used to program the different operation modes for
the CCP modules ( through bits CCPxM3:CCPxM0). Bits DCxB1 and DCxB0 are
only used in PWM mode.

14
PULSE WIDTH MODULATION (PWM)
 Pulse width modulation (PWM) is a technique of controlling the amount of
power delivered from analog circuits to an electronic load using an on-off
digital signal from microcontroller.
 The fraction of the period for which the signal (the square wave) is on is
known as the duty cycle.
 The average DC value of the signal can be varied by varying the duty cycle.
 This method is commonly used for controlling speeds of DC motors, the
angular position of servo motor and brightness of lamps.

15
 In PWM mode, the CCPx pin of 16F873 produces up to a 10-bit resolution PWM output.
This means that the duration TON of the pulses can change at time increments of T/1024.
 Steps for configuring the CCP module for PWM operation:
1. Set the PWM period by writing to the PR2 register.
2. Set the PWM duty cycle by writing to the CCPR1L for the higher 8-bits and set CCP1CON<5:4> bits for
lower 2-bits
3. Make the CCP1 pin an output by clearing the TRISC<2> bit.
4. Using the T2CON register, set the TMR2 pre-scale value.
5. Clear the TMR2 register.
6. Configure the CCP1CON register for PWM.
7. Start Timer2.

 PWM period in second, Tpwm, is determined by the following formula:


Tpwm = ([PR2] + 1)⋅4Tosc⋅ [ TMR2ps ]
where TMR2ps is the TMR2 pre-scale value, and Tosc is the oscillation period.

 The PWM duty cycle that is represented by DCxB9:DCxB0 is specified by writing to the
CCPRxL register that contains the eight MSbs and CCPxCON<5:4> contains two LSBs.

 The PWM duty cycle in second, Dpwm, is given by the following formula: 16
Dpwm = [DB9 : DB0] ⋅ Tosc⋅ [TMR2ps]
EXAMPLE
 Given PIC 16F873 clock frequency is 20 MHz. Generate a desired PWM
frequency that has frequency of 78.125KHz (i.e., PWM period of 12.8µs)
with 50% duty cycle pulse and TMR2 prescale value of 16.

 Step 1: Set the PWM period by writing to the PR2 register.

If prescale value is not


given, you will need to
choose it with the
condition that [PR2]
value cannot exceed 255
17
 Step 2: Establish the PWM duty cycle by writing to the DCxB9:DCxB0 bits.
- Since we have express the duty cycle of PWM, Dpwm, in term of second, 50% of the
Tpwm of 0.5 ms is 0.25 ms.

18
 Step 3: Make the CCP1 pin an output by clearing the TRISC<2> bit.
- Third step is to properly allocate the CCP1 pin, which shares with RC2 pin of
PORTC. Since the CCP1 pin is an output pin, PORTC<2> must be set as an output by
clearing the TRISC<2> bit. In the following lines of code, PWM1 must be declared as 2
for CCP1 pin.

 Step 4: Using the T2CON register, set the TMR2 pre-scale value.
- Since we already selected our pre-scale as 16, we choose the 1:16 ratio by selecting bits 1
and 0 of T2CON as 11 or 10. For post-scale, we choose 1:1 ratio by selecting TPS3:TPS0
as 0000.
Banksel T2CON
;TMR2 Prescale selection
;and TMR2 OFF
movlw 0x02
movwf T2CON

19
 Step 5: Clear the TMR2 register.
Banksel TMR2
clrf TMR2

 Step 6: Configure the CCP1CON register for PWM.

 Step 7: Start Timer2.


bsf T2CON,TMR2ON

20
Internal operation of PWM
 When TMR2 is equal to PR2, the following three events occur on the next increment cycle:
• TMR2 is cleared
• The CCPx pin is set (exception: if PWM duty cycle = 0%, the CCPx pin will
not be set)
• The PWM duty cycle is latched from CCPRxL into CCPRxH
 The DCxB9:DCxB0 bits can be written to at any time, but the duty cycle value is not latched into
CCPRxH until after a match between PR2 and TMR2 occurs (which is the end of the current
period).
 In PWM mode, CCPRxH is a read-only register. The CCPRxH register and a 2-bit internal latch
are used to double buffer the PWM duty cycle. This double buffering is essential for glitch-less
PWM operation. When CCPRxH and 2-bit latch match the value of TMR2 concatenated with the
internal 2-bit Q clock (or two bits of the TMR2 prescaler), the CCPx pin is cleared. This is the end
of the duty cycle.

21
ACTUATOR INTERFACING : DIRECT CURRENT (DC)
MOTOR AND SERVO MOTOR
 DC motors are particularly versatile because both their speed and direction can be readily
controlled; speed by the voltage or duty cycle of their power supply, and direction by its
polarity. By changing (modulating) the width of the pulse at the logic gate or port bit output,
we can control how long the switch is turned on effectively controlling the amount of power
applied to the DC motor. As the load and voltage are fixed, the amount of power applied is
directly proportional to the amount of current applied, thereby increasing or decreasing the
motor speed.

 A servo motor is a special geared DC motor equipped with an electronic circuit for controlling
the direction of rotation, as well as the position, of the motor shaft. Because servo motors
allows precise angular positioning of their output shaft, they are used extensively in robotics
and radio-controlled cars, airplanes, and boats to control the motion of their various parts.

22
Transistor Switching of Resistive DC Loads

In many embedded systems we want to be able to switch DC loads electronically. The standard circuits
on this slide and the next represent simple ways of switching small resistive loads from a logic circuit.

VS V
S

RL RL
base current
controls load current gate voltage controls
load current IL
IL
VOH RB
b V
G
IB

IB > IL
b
VG > VGS(th)
V - 0.6
RB = i
IB

Bipolar Transistor MOSFET 23


On-Off Switching of Inductive Loads V S1

Inductors, including motors, relays,


solenoids etc, store energy when current is path of decaying
flowing in them, and this energy must be current when
returned to the circuit in a controlled manner transistor is R
p
switched off.
(by providing a current path for the current
D
to decay to zero) when the current is
L
switched off. Otherwise arcing will occur.
For DC switching this is normally done with “freewheeling” diode
a “free-wheeling” diode. I

Vi

Vi

0V

I 24
DC Motor Control

 The most famous transistor control scheme, so-called H-bridge that consists of
four transistors with a DC motor at the center, is normally used for the speed
and direction control of DC motor. L293D motor driver is a famous 2 H-Bridge
circuits, 1 per side of the chip or 1 per motor.
 The diodes, called "fly back diodes" in the H-bridge, are very important in
preventing voltage spikes of the motors from destroying the transistors.
 When a motor rotates and changes direction, the motor winding coils act as a
generator and produce a current. This current is called the back electromotive
force (EMF). This current travels back through the circuit in the form of
powerful voltage spikes to the transistor.
 Therefore, if this current is particularly large, when you reverse the direction
of the motor, it may blow the transistors. The diode’s job is then to allow this
current to bypass the transistor and travel safely back to the battery.

25
 When A is High and B is Low,
- transistors Q1 and Q4 are turned on and Q2 and Q3 are turned off.
- the current flows from the motor power supply through Q1 to the positive
terminal of the motor and through Q4 to the motor power supply.
- Thus, the motor turns in forward direction.
 When A is Low and B is High,
- transistors Q2 and Q3 are turned on and Q1 and Q4 are turned off.
- the current flows from the motor power supply through Q2 to the negative
terminal of the motor and through Q3 to the motor power supply.
- Thus, the motor turns in reverse direction.
 When both A and B are Low,
- No transistor turned on to flow the current through the motor.
- Thus, the motor stops.

26
27
Servo Motor Control

 Most servo motor will work well on 50 Hz of PWM frequency; this mean the
PWM signal should have a period of 20ms.
 The angle is determined by the duration of a pulse (pulse width) that is applied
to the control wire.
 The servo expects to see a pulse every 10-20 ms. The length of the pulse will
determine how far the motor turns. The position pulse must be repeated to
instruct the servo to stay in position.

28
 Most of the commonly available PIC microcontrollers come with built in PWM module which can
be easily configured to generate pulse of desired width or duty cycle on the CCPx pin. But these
modules are not designed to produce low frequency pulses.
 For example, by looking at the PIC 16F877A datasheet with 20 MHz of operating frequency clock
and using maximum prescaler of 16 (TIMER2), the minimum PWM frequency we could achieve
can be calculated using this formula:
PWM period = [( PR2 + 1) ] x 4 x Tosc x (TMR2 prescaler value) second
Using maximum PR2 register value of 0xFF (255 decimal), we will get this result:
PWM period = (255 + 1) x 4 x (1 / 20000000) x 16 = 0.8192 ms
PWM frequency = 1 / PWM period = 1 / 0.002048 = 1220.70 Hz
The 1220.70 Hz frequency is still too high from the servo motor working frequency of 50Hz;
therefore this leads to four alternatives below:
a) Use the Compare module, which can be programmed (lightly) to pulses of low frequencies.
b) Keep using the PIC PWM peripheral and lower the operation frequency by setting the
related register and PR2 register until it meets the servo motor frequency requirement. This
approach will scarify the program execution speed.
c) Create our own PWM function to mimic the PWM signal as follow: turn on the PORT, make
some 2 ms delay, turn off the PORT, and make some 18 ms delay and so forth. This approach
is not the efficient way.
d) Use the PIC 16F877A microcontroller TIMER0 with the interrupt to actually generate the
PWM signal as the TIMER0 have wider prescaler to choose comparing to the TIMER2, but
unfortunately the PWM peripheral on the PIC 16F877A only work with TIMER2 not 29

TIMER0. However it is possible to make this TIMER0 as our PWM base generator for driving
the servo motor.

You might also like