0% found this document useful (0 votes)
15 views10 pages

16 Timer

The document provides an overview of Timer-A in the MSP430 microcontroller, detailing its functionality for generating time delays and controlling outputs. It explains the importance of clock signals in digital circuits, the MSP430's clock system, and how to use Timer-A for tasks like blinking an LED. Additionally, it covers the configuration of the timer, including clock source selection and pre-scaling for generating longer delays.

Uploaded by

vishnuks
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)
15 views10 pages

16 Timer

The document provides an overview of Timer-A in the MSP430 microcontroller, detailing its functionality for generating time delays and controlling outputs. It explains the importance of clock signals in digital circuits, the MSP430's clock system, and how to use Timer-A for tasks like blinking an LED. Additionally, it covers the configuration of the timer, including clock source selection and pre-scaling for generating longer delays.

Uploaded by

vishnuks
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/ 10

Understanding Timer-A

October 14, 2011

1 Introduction

Timer/counter units integrated with a microcontroller help us to measure time


periods, generate delays and drive outputs at specic frequencies. In this lesson,
we learn to use the MSP430 processor's Timer-A to generate time delays.
[Note: Timers are considerably more complex than Digital I/O ports - so
don't worry if you nd some of the discussions in this lesson to be a bit con-
fusing! It is assumed that you have a basic understanding of signals - the
terms: time period, frequency etc should make sense to you. If not, please read
http://www.doctronics.co.uk/signals.htm (rst 2-3 pages should be enough to
get started) before continuing with the lesson. Use the course forum actively to
clear your doubts! ]
[Note: The details regarding the working of the timer are explained in
the processor manual MSP430 Family Guide. You should download it from:
http://recursive-labs.com/datasheets/msp430-family-guide.pdf . It is not pos-
sible to complete this lesson without access to this document]

2 A note about clocks

Many digital circuits (so-called synchronous circuits) need a clock signal


(Ref: http://en.wikipedia.org/wiki/Clock_signal) to co-ordinate the actions of
dierent parts of the circuit. The clock signal is usually a square waveform as
shown in Figure 1 . A modern day microprocessor is an immensely complex
digital circuit and needs a clock to function properly. When you say that your
Pentium dual core processor has a speed of 2.8GHz, you are actually referring to
the clock speed, ie, the frequency of the clock signal fed to the processor. Your
processor may be able to perform one computation in a single cycle of the clock

Figure 1: Square wave

1
signal, in which case the processor will be able to execute 2.8 ∗ 109 instructions
per second. You might have heard of things like overclocking in which people
(mostly game enthusiasts) try to gain better performance by increasing the clock
speed (Ref: http://en.wikipedia.org/wiki/Overclocking ). The power consumed
by the processor increases as its clock speed is increased - this has signicant
implications in battery-powered systems (say mobile phones).
Things are even more complex in the case of a microcontroller because the
controller integrates a processing engine with lots of other peripherals - each
of these peripherals will need clocks of varying frequencies. In order to save
power, the microcontroller should be able to shut down the clocks to each of
the peripherals independently (thereby powering down that peripheral). In a
complex controller like the ARM, you will nd a very large number of pages in
the manual describing the working of the clock subsystem in detail !
1

2.1 MSP430 Clock System


The MSP430 family of controllers have an internal DCO (digitally controlled
oscillator) which is capable of providing clocks of various frequences starting
from a few KHz to about 15-16MHz. By default, the DCO is congured to
generate a clock signal of about 1MHz at system startup. This is the signal
which controls the CPU core - it can also be used as the clock input to the
various peripheral units within the microcontroller.

3 Blinking LED using a delay loop

It is easy to write a blinking LED program using what is called a delay loop:

#include <msp430.h>
#define LED1 BIT0
#define TOGGLE_LED1 (P1OUT ^= LED1)
void delay()
{
unsigned int i = 0;
while(++i < 30000);
}
main()
{
P1OUT = 0;
P1DIR = 1;
while(1) {
TOGGLE_LED1;
delay();
}
1 The MSP430 datasheet has only 13 pages describing the working of the basic clock
module - page 273 to 286

2
}

Notice how the RED led blinks when you run this code! There are a few points
to discuss regarding this program:

3.1 Use of a delay loop


The delay function simply executes a loop 30000 times (an unsigned int, on
a MSP430 processor, is a 16 bit variable which can hold values from 0x0 to
0x - or, 0 to 65,535 in decimal). You know that the code which actually gets
executed on the controller is machine code. A loop like the one given above will
be translated by the C compiler into a few assembly instruction (which will in
turn be transformed into machine code by the assembler and the linker - I hope
you have not forgotten the dierent stages of the C compilation process which
we had studied in an earlier lesson). I can see that the GNU C compiler on my
system has transformed the loop into six assembly language instructions. I infer
from the datasheet that on an average, each instruction takes about 3 cycles of
the clock signal to execute. If our clock frequency is 1MHz, each clock cycle will
take 1 micro second. So, six instructions will consume 18 microseconds.
The loop is executing 30,000 times - so total time spent in the loop is:

30000 * 18 micro seconds

Which is equal to:

540,000 micro seconds = 540 milliseconds = 0.54 seconds

This is a very rough back-of-the-envelope calculation - but it does give us an


idea of how much delay we can expect. The things which make this calculation
not very accurate are :
2

1. The digitally controlled oscillator's frequency is not very precise - the


processor datasheet says that on powerup, this frequency will be between
0.8 to 1.5MHz. We don't really know what the exact frequency is.

2. The 3 cycles average gure is also not very accurate - we will have to
refer the datasheet and nd out how many cycles each instruction takes
to arrive at a more accurate gure.

3.2 Use of BIT0 and BIT6


BIT0 is a #dene'd constant whose value is 1. BIT1 has value 2, BIT2 has
value 4, BIT3 = 8, BIT4=16, BIT5=32, BIT6=64 and BIT7=128.
Note the patterns: BIT0 has a binary pattern with the only the D0'th bit
being 1. BIT1 has only the D1'th bit equal to 1. BIT2 has only the D2'th bit
equal to 1 ... and so on.

2 There are a few other issues concerning compiler code generation which we shall not
discuss at this point

3
These patterns are useful for manipulating individual bits of peripheral reg-
isters. For example, the statement:

P1OUT = P1OUT | BIT2

will set the D2'th bit of P1OUT (thereby making pin P1.2 go logic HIGH if it is
congured as an output pin). Similarly, the statement (remember, ^ represents
the bitwise XOR operation):

P1OUT = P1OUT ^ BIT0

will result in the D0'th bit of P1OUT toggling its value (if current value is 1, it
becomes 0, if it is 0, it becomes 1). Similarly, the statement:

P1OUT = P1OUT & ~BIT2

will result in the D2'th bit of P1OUT becoming equal to 0, with no other
bits aected. We should always use these symbolic names when manipulating
individual bits.

3.3 Use of LED1 and TOGGLE_LED1


We declare a macro LED1 (#dened to BIT0) to make our code more readable;
now we can use a more meaningful name, LED1, in our code rather than the
more cryptic BIT0.
The TOGGLE_LED1 macro also is meant to make the code more readable.
Note that:

P1OUT ^= LED1

is equiavalent to:

P1OUT = P1OUT ^ LED1

which has the eect of toggling P1.0 (the pin to which LED1 of the launchpad
board is connected to).

4 Timer A

[Note: The MSP430's Timer A is a complicated device capable of doing many


interesting things. In order to keep this discussion simple, we shall explore only
a very small part of the working of this peripheral.]

4
4.1 What does a timer really do?
The timer is conceptually a simple device. Here is how it works: every timer
has a register internal to it which is capable of holding an 8/16 bit value. The
timer takes as input a clock signal. Suppose the frequency of this clock signal
is 100Hz. Once the timer starts running, the value stored in the internal 8/16
bit register will get incremented every cycle of the clock signal. That is, if the
value of the timer register was 0 at the moment the timer got started, after 1
second, its value will become 100 (if the clock frequency is 100Hz).
Now, here comes the really important point: you have to execute certain
instructions in software to start the timer - but once it starts running, the count
will get incremented once every clock cycle - the microcontroller can keep on
executing the instructions in your program and the timer will happily run in
parallel!
The key word here is in parallel. Make sure that you have understood
this properly - none of the discussion below will make sense if you do not get
this idea. The microcontroller keeps running your code and the timer keeps on
ticking independently, in parallel!
How can such a device be useful? Suppose you wish to measure the time
dierence between an I/O pin going low-to-high and then high-to-low. Here is
a recipe for doing this:

1. When you detect the input pin going low-to-high, set the timer register
to zero and issue an instruction to start the timer.

2. Note the value of the timer register when the input pin goes high-to-low.
Store this in a variable.

Suppose the value of this variable is 10 - this means that 10 cycles of the timer's
input clock had elapsed between the transitions on the I/O pin. Assuming that
the clock frequency is 100Hz (which means clock period is 10 milli seconds), the
total time dierence between the I/O pin transitions is:

10 cycles * 10ms/cycle = 100ms

4.2 More about the clock input to the timer


The frequency of the clock input to a timer unit can be dierent from the
frequency of the clock which synchronises the processor's instruction execution.
In fact, on most microcontrollers, it is possible for us to select a range of clock
frequencies - starting from a base frequency and then getting scaled down by
factors of 2, 4, 8 etc. We shall see more about this very soon ...

4.3 The accuracy of a timer


The accuracy of a timer is tied to the accuracy of it's input clock. Only if
you know the precise value of the clock input to the timer will you be able to
compute delays accurately. By default, the MSP430G2231 on the launchpad

5
uses an internal digitally controlled oscillator (DCO) as a clock source - with
the DCO frequency set to a value between 0.8 to 1.5MHz. The problem is that
we do not know what the precise value is. In some applications, this may not
really be a problem. But if you really wish to get precise timing, you will have
to think of choosing a clock source other than the internal DCO .
3
On most microcontrollers, you have an option to use an external component
(a quartz crystal; reference: http://en.wikipedia.org/wiki/Crystal_oscillator)
to provide a stable clock signal with precisely known frequency. The MSP430G2231
microcontroller too has this option (you might have noticed that the launchpad
kit comes with a watch crystal which may be soldered on to the board if
required), but we shall not explore it at the moment .
4

4.4 Blinking LED with the MSP430G2231's Timer-A


With this much of a background, let's look into how we can program the
MSP430G2231's Timer-A. The objective is to blink an LED, but this time, we
will use the timer for generating the delay. Please keep the processor datasheet
open while you read this!
Timer-A is a 16 bit timer (meaning the timer register is capable of holding
values from 0 to 65535). It's working is documented in page 357 of the msp430
family user's guide. Don't worry if the descriptions given there don't make too
much sense ... it will take some time for you to become comfortable reading
processor manuals!
Like any other peripheral device, the timer too is manipulated using periph-
eral registers. There is only one peripheral register which we shall manipulate
in our program; it is called:

TACTL (Timer A Control Register)

Refer page 372 of the datasheet - you will see a description of this 16 bit register
on that page. The page begins with two table rows with each row containing
names like IDx, MCx, TACLR etc.
What does the name IDx represent? It is the name given to two bits of
this register, bits 6 and 7. Similarly, what does the name TACLR represent? It
is a symbolic name given to bit 2 of TACTL. Because each bit of the register has
some special purpose (except the few unused bits), it makes sense to give specic
names to them so that you can talk about them without actually mentioning
the bit numbers. Note that these names are just a notation used for convenience
sake.
You will see something like this written below TACLR (and all the other
bits):

3 It is possible to calibrate the internal DCO to a certain frequency. But once again,
there are other issues. The DCO frequency will change with temperature ... the only way to
achieve a stable frequency over a range of temperatures is to use an external crystal as the
clock source.
4 Some more info, for those who are interested: http://mspsci.blogspot.com/2010/06/crystal-
timers.html

6
rw-(0)

This says that the bit is read-write - you can read it's value, you can also write
to it. The (0) indicates the fact that the default power-up value of the bit is 0.
We shall now look at what some of these bits are actually used for!

4.4.1 Conguring the clock source to the timer

Let's focus on the bits TASSELx (Timer-A clock source select) - bit numbers 8
and 9.
There are multiple sources for the clock signal to the timer on the msp430
processor. A discussion of the dierence between these sources is beyond our
scope at the moment. You need to understand the following:

1. You can choose the clock for timer-A from 4 dierent sources

2. This selection is done by using one of the four combinations of values: 00,
01, 10, 11 as the value of the TASSELx bits (bits 8 and 9).

3. For the moment, we will chose the SMCLK


5 as our clock source. The
SMCLK is obtained from the DCO (about 1MHz) on power up. For
choosing SMCLK, we need to set bit9 to 1 and bit8 to 0.

4.4.2 Pre-scaling (dividing) the clock to the timer

It is possible to divide (ie, reduce) the frequency of the clock


6 before it is fed to
the timer unit. This division may be required when you wish to generate longer
delays. The division factor is set by the two bits 6 and 7 (the IDx bits).
The manual tells us that an IDx value of 00 (bit7=0, bit6=0) will result in
a divison factor of 1 (ie, no division). An IDx value of 01 (bit7=0, bit6=1) will
set the divison factor to 2, an IDx value of 10 sets division factor to 4 and IDx
value of 11 sets division factor to 8.
The choice of the division factor depends on the specic needs of the appli-
cation.

4.4.3 Choosing the timer operating mode

The timer has four dierent modes of operation. These are:

1. STOP: The timer is stopped.

2. Continuous mode: The timer increments the value of the internal count
register from 0, 1, 2, 3, ... 0x (65535) - one increment per clock cycle.
Once the maximum count of 0x is reached, the count resets to 0 and
the process restarts. So the count sequence is: 0, 1, 2, 3, .... 0xfe, 0x,
0, 1, 2, 3, .....

5 The Sub Main Clock - ref: page 274 of processor datasheet


6 Lower the frequency, greater the time period

7
3. Up mode: The timer counts from 0 to the value specied in a special
register called TACCR0. Once the value of the count register becomes
equal to the value in TACCR0, the counter resets to 0 and the process
restarts.

4. Up/Down mode: The timer counts from 0 to the value specied in a special
register, TACCR0. Once the value of the count register becomes equal to
the value in TACCR0, instead of resetting to 0, the timer starts counting
down. For example, if the value in TACCR0 is 5, the count sequence is:
0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, 3, ....

Each of the three modes (we ignore the STOP mode) is useful in certain contexts
(we shall not analyse the specic contexts in this lesson). The simplest mode is
Continuous - we will use this mode for writing our LED blinking code. The
MCx bits (bit4 and bit5 of TACTL) decide the operating mode. Refer the
processor manual for the MCx bit combination for each operating mode.

4.4.4 Using the TAIFG bit

There is an easy way to know when the count resets to zero - simply check
the value of bit 0 of the TACTL register. This bit is called TAIFG (Timer A
Interrupt Flag). TAIFG gets set to 1 when the count becomes 0. If you clear
the TAIFG bit (ie, set its value to 0), it will automatically become set again the
next time the count becomes equal to 0.

4.4.5 Writing the blinking LED program

You now have enough information to write the blinking LED program. The
rst version of this program used a simple loop to generate a delay. In this
version, you will use Timer-A to generate the required delay.
I will provide you with an outline of the code; you have to replace the
comments in the code with actual C statements and it will start working!

#include <msp430.h>
main()
{
// set P1.0 as output
// make P1.0 go logic HIGH
// Initialize Timer-A; SMCLK; no division, continuous mode

while(1) {
while(/* TAIFG bit is 0 */)
;
// clear TAIFG bit (ie, make it 0)
// Toggle LED on P1.0
}
}

8
I shall elaborate a few points:

1. Keep in mind the fact that the timer, once started, runs in parallel with
your code, in a completely independent way.

2. The basic idea is simple - you start the timer and wait for it to overow
to zero; this overow happens after 65536 clock cycles. If the clock is
1MHz (time period = 1 micro second), the overow will happen in about
65 milli seconds. You know that the timer has reset to 0 when the TAIFG
bit becomes 1 - so you keep on looping as long as the TAIFG bit is zero.
That is what the inner while loop (the loop with empty body) does!

3. Once the timer has reset to 0 (in about 65ms), you can toggle the LED
and once again wait for the next overow! Remember, the timer keeps on
going tick-tick-tick ... while your code is running!

4. The clear TAIFG bit is required because we will know that a count reset
(from 0x to 0) has occurred only when the TAIFG bit changes from 0
to 1. Once this bit becomes set, it is our job to clear it and then wait
again till it becomes set!

5. The timer initialization is done by writing a number


7 to the TACTL reg-
ister. How do you nd out this number? Simple - just write down the
patterns required for the TASSELx, IDx and MCx bits. Set all the re-
maining bits to 0. We are initializing the timer in such a way that the
clock is chosen as SMCLK, division factor is set to 1 (no division) and
mode is set to continuous.

Now, go ahead, write the code and enjoy the sight of the LED blinking! (And,
don't forget to push your code to github!).

4.5 Modications
Try to experiment with the code in dierent ways. A fun idea is to vary the
frequency of blinking by changing the IDx bits - try all combinations!
More advanced stu: Read the processor manual and try to use the UP
mode or UP/DOWN mode! Can you blink two LED's (red and green) on the
launchpad board at dierent frequencies?
Another experiment: Compile the rst version of the LED Blinking program
(using delay loop) using the extra option -O3 (gcc -O3 -mmcu=msp430g2231 -
mdisable-watchdog a.c). What do you see when you run the code?

5 Exercises

1. What is the frequency of an oscillator made using a standard watch crys-


tal?
7 We will see a way to represent this number symbolically in the next lesson!

9
(a) 1KHz

(b) 32768Hz

(c) 14236Hz

(d) 1MHz

2. Is there anything interesting about the frequency 32768Hz?

(a) It is a power of two, and there is something interesting in it.

(b) It is a power of two - but there is nothing interesting in it.

3. I wish to initialize Timer-A in UP/DOWN mode, clock source = SMCLK


and division factor = 8. Which number should I write to TACTL?

(a) 0x823

(b) 0x2f0

(c) 0x0135

4. The register which holds the timer's count can be accessed in your program
- the name of this register (as per the processor manual) is:

(a) TAIV

(b) TACCR1

(c) TAR

5. A Phase Locked Loop (PLL) is used for:

(a) Amplifying a signal

(b) Frequency multiplication

6. Which of the following I/O pins of the MSP430G2231 has no alternate


function associated with the timer ?
8

(a) P1.0

(b) P1.3

(c) P1.1

8 Ref: http://recursive-labs.com/datasheets/msp430g2x31.pdf

10

You might also like