You are on page 1of 8

Copyright © 2022 Department of Electrical Engineering, University of Engineering

and Technology Lahore, Pakistan.


Permission is granted to copy and distribute for educational purpose. However, any
commercial use of the material, in any form, is not allowed.

1
Experiment 7

Timers and Time Base Generation

Timers/Counters
Almost every microcontroller comes with one or more (sometimes many more) built-in timer/-
counters, and these are extremely useful to the embedded programmer. The term timer/counter
itself reflects the fact that the underlying counter hardware can usually be configured to count
either regular clock pulses (making it a timer) or irregular event pulses (making it a counter).
Sometimes timers are also called “hardware timers” to distinguish them from software timers
which are bits of software that perform some timing function.

What is a Timer?
We use timers every day - the simplest one can be found on your wrist. A simple clock will time
the seconds, minutes and hours elapsed in a given day - or in the case of a twelve hour clock,
since the last half-day. ARM timers do a similar job, measuring a given time interval.

Micro-controllers, such as the TM4C123 utilize hardware timers to generate signals of various
frequencies, generate pulse-width-modulated (PWM) outputs, measure input pulses, and trigger
events at known frequencies or delays. The TM4C123 parts have several different types of timer
peripherals which vary in their configurability. The simplest timers are primarily limited to
generating signals of a known frequency or pulses of fixed width. While more sophisticated
timers add additional hardware to utilize such a generated frequency to independently generate
signals with specific pulse widths or measure such signals.

How a Timer Works?


An ARM timer in simplest term is a register. Timers generally have a resolution of 16/32
or 32/64 bits. So a 16 bit timer is 16 bits wide, and is capable of holding value within 0-
65536. But this register has a magical property - its value increases/decreases automatically at
a predefined rate (supplied by user). This is the timer clock and this operation does not need
CPU’s intervention.

An example of a basic timer is illustrated in Figure 7.2. This timer has four components –
a controller, a prescaler (PSC), an “auto-reload” register (ARR) and a counter (CNT). The
function of the prescaler is to divide a reference clock to lower frequency. The TM4C123 timers
have 8-bit prescaler registers for 16-bit timers which can divide the reference clock by any value
1..255 and 16-bit prescalar for 32-bit timer which can divide the reference clock by any value

2
3

Figure 7.1: Timer Register

1..65535. The counter register can be configured to count up, down, or up/down and to be
reloaded from the auto reload register whenever it wraps around (an “update event”) or to
stop when it wraps around. The basic timer generates an output event (TGRO) which can be
configured to occur on an update event or when the counter is enabled (for example on a GPIO
input).
CHAPTER 10. TIMERS

TIMxCLK
CK_INT TRGO
(RCC)
Trigger
Controller
CK_PSK

ARR
Auto Reload

PSC CNT
CK_CNT
Prescaler Counter

Figure 10.1:
Figure Basic Timer
7.2: Basic Timer

from 0 to 3 (ARR) and then is reset to 0. When the reset occurs, an “update
To understandevent” is generated.
the three counterThis update
modes event may
consider be tied
Figure 7.3.to In
TRGO,
theseorexamples,
in more we assume a
complex timers with capture/compare channels it may have additional effects
prescaler of 1 (counter
(describedclock is Similarly,
below). half the internal
in “Down”clock), andcounter
mode, the a autodecrements
reload value
fromof
3 3. Notice that
in “Up” mode,tothe 0 and then is reset
counter to 3 (ARR).
increments fromIn0Down
to 3 mode,
(ARR) an and
update “event”
then (UEV)
is reset to 0. When the
is generated when the counter is reset to ARR. Finally, in Up/Down mode,
reset occurs, an “update event” is generated. This update event may be tied to TRGO, or in
the counter increments to ARR, then decrements to 0, and repeats. A UEV
more complex istimers withbefore
generated capture/compare
each reversal withchannels
the effectitthat
maythehave additional
period in Up/Downeffects. Similarly,
in “Down” mode, modethe
is one shorterdecrements
counter than in eitherfrom
Up or3 Down
to 0 mode.
and then is reset to 3 (ARR). In Down
Many timers
mode, an update “event” (UEV)extend this basic module
is generated withcounter
when the the addition of counter
is reset to ARR. Finally, in
channels such as the one illustrated in Figure 10.3. The “x” refers to the
Up/Down mode, the counter
channel number –increments to ARR,
frequently, timers thenmultiple
support decrements to 0, With
channels. and repeats.
this A UEV is
modest
generated before eachadditional
reversal hardware,
with thean output
effect canthe
that be generated
period inwhenever
Up/Down the mode
count is one shorter
register reaches a specific value or the counter register can be captured when
than in either aUp or Down mode.
specific input event occurs (possibly a prescaled input clock).
An important use of counter channels is the generation of precisely
timed pulses. There are two variations of this use – “one-pulse” pulses, in
which a single pulse is generated, and pulse width modulation, in which a

140 Revision: 1396a85 (2013-01-07)


4 CHAPTER 7. TIMERS AND TIME BASE GENERATION

CNT 0 1 2 3 0 1 2 3 0
Up
UEV

CNT 3 2 1 0 3 2 1 0 3
Down
UEV

Up/Down CNT 2 3 2 1 0 1 2 3 2

UEV

CK CNT ®
Stellaris LM4F120H5QR M
CK INT

Figure 7.3: Counter Modes (ARR=3, PSC=1)


Figure 10.2: Counter Modes (ARR=3, PSC=1)
Figure 5-5. Main Clock Tree
Clock Configuration
series of pulses is generated with the counter UEV period. The pulse width is
controlled by the Capture/Compare Register (CCR). For example, the channel
The clock system on the Tiva-C Launchpad is extremely flexible. The clock tree of system clock
output (OCxREF) may tied to whether the CNT register is greater (or less)
configuration is shown
than the in Figure
Compare 7.4In Figure 10.4 we illustrate the use of two channels
register.
for one-pulse and PWM outputs. Here we assume that the ARR is 7 and the
CCR is 3. In PWM mode, ARR XTALacontrols the period, and CCR controls the
PWRDN b
pulse width (and hence the duty cycle). In one-pulse mode, the pulse begins
CCR cycles after an initial trigger event, and has a width of ARR-CRR. It
a
isMOSCDIS
possible to use multiple channels to create a set of synchronized, pulses
beginning at precise delays from PLLeach other. BYPASS b,d
Main OSC (400 MHz)c USESYSDIV a,d
A timer channel may also be used to DIV400
measure pulse widths – in effect
decoding pwm signals. There are many other
÷2 configuration options for the
STM32
IOSCDIStimers
a including mechanisms to synchronize multiple timers both to
each other and to external signals. System Clock
Precision
In the remainder of thischapter we consider two timer applications in-
Internal OSC ÷ SYSDIVe
cluding
(16 MHz)PWM output (Section 10.1), input pulse measurement (Section 10.2).
÷4
In Chapter 13 we show how to use a timer to control DMA transfers for an
BYPASS b,d
audio player and in Chapter 14 we use a timer to sample and analog input at
Internal OSC
(30 kHz)intervals.
regular

Hibernation
OSC OSCSRC b,d
(32.768 kHz)
Revision: 1396a85 (2013-01-07) 141
Figure 7.4: System Clock Tree

The internal system clock (SysClk), is derived from any of the four reference sources plus two
others: the output of the main internal PLL and the precision internal oscillator divided by
four (4 MHz ± 1%).
Note: Thea.frequency
Control of the PLL
provided clockregister
by RCC reference must be in the range of 5 MHz
bit/field.
to 25 MHz (inclusive). Following
b. Controltable shows
provided by how
RCC the various
register clock
bit/field sources
or RCC2 can be
register usedifin
bit/field, a
overridden with RCC
system. USERCC2.
c. Control provided by RCC2 register bit/field.
d. Also may be controlled by DSLPCLKCFG when in deep sleep mode.
e. Control provided by RCC register SYSDIV field, RCC2 register SYSDIV2 field if overridden
bit, or [SYSDIV2,SYSDIV2LSB] if both USERCC2 and DIV400 bits are set.
f. Control provided by UARTCC, SSICC, and ADCCC register field.
The internal system clock (SysClk), is derived from any of the above sources plus two others: the
output of the main internal PLL and the precision internal oscillator divided by four (4 MHz ± 1%).
The frequency of the PLL clock reference must be in the range of 5 MHz to 25 MHz (inclusive).
Table 5-3 on page 217 shows how the various clock sources can be used in a system.
5
Table 5-3. Clock Source Options
Clock Source Drive PLL? Used as SysClk?
Precision Internal Oscillator Yes BYPASS = 0, Yes BYPASS = 1, OSCSRC = 0x1
OSCSRC = 0x1
Precision Internal Oscillator divide by No - Yes BYPASS = 1, OSCSRC = 0x2
4 (4 MHz ± 1%)
Main Oscillator Yes BYPASS = 0, Yes BYPASS = 1, OSCSRC = 0x0
OSCSRC = 0x0
Low-Frequency Internal Oscillator No - Yes BYPASS = 1, OSCSRC = 0x3
(LFIOSC)
Hibernation Module 32.768-kHz No - Yes BYPASS = 1, OSCSRC2 = 0x7
Oscillator

5.2.5.2 Clock Configuration Figure 7.5: Clock Source Options


The Run-Mode Clock Configuration (RCC) and Run-Mode Clock Configuration 2 (RCC2)
registers provide control for the system clock. The RCC2 register is provided to extend fields that
offer
The additional encodings
Run-Mode over the RCC(RCC)
Clock Configuration register.and
When used, the Clock
Run-Mode RCC2 register field values
Configuration are
2 (RCC2)
used by the logic over the corresponding field in the RCC register. In particular, RCC2 provides for
registers
a largerprovide control
assortment for configuration
of clock the system clock.
options.The RCC2
These register
registers is provided
control to extend
the following clock fields
functionality:
that offer additional encodings over the RCC register. When used, the RCC2 register field
values are used
■ Source by the
of clocks logic and
in sleep overdeep-sleep
the corresponding
modes field in the RCC register. In particular,
RCC2 provides for a larger assortment of clock configuration options. These registers control
■ System clock derived from PLL or other clock source
the following clock functionality:
■ Enabling/disabling of oscillators and PLL
ˆ Source of clocks in sleep and deep-sleep modes
ˆ System clock derived from PLL or other clock source
ˆ Enabling/disabling of oscillators and PLL
ˆ Clock
January 19, 2013 divisors 217
Texas Instruments-Advance Information
ˆ Crystal input selection

To configure RCC and RCC2 clock configuration registers consult the data sheet of TM4C123.

Timers in TM4C123
The Tiva-C General-Purpose Timer Module (GPTM) in TM4C123 contains six 16/32-bit GPTM
blocks and six 32/64-bit Wide GPTM blocks. Each 16/32-bit GPTM block provides two 16-bit
timers/counters(referred to as Timer A and Timer B) that can be configured to operate inde-
pendently as timers or event counters. The register map of the GPTM is given in the data
sheet. Some key registers are described below:

SYSCTL RCGCTIMER R - enable clock for GPTM (enable clock for Timer0)

TIMER0 CTL R - control Timer0 module

TIMER0 CFG R - control global operation of Timer0 module (use 32-bit mode)

TIMER0 TAMR R - control the mode for Timer0

TIMER0 TAPR R - set the prescalar for Timer0

TIMER0 TAILR R - load the starting count value into the timer when counting down and set
the upper bound for the timeout event when counting up
6 CHAPTER 7. TIMERS AND TIME BASE GENERATION

How to Configure a Timer for Periodic Interrupts


The GPTM is configured for Periodic mode by the following sequence:

1. Enable the General Purpose Timer Module(GPTM) by asserting the appropriate TIMERn
bit in the RCGCTIMER register.
2. Ensure the timer is disabled (the TnEN bit in the GPTMCTL register is cleared) before
making any changes.
3. Write the GPTM Configuration Register (GPTMCFG) with a value of 0x04 to configure
in 16-bit mode.
4. Write a value of 0x2 in the TnMR field of the GPTM Timer n Mode Register (GPTMT-
nMR) to configure it in periodic mode
5. Load the period value into the GPTM Timer n Interval Load Register (GPTMTnILR)
6. Load the prescale value into the GPTM Timer n Prescale Register (GPTMTnPR).
7. Assert Timer A Time-Out Clear Interrupt (TATOCINT) bit of GPTM Interrupt Clear
Register(GPTMICR) to clear the time-out flag.
8. Set Timer A Time-Out Interrupt Mask (TATOIM) bit of GPTM Interrupt Mask Regis-
ter(GPTMIMR) to enable the time-out interrupt.
9. Set the priority in the correct NVIC Priority Register.
10. Enable the correct interrupt in the correct NVIC Priority Register
11. Set the TnEN bit in the GPTMCTL register to enable the timer and start counting.

Note1: The register map for System Control module (for RCGCTIMER) is to be consulted
from article 5.4 - System Control - Register Map of the controller datasheet.

Note2: The register map for Timers is to be consulted from article 11.5 - General-Purpose
Timers - Register Map of the controller datasheet.

Note3: Consult table 2-8 and 2-9 for the entries of the vector table from article 2.5.2 The
Cortex-M4F Processor - Exception Types of the datasheet.

Note4: The register map for NVIC is to be consulted from article 3.2 - Cortex-M4 Periph-
erals - Register Map of the controller datasheet.

Note5: The register map for GPIO is to be consulted from article 10.4 - General-Purpose
Input/Outputs (GPIOs) - Register Map of the controller datasheet.
7

Source Code
Complete source code for generating the periodic interrupts for Timer 0A (configured in 16-bits).
This program toggles the state of PF1 with 1 Hz frequency.
Example 7.1 (timer.h).

/ / GPIO r e g i s t e r s
# define SYSCTL_RCGCGPIO_R (*(( volatile unsigned long * ) 0 x400FE608 ) )
# define GPIO_PORTF_DATA_R (*(( volatile unsigned long * ) 0 x400253FC ) )
# define GPIO_PORTF_DIR_R (*(( volatile unsigned long * ) 0 x40025400 ) )
# define GPIO_PORTF_DEN_R (*(( volatile unsigned long * ) 0 x4002551C ) )

/ / Timer r e g i s t e r s
# define SYSCTL_RCGCTIMER_R (*(( volatile unsigned long * ) 0 x400FE604 ) )
# define TIMER0_CTL_R (*(( volatile unsigned long * ) 0 x4003000C ) )
# define TIMER0_CFG_R (*(( volatile unsigned long * ) 0 x40030000 ) )
# define TIMER0_TAMR_R (*(( volatile unsigned long * ) 0 x40030004 ) )
# define TIMER0_TAILR_R (*(( volatile unsigned long * ) 0 x40030028 ) )
# define TIMER0_TAPR_R (*(( volatile unsigned long * ) 0 x40030038 ) )
# define TIMER0_ICR_R (*(( volatile unsigned long * ) 0 x40030024 ) )
# define TIMER0_IMR_R (*(( volatile unsigned long * ) 0 x40030018 ) )

/ / NVIC r e g i s t e r s
# define NVIC_EN0_R (*(( volatile u n s i g n e d l o n g * ) 0 xE000E100 ) )
# define NVIC_PRI4_R (*(( volatile u n s i g n e d l o n g * ) 0 xE000E410 ) )

/ / constant values
# define TIM0_CLK_EN 0 x____ // enableclockforTimer0
# define TIM0_EN 0 x____ // disableTimer0beforesetup
# define TIM_16_BIT_EN 0 x____ / / configure16 − bittimermode
# define TIM_TAMR_PERIODIC_EN 0 x____ // configureperiodicmode
# define TIM_FREQ_10usec ____ / / selectprescalaerfor desired
f r e q u e n c y 1 0 0 kHz
# define TIM0_INT_CLR 0 x____ // cleartimeoutinterrupt
# define EN0_INT19 0 x____ // enableinterrupt19
# define PORTF_CLK_EN 0 x____ // enableclockforportF
# define TOGGLE_PF1 0 x____ / / t o g g l e r e d l e d ( PF1 )
# define LED_RED 0 x____ / / c o n f i g u r e r e d l e d ( PF1 )

/ / f u n c t i o n headers
void GPIO_Init ( void ) ;
void T i m e r _ I n i t ( unsigned long period ) ;
void DisableInterrupts ( void ) ;
void EnableInterrupts ( void ) ;
void WaitForInterrupt ( void ) ;
8 CHAPTER 7. TIMERS AND TIME BASE GENERATION

Example 7.2 (Timer0A Periodic Interrupt.c).

# include ‘ ‘ timer . h ’ ’

void T i m e r _ I n i t ( unsigned long period )


{
SYSCTL_RCGCTIMER_R | = TIM0_CLK_EN ; / / enable clock f or
Timer0
TIMER0_CTL_R &= ~ ( TIM0_EN ) ; / / d i s a b l e Timer0 before
setup
TIMER0_CFG_R | = T I M _ 1 6 _ B I T _ E N ; / / c o n f i g u r e 16 − b i t timer
mode
TIMER0_TAMR_R | = TIM_TAMR_PERIODIC_EN ; // configure periodic
mode
TIMER0_TAILR_R = p e r i o d ; / / set i n i t i a l load value
TIMER0_TAPR_R = T I M _ F R E Q _ 1 0 u s e c ; / / set prescalaer for
d e s i r e d f r e q u e n c y 1 0 0 kHz
TIMER0_ICR_R = T I M 0 _ I N T _ C L R ; / / clear timeout
interrupt
TIMER0_IMR_R | = TIM0_EN ; / / enable i n t e r r u p t mask
f o r Timer_0A
DisableInterrupts () ;

/ / Set p r i o r i t y f o r i n t e r r u p t
NVIC_PRI4_R = ( NVIC_PRI4_R & 0 x00FFFFFF ) | 0 x40000000 ;
NVIC_EN0_R | = E N 0 _ I N T 1 9 ; / / e n a b l e i n t e r r u p t 19
TIMER0_CTL_R | = TIM0_EN ; / / enableTimer_0A
EnableInterrupts () ;
}

void GPIO_Init ()
{
SYSCTL_RCGCGPIO_R | = PORTF_CLK_EN ;
GPIO_PORTF_DIR_R | = LED_RED ;
GPIO_PORTF_DEN_R | = LED_RED ;
}

void Timer0A_Handler ( void )


{
TIMER0_ICR_R = T I M 0 _ I N T _ C L R ;
GPIO_PORTF_DATA_R ^ = TOGGLE_PF1 ;
}

i n t main ( v o i d )
{

Timer_Init (50000) ; / / g e n e r a t e a s q u a r e wave f o r 2 Hz


GPIO_Init () ; / / i n i t i a l i z e PF1 a s d i g i t a l o u t p u t
while (1) ;
}

You might also like