48
1 Prepared By: Prof. Ankit D. Shah  Assistant Professor, EC Department, IDS, NU Demonstration of Embedded C Program based on  T i mer / Counte r

Timer - Coutner

  • Upload
    palakq

  • View
    218

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 1/48

1

Prepared By: Prof. Ankit D. Shah Assistant Professor,EC Department, IDS, NU

Demonstration of Embedded CProgram based on

 Timer / Counter

Page 2: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 2/48

SIGNIFICANCE OF TIMER/COUNTER:

Many microcontroller applicationsrequired the counting of external events,such as the frequency of a pulse train,

object counter or the generation of  precise interval time delays betweencomputer actions or in time delayprogram used in digital clock or any other

application where precise time delay isrequired.

Saturday, February 23, 2013 Prof. Ankit D. shah 2

Page 3: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 3/48

Saturday, February 23, 2013 Prof. Ankit D. shah 3

 A counter is a device that generatesbinary numbers in a specified countsequence when triggered by an incomingclock pulse.

Timers are counters that count pulses. If the pulses are “Internal clock” pulses,

then the timers count time.

What is a Timer/Counter?

Page 4: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 4/48

Saturday, February 23, 2013 Prof. Ankit D. shah 4

Cont….

The 8051 comes with two 16-bittimers/counters, both of which may becontrolled, set, read, and configured individually.

The 8051 timers have three general functions: Keeping time and/or calculating the amount of time

between events (Timer Mode).

Counting the events themselves (Event CounterMode)

Generating baud rates for the serial port.  Always count UP irrespective of function as a

timer or a counter.

Page 5: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 5/48

Saturday, February 23, 2013 Prof. Ankit D. shah 5

Difference between Timer and

Counter: When the incoming clock frequency is known, we can

generate a fixed period of time known to the designer bysetting a preloaded value. This is called a “timer”.

It is also called an “interval timer” since it is measuring thetime of the interval between two events.

When the incoming clock is irregular and we are onlyinterested in the number of occurrences of the pulse, this iscalled a “counter”. Since we are counting events, is alsoknown as an “event counter”.

In 8051, timer gets its clock from the oscillator (crystal that

connected to the CPU) frequency (1/12 of it). Counter gets the clock from an external pin:

P3.4 for timer 0, and P3.5 for timer 1.

Page 6: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 6/48

Saturday, February 23, 2013 Prof. Ankit D. shah 6

Cont….

Timer mode (if the timer control bit is set to timer, thetimer uses the system clock)

Increments by 1 every machine cycle.

 A single machine cycle consists of 12 clock pulses.

Each counter may be programmed to count internalclock pulsing, acting as a timer

Event mode (if the timer control bit is set to event, thetimer/counter uses a port bit)

Increments by 1 for each pulse on P3.4 for Timer 0,

and P3.5 for Timer 1, respectively. Each counter may be programmed to count external

pulses as a counter.

Page 7: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 7/48

Saturday, February 23, 2013 Prof. Ankit D. shah 7

Applications of Timers / Counters: Generating time delays.

Measuring pulse duration or timingintervals.

Counting pulses or events.

Generating baud rate clock for the internal8051 serial I/O port.

Generating interrupts.

Page 8: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 8/48

Saturday, February 23, 2013 Prof. Ankit D. shah 8

Software Technique V/S

Timer/Counter: Both of these task can be accomplished usingsoftware technique, but software loops forcounting or timing keep the processor occupied

so that other, perhaps more important, functionare not done. To relieve the processor of this time consumingtask, two 16-bit up counter, named T0 (Timer 0)

and T1 (Timer 1), are provided for the generaluse of the programmer.

Page 9: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 9/48

Saturday, February 23, 2013 Prof. Ankit D. shah 9

Calculation of clock frequency when

timer/counter operates as a timer: Find the timer’s clock frequency and

period for 8051-based systems with thefollowing crystal frequencies:

12 MHz

1/12 x 12 MHz = 1 MHz => T = 1 us

16 MHz

1/12 x 16 MHz = 1.333 MHz => T = .75 us

Page 10: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 10/48

Saturday, February 23, 2013 Prof. Ankit D. shah 10

Timer/Counter SFR:

 The counters are divided into two 8-bit registers calledthe timer low (TL0 & TL1) and high (TH0 & TH1) bytes.All counter action is controlled by bit states in the timermode control register (TMOD), time / counter control

register (TCON) and certain programinstructions. TMOD is dedicated solely to the two timers and can beconsidered to be two duplicate 4-bit registers, each of which controls the actionof one of the timer. TCON has control bits and flags for the timers in the

upper nibble and control bits and flags for the externalinterrupts in the lower nibble.

Page 11: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 11/48

Saturday, February 23, 2013 Prof. Ankit D. shah 11

Cont….

Timer Special Function Registers (SFRs)

 As mentioned before, the 8051 has two timers that essentiallyfunction the same way.

One timer is called TIMER0 (T0) and the other is TIMER1(T1).

The two timers share two SFRs (TMOD and TCON) that control thetimers.

Each timer also has two SFRs dedicated solely to itself (TH0/TL0and TH1/TL1).

It is common practice to use given SFR names to refer to them, but

in reality an SFR has a numeric address. When you enter the name of an SFR into an assembler or compiler,

it internally converts it to the specified SFR address.

Page 12: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 12/48

Saturday, February 23, 2013 Prof. Ankit D. shah 12

Cont….

Internal 1 byte address of Timer SFRs

SFR Name Description Address

TH0 Timer 0 High Byte 8CHTL0 Timer 0 Low Byte 8AH

TH1 Timer 1 High Byte 8DH

TL1 Timer 1 Low Byte 8BH

TCON Timer Control 88HTMOD Timer Mode 89H

Page 13: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 13/48

Saturday, February 23, 2013 Prof. Ankit D. shah 13

Structure of TCON and TMOD SFR:

 Timer Control Register (TCON)

TCON has the following functions:

Turns Timer 0 and Timer 1 on or off. (Timer RunControl Bit)

Sets trigger type (edge or level) for interrupt 0 andinterrupt 1. (Interrupt type bit)

Sets flags when timer 0 or timer 1 overflow.

Sets flags when negative edge triggered externalinterrupt 0 or external interrupt 1 occurs on pinP3.2 or P3.3 respectively.

Page 14: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 14/48

Prof. Ankit D. shah 14

Cont….

Only the upper 4 bits are related to timers; the lower 4 bits have nothing toOnly the upper 4 bits are related to timers; the lower 4 bits have nothing todo with timersdo with timers -- they have to do with interrupts.they have to do with interrupts.

 TCON is a bit TCON is a bit--addressable register.addressable register.

Bit Symbol Function

D7 TF1 Timer 1 Overflow Flag. Set when all the bits of timer 1 roll from 1’s to 0’s. Cleared when processor vectors to execute interrupt service routine located at program address 001B H.

D6 TR1 Timer 1 Run control bit. Set to 1 by program to enable timer to count; cleared to 0 by program to halt

timer. Does not reset timer.

D5 TF0 Timer 0 Overflow Flag. Set when all the bits of timer 0 roll from 1’s to 0’s. Cleared when processor 

vectors to execute interrupt service routine located at program address 000B H.

D4 TR0 Timer 0 Run control bit. Set to 1 by program to enable timer to count; cleared to 0 by program to halt

timer. Does not reset timer.

D3 IE1 External Interrupt 1 Edge flag. Set to 1 when a high to low edge is received on port 3 pin 3.3. (INT

1’). Cleared when processor vectors to interrupt service routine located at program address 0013H.

 Not related to timer operation.

D2 IT1 External Interrupt 1 signal Type control bit. Set to 1 by program to enable external interrupt to be

triggered by a falling edge signal. Set to 0 by program to enable a low level signal on external

interrupt 1 to generate an interrupt.

D1 IE0 External Interrupt 0 Edge flag. Set to 1 when a high to low edge is received on port 3 pin 3.2. (INT

0’). Cleared when processor vectors to interrupt service routine located at program address 0003H.

 Not related to timer operation.

D0 IT0 External Interrupt 0 signal Type control bit. Set to 1 by program to enable external interrupt to be

triggered by a falling edge signal. Set to 0 by program to enable a low level signal on external

interrupt 1 to generate an interrupt.

Structure o r Format of TCON SFR:

D7 D6 D5 D4 D3 D2 D1 D0

 TF0 TR1 TF1 TR0 IE1 IT1 IE0 IT0

Saturday, February 23, 2013

Page 15: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 15/48

Saturday, February 23, 2013 Prof. Ankit D. shah 15

Cont…..

 Timer Mode Control (TMOD) Register TMOD controls timer 0 and timer 1 functions. The register’s upper nibble controls Timer 1 and the

lower nibble controls timer 0. The four bits for each timer control a gate function,

selection of counter or timer, and timer mode. The timer or counter function is selected by control bits

C/T’; these two timers/counters have 4 operatingmodes, selected by appropriate M0 and M1 bits in theTMOD register.

TMOD is not a bit-addressable register. It has to bemanipulated as a byte.

Page 16: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 16/48

Saturday, February 23, 2013 Prof. Ankit D. shah 16

Cont….(MSB) (LSB)

GATE TC/  M1 M0 GATE TC/  M1 M0

GATE

TC/ 

If GATE = 1, timer x will run

only when TRx = 1 and INTx

= 1. If GATE = 0, timer x will

run whenever TRx = 1.

Timer mode select. If 

TC/  = 1, timer x runs in

counter mode taking its input

from Tx pin. If  TC/  = 0 ,

timer x runs in timer mode

taking its input from the

system clock.

M1

0

0

1

1

1

M0

0

1

0

1

1

Operating Mode

13-bit timer mode (8048

mode).

16-bit timer mode.

8-bit auto-reload mode.“THx” holds a value

which is to be reloaded

into “TLx” each time itoverflows.

(Timer 0) TL0 is an 8-bit

Timer/Counter controlled

by the standard Timer 0

control bits. TH0 is an

8-bit timer only controlledby Timer 1 control bits.

(Timer 1) Timer/Counter

1 is stopped.

Timer 1 Timer 0

Page 17: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 17/48

Saturday, February 23, 2013 Prof. Ankit D. shah 17

Cont….

Indicate which mode and which timer areselected for each of the following:

TMOD = 0000 0001, mode 1 of timer 0, mode 0 of timer 1

TMOD = 0010 0000, , mode 0 of timer 0, mode 2of timer 1

TMOD = 0001 0010, mode 2 of timer 0, and mode

1 of timer 1 are selected

Page 18: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 18/48

 Timer / Counter Control Logic:

OscillatorFrequency

% 12

 T1 / 0 Input Pin

 To Timer

Stage OR Timer Clock

Counter

 Timer

C/ T’ =1 (TMODcounter operation)

C/T’ =0 (TMODtimer operation)

 TR1/0 Bit in TCON

Gate Bit in TMOD

INT1’/ 0’ Input Pin

S1

S2

Saturday, February 23, 2013 Prof. Ankit D. shah 18

 The following diagram shows the control logic for timer / counter pulsegeneration which will become the clock pulse for timer / counter.

Page 19: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 19/48

Saturday, February 23, 2013 Prof. Ankit D. shah 19

 Various modes of Timer/Counter:

As we know that the timers may operatein any one of four modes that aredetermined by the mode bits, M1 and M0,in the TMOD register.

Page 20: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 20/48

Saturday, February 23, 2013 Prof. Ankit D. shah 20

Mode 0 – 13 Bit Timer / Counter: TH, TL = XXXXXXXX, 000XXXXX

8 bits from TH

5 bits from LSB of TL

For compatibility with older microcontroller (8048), not very

useful now.

Range = 0 to 8191.

Timer clock

Overflow flag

TLx(5 bits)

THx(8 bits)

TFx

8051 Timer Mode 0

Page 21: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 21/48

Saturday, February 23, 2013 Prof. Ankit D. shah 21

 Timer Mode 1 – 16 Bit Timer /

Counter: 8 bits from TH, another 8 bits from TL.

Each byte loaded separately

Counts UP (so initialize with negative value).

The counters start counting when enabled (by a bit in the TCON).

Counts time (when acting as timer) until a preset number asspecified by the THx and TLx registers is reached.

Generates an overflow (interrupt) when timed out.

In order to repeat the process the registers TH and TL must bereloaded with the original value and the timer overflow flag mustbe reset under the control of the program.

Page 22: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 22/48

Saturday, February 23, 2013 Prof. Ankit D. shah 22

Cont….

ExampleExample

#i ncl ude “#i ncl ude “anki t . hanki t . h””

voi d DELAY ( voi d) ;voi d DELAY ( voi d) ;

voi d mai n ( voi d)voi d mai n ( voi d)

{{

 TMOD = 0X01; TMOD = 0X01;

whi l e (1)whi l e (1)

{{

 TL0 = 0X0F2; TL0 = 0X0F2;

 TH0 = 0XFF; TH0 = 0XFF;

P1. 5 = ~P1. 5;P1. 5 = ~P1. 5;

DELAY ( ) ;DELAY ( ) ;

}}

}}

Timer 

clock

Overflow flag

THx

(8 bi ts) TFx

TLx

(8 bits)

8051 Timer Mode 1 TRx TRx

/12/12

XTALXTALOSC.OSC.

FFF2,FFF3,FFF4,…,FFFE,FFFF,0000FFF2,FFF3,FFF4,…,FFFE,FFFF,0000

12 MHz, Timer clock period = 112 MHz, Timer clock period = 1ss

14 counts14 counts

Half pulse = 14Half pulse = 14 ss

Full period = 28Full period = 28 ss

Frequency = 1/28Frequency = 1/28 s = 35.714 kHzs = 35.714 kHz

ExampleExample ( cont …)( cont …)

voi d DELAY (voi d)voi d DELAY (voi d)

{{

 TR0 = 1; TR0 = 1;

whi l e ( TF0 == 0) ;whi l e ( TF0 == 0) ;

 TR0 = 0; TR0 = 0;

 TF0 = 0; TF0 = 0;

}}

Page 23: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 23/48

Saturday, February 23, 2013 Prof. Ankit D. shah 23

 Assume that we know the desired amount of timer

delay, tdelay. To calculate the values to be loaded into

the TL and TH registers, using crystal frequency of Xcrystal

MHz, the following steps are needed:

Step 1: find n, where n =

Step 2: Perform 65536 - n

Step 3: Convert step 2 result to hex, assume this result is yyxx Step 4: Set TL = xx and TH = yy.

 period clock timer 

t

12

Xt delaycrystaldelay

t  ActualCoun

Finding load count value:

Page 24: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 24/48

Saturday, February 23, 2013 Prof. Ankit D. shah 24

Cont….

 Assuming a desired time delay of 5 ms and Xcrystal= 11.0592 MHz, determine the values of TL and THin hex.

 EEH TH 

 H TL

 H  EE  H  H  Loadcount 

 H n

t  Actualcoun

00

0012000000

1200460812/100592.11105

 period clock timer 

t

12

Xt

63

delaycrystaldelay

Page 25: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 25/48

Saturday, February 23, 2013 Prof. Ankit D. shah 25

Programming in Moe 1:

To generate a time delay using timer mode 1, thefollowing steps are taken.

1. Load the TMOD value register indicating whichtimer (0 or 1) is to be used and which timer modeis selected.

2. Load registers TL and TH with initial count values.

3. Start the timer by the statements “ TR0 = 1; ” fortimer 0 and “ TR1 = 1; ” for timer 1.

4. Keep monitoring the timer flag (TF) with the

 “whi l e ( TFx == 0) ; ” statement to see if it israised. Get out of the loop when TF becomeshigh.

Page 26: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 26/48

Saturday, February 23, 2013 Prof. Ankit D. shah 26

Cont…..

5. Stop the timer with the statements “ TR0 = 0; ” or “ TR1 = 0; ”, for timer 0 and timer 1,

respectively.

6. Clear the TF flag for the next round with thestatements “ TF0 = 0; ” or “ TF1 = 0; ”, for timer

0 and timer 1, respectively.

7. Go back to step 2 to load TH and TL again.

The programming techniques mentioned here are

also applicable to counter/timer mode 0. The onlydifference is in the number of bits of the initializationvalue.

Page 27: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 27/48

Saturday, February 23, 2013 Prof. Ankit D. shah 27

Cont….

Embedded C program to continuously generate asquare wave of 2 kHz frequency on pin P1.5 usingtimer 1. Assume the crystal oscillator frequency to be12 MHz.

Solution: Initial calculations are as follows.

The period of the square wave is T = 1/(2 kHz) = 500s. Each half pulse = 250 s.

The value n for 250 s is: 250 s /1 s = 250

65536 - 250 = FF06H.

TL = 06H and TH = 0FFH.

Page 28: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 28/48

Saturday, February 23, 2013 Prof. Ankit D. shah 28

Square Wave Generation on Pin P1.5#i ncl ude “#i ncl ude “anki t . hanki t . h””

voi d mai n ( voi d)voi d mai n ( voi d){{

 TMOD = 0X10; I ni t i al i ze t i mer 1 i n mode TMOD = 0X10; I ni t i al i ze t i mer 1 i n mode –– 11P1. 5 = 0; To st ar t squar e wave f r om l ow per i odP1. 5 = 0; To st ar t squar e wave f r om l ow per i odwhi l e ( 1)whi l e ( 1){{

 TL1 = 0X06; To l oad l ower 8 TL1 = 0X06; To l oad l ower 8-- bi t of countbi t of count

 TH1 = 0XFF; To l oad hi gher 8 TH1 = 0XFF; To l oad hi gher 8-- bi t of countbi t of count TR1 = 1; To st ar t t i mer 1whi l e (TF1 == 0) ; To check whether t i mer 1

; has compl eted t he count or not TR1 = 0; To st op t i mer 1P1. 5 = ~P1. 5; Compl ement P1. 5 t o make i t

; f r om l ow t o hi gh and hi gh t o l ow`

 TF1 = 0; To cl ear t he t i mer 1 f l ag}

}I n t hi s progr am we have t o l oad count val ue agai n asmode - 1 i s not aut o rel oad.

Page 29: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 29/48

Saturday, February 23, 2013 Prof. Ankit D. shah 29

Mode 2 – 8 Bit Auto Reload:

TL0 or TL1 is an 8 bit counter/timer TH0 or TH1 holds an initialization value

TL reloaded from TH on 255 to 0 transition

The reload leaves TH unchanged.

Used to generate UART baud rate clock; a periodic flagor interrupt.

Timer 

clock

THx

(8 bits)

TLx

(8 bits)TFx

Overflow flag

Reload

8051 Timer Mode 2

Page 30: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 30/48

Saturday, February 23, 2013 Prof. Ankit D. shah 30

1. Load the TMOD value register indicating whichtimer (0 or 1) is to be used; select timer mode 2.

2. Load TH register with the initial count value as wellas first time load TL with the same value. As it is

an 8-bit timer, the valid range is from 00 to FFH.3. Start the timer.

4. Keep monitoring the timer flag (TFx) to see if it israised. Get out of the loop when TFx goes high.

5. Clear the TFx flag.

6. Go back to step 4, since mode 2 is auto-reload.

Programming in Moe 2:

Page 31: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 31/48

Saturday, February 23, 2013 Prof. Ankit D. shah 31

Cont….

Embedded C program segment that uses timer1 in mode 2 to toggle P1.0 once whenever the

counter reaches a count of 100. Assume thetimer clock is taken from external source P3.5(T1).

Solution:

The TMOD value is 60H

The initialization value to be loaded into TH1 is

256 - 100 = 156 = 9CH

0 1 1 0 0 0 00

Gate C/T M1 M0 Gate C/T M1 M0

 Timer 1 Timer 0

Page 32: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 32/48

Saturday, February 23, 2013 Prof. Ankit D. shah 32

Cont….#i ncl ude “#i ncl ude “anki t . hanki t . h””voi d mai n ( voi d)voi d mai n ( voi d){{

 TMOD = 0X60; Count er 1 i n mode TMOD = 0X60; Count er 1 i n mode –– 2, C/ T’ = 12, C/ T’ = 1P3. 5 = 1; To make T1 pi n as an i nput pi nP3. 5 = 1; To make T1 pi n as an i nput pi n

 TH1 = 0X9C; To l oad count val ue TH1 = 0X9C; To l oad count val ue TL1 = 0X9C; To l oad count val ue f i r st t i me TL1 = 0X9C; To l oad count val ue f i r st t i me TR1 = 1; To st ar t t i mer 1P1. 0 = 0; I ni t i al l y t o make i t l owP1. 0 = 0; I ni t i al l y t o make i t l owwhi l e ( 1)whi l e ( 1)

{{whi l e (TF1 == 0) ; To check whet her t i mer 1

; has compl eted t he 100 countP1. 0 = ~P1. 0; Compl ement P1. 0

 TF1 = 0; To cl ear t he t i mer 1 f l ag

}

} Note in the above program the role of the statement

 “P3. 5 =1; ”. We make P3.5 an input pin by making it high toaccept the external signal as an input.

Page 33: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 33/48

Saturday, February 23, 2013 Prof. Ankit D. shah 33

Significance of Timer/Counter Interrupt:

 The counters have been included on the chip torelieve the microcontroller of timing and countingchores.When the program whishes to count a certainnumbers of internal pulses or external events, a

number is placed in one of the counters. The number represents the maximum count less thedesired count, plus 1. The counter increments formthe initial number to the maximumand then rolls over0 on the final pulse and also sets a timer flag. The flag condition may be tested by an instruction totell the program that the count has beenaccomplished, or the flag may be used to interruptthe program.

Page 34: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 34/48

Saturday, February 23, 2013 Prof. Ankit D. shah 34

Timer/Counter as a Timer:

If a counter is programmed to be a timer, it will count the internalclock frequencyof the 8051 oscillatordivide by12. As anexample, if the crystal frequency is 6 megahertz, thenthe timerclock will have afrequencyof 500 kilohertz. The resultant timer clock is gate to the timer by means of the circuitshown in timer / countercontrol logic.In order for oscillator clock pulses to reach the timer, the C/T’ bit inthe TMOD register mustbe setto 0 (timeroperation).Bit TRX in the TCON register must be set to 1 (timer run), and thegate bit in the TMOD register must be 0, or external pin INTX’ mustbe a 1.

In other words, the counter is configured as a timer, then the timerpulses are gated to the counter by the run bit and the gat bit orexternal input bits INTX’.

Page 35: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 35/48

Saturday, February 23, 2013 Prof. Ankit D. shah 35

Timer/Counter as a Counter:

 The only difference between counting and timing is the source of theclockpulses to the counters.When used as a timer, the clock pulses are sourced from the oscillatorthrough the divide by 12 circuit. When used as a counter, pin T0 (P3.4)suppliespulses to counter0 and pinT1 (P3.5) to counter1.

 The C/T’bit inTMOD mustbe set to 1 to enable pulses fromthe TX pin toreachthecontrol circuitshown timer / countercontrol logic.

 The input pulse on TX is sampled during P2 of state 5 every machinecycle.A change on the input from high to low between samples will incrementthe counter.Each high and low state of the input pulse must thus be held constant forat leastone machine cycle to ensure reliablecounting.Since this takes 24 pulses, the maximum input frequency that can beaccuratelycounted is theoscillator frequencydivide by24.For our 6 megahertz crystal, the calculation yields a maximum externalfrequencyof 250 kilohertz.

Page 36: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 36/48

Saturday, February 23, 2013 Prof. Ankit D. shah 36

Timing Functions:

Functions are used by main programs in what is known as atransparent manner – that is, the main program can use the functionswithout being bothered by the details of what is actually going on in thesubroutine.Usually, the main program preloads certain locations with data(argument), calls the function, then gets the results back in the preload

locations (returnvalue). The function must take great care to save the values of all memorylocations in the system that the function uses to perform internalfunctions and restore these values before returning to the call program.Failure to save values results in occasional bugs in the main program. The main program assumes that everything is the same both before

and aftera subroutine is called.Finally, good documentation is essential so that the user of the functionknows preciselyhow to use it.

Page 37: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 37/48

Saturday, February 23, 2013 Prof. Ankit D. shah 37

Time Delay:Perhaps the most-used subroutine is one that generates a programmable time

delay. Time delays may be done by using software loops that essentially do nothing forsome period, orbyusinghardware timers thatcountinternal clockpulses.

 The hardware timers maybe operatedineither a software ora hardware mode.In the software mode, the program inspects the timer Overflow flag and jumpswhen itis set.

 The hardware mode uses the interrupt structure of the 8051 to generate aninterruptto theprogramwhen the timeroverflows.

 The interrupt method is preferred whenever microcontroller time is very precious. The interrupt mode allows the microcontroller to continue to execute useful codewhile the time delay is taking place. Both the pure software and timer-softwaremodes tie upthemicrocontrollerwhile the delay is taking place.If the interruptmode is used, then theprogrammust behave an interrupt handlingfunction at the dedicated interrupt program vector location specified by theengineer who design the microcontroller.

 The programmer must be also have programmed the various interrupt controlregisters. This degree of non-transparency generally means that interrupt drivenfunctions are normally written by the user as needed and not used from apurchased libraryof functions.

Page 38: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 38/48

Saturday, February 23, 2013 Prof. Ankit D. shah 38

Pure Software Time Delay:

In this we generate time delaywithout the use ofon chip timer / counter. To develop pure software time delay program, we must know the machinecycle requiredbyeach instructionused in theprogram.So, this is one of the limitations of pure software time delayprogram.Second limitation of it is that itwill notgenerate accurate time delay and thirdlimitation is the controller busy or tie up in the execution of time delayprogramso, itcan notgive attention to important taskwhile execution of pure

software time delay.Normally in pure software time delay program, we will find count value as pertime delay required to be generated. It the count value is not integer then wewill truncate it and then load that count value in one register or more thanone registeras a down counter.

 To generate accurate time delay we have to insert NOP instruction in theprogramas per the requirementand itkeptoutside the loop.In short the pure software time delay program is one kind of down counterprogram in which we load any one register or more than register by countvalue and then decrement ituntil countbecomes 0.

Page 39: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 39/48

Saturday, February 23, 2013 Prof. Ankit D. shah 39

Software Polled and Pure Hardware Time

Delay:A delay that uses the timers to generate the delay and acontinuous software flag test (the flag is “polled”to see whether itis set) to determine when the timerhave finished the delay.

If delaymust be done in a program, but the programcan notwaitwhile the delay is computed, then the delay will have to be doneusing a timer enable to interrupt the main program. A timerinterrupt allows a timer to run and generate a time delay at thesame time as themainprogramloop is executing.

Page 40: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 40/48

Saturday, February 23, 2013 Prof. Ankit D. shah 40

Significance of Pure Software TimeDelay:  Very short intervals can not be generated using timersbecause of the overhead needed to start and stop the timers.

Such short timing intervals are usually generated using tightsoftware loops.

The following code segment generates a 250 KHz wave with25% duty cycle on P1.0. Assume XTAL = 12 MHz.

LOOP: SETB P1. 0 ; 1 machi ne cycl e

CLR P1. 0 ; 1 machi ne cycl e

SJ MP LOOP ; 2 machi ne cycl es

SETB

CLR

SJMP SETB

1 s 1 s 1 s 1 s 1 s

4 s

Page 41: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 41/48

Saturday, February 23, 2013 Prof. Ankit D. shah 41

Cont….

The following code segment generates a 250 KHzsquare wave on P1.0. Assume XTAL = 12 MHz.

LOOP: NOP ; 1 machi ne cycl e

SETB P1. 0 ; 1 machi ne cycl e

 J BC P1. 0, LOOP ; 2 machi ne cycl es

1 s 1 s 1 s 1 s 1 s4 s

NOP SETB JBC P1.0 NOP

Page 42: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 42/48

Saturday, February 23, 2013 Prof. Ankit D. shah 42

Constraint of Generating TimeDelay by different technique:

 TTiimmee IInntteer r vvaall TTeecchhnniiqquuee 

NNoo lliimmiitt SSoof f ttwwaarree llooooppss 

NNoo lliimmiitt 1166--bbiitt pplluuss ssoof f ttwwaarree llooooppss 

6655553366mmaacchhiinnee ccyycclleess 1166--bbiitt ttiimmeerr 

225566mmaacchhiinnee ccyycclleess AAuuttoo--rreellooaadd ((88--bbiitt)) 

Page 43: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 43/48

Steps to be consider while developing time

delay program by Software-Polled Timer:

Saturday, February 23, 2013 Prof. Ankit D. shah 43

Find out the actual count value from the value of timedelay to be generated and the time period of crystal

frequency /12 or machine cycle time.

Decide the timer mode from the value of actual count.

Find out the load count value from the actual count value.

The equation of load count value is load count value =maximum count value – actual count value + 1.

Select the mode and make the gate bit 0 by loading

appropriate value in TMOD SFR for a timer / counter to be

used.

Copied the load count value in lower and higher byte of 

respective timer / counter.

Set the run bit of respective timer / counter in TCON SFR 

 by using TRx = 1; statement.

Page 44: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 44/48

Cont…

Saturday, February 23, 2013 Prof. Ankit D. shah 44

Check the status of timer overflow flag of respective

timer / counter in TCON SFR by using while syntax

(while (TFx == 0);).

If timers overflow flag is set then first cleared (set to 0)

timer run bit of respective timer / counter in TCON SFR  by using TRx = 0; statement.

Perform the task which you have to perform after the

generation of particular time delay by software polled 

timer.

Cleared the timer overflow flag of respective timer /counter in TCON SFR by using TFx = 0; statement.

Page 45: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 45/48

Steps to be consider while developing time

delay program by Pure Hardware Delay:

Saturday, February 23, 2013 Prof. Ankit D. shah 45

Find out the actual count value from the value of time delay to begenerated and the time period of crystal frequency /12 or machine cycle

time.

Decide the timer mode from the value of actual count.

Find out the load count value from the actual count value. The equation

of load count value is load count value = maximum count value – actual

count value + 1.Select the mode and make the gate bit 0 by loading appropriate value

in TMOD SFR for a timer / counter to be used in main program.

Copied the load count value in lower and higher byte of respective

timer / counter in main program.

Set the run bit of respective timer / counter in TCON SFR by using

TRx = 1; statement in main program.

Enable the interrupt bit of respective timer / counter and EA (D7) bit in

interrupt enable register by using EA = 1; statement in main program.

Page 46: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 46/48

Cont….

Saturday, February 23, 2013 Prof. Ankit D. shah 46

Also decide the priority of respective timer / counter interrupt in interruptregisterby making itsetorclearedusing statement inmain program.Also develop interrupt subroutine of respective timer / counter and stored itatpredefined memory locations. For example for timer / counter 0 itmust bestored at 000BH and for timer / counter 1 it must be stored at 001BHmemory location. Then, continue the developmentofmain program.Now, when you execute the main program and whenever respective timer /counter interrupt overflow is set due to rolls of all bits from 1’s to 0’s of respective timer / counter.Automatic program sequence change from main program to the respectivetimer / counter interrupt function is executed and respective timer / counteroverflowflag is cleared.Now, if you want to execute timer / counter interrupt function only one timethen you must cleared respective timer / counter run bit in TCON SFR by

usingTRx =0; statement.After the execution of timer / counter interrupt function, the programsequence come back to an instruction in main program where the interruptoccurred.

Page 47: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 47/48

Saturday, February 23, 2013 Prof. Ankit D. shah 47

Question – Answer Session

Page 48: Timer - Coutner

8/22/2019 Timer - Coutner

http://slidepdf.com/reader/full/timer-coutner 48/48

Thank you