03 October 2010

Tutorial 11-b: Using the Auxiliary Clock

If you did the exercise at the end of the last tutorial, you probably noticed that the program stopped working if you tried using any of the LPMs other than LPM0 or LPM1.  The reason for this has to do with the clock that is chosen to power the timer.  So let's take a careful look at just what's happening in the limboG2211.c program.

First of all, we set the DCO to the calibrated 1 MHz frequency.  Pretty straight-forward here; the MSP430 MCLK timing the CPU will operate at very close to 1 MHz.  What isn't as obvious is that the sub-main clock (SMCLK) is also driven by the DCO, and so also operates at 1 MHz.

The timer is then configured to run with the SMCLK divided by 8, or at 125 kHz.  The timer counts to TACCR0 and then triggers an interrupt, wherein the current through the speaker (or current to the LEDs if you changed it to that mode) is switched.  The frequency of the switching drives the speaker to create a particular tone.

In between switches, the MSP430 enters LPM0.  We can see what happens to the chip when entering this mode by looking again at the diagram and table on page 2-15 of the x2xx Family Guide: the CPUOFF bit in the Status Register is set to 1.  The CPU turns off, as does MCLK, leaving SMCLK and ACLK running.  If we run LPM1, then the CPUOFF bit is set as in LPM0, and in addition SCG0 is set to 1.  We can see that this mode has the added benefit of turning off the DCO if the SMCLK is not being used.  In our case, we're using SMCLK to drive Timer A, so the DCO is not turned off for LPM1.  Essentially, for this program, there is no difference between LPMs 0 and 1.

If we move to LPM2, however, we set CPUOFF and SCG1, which has a much different effect: in addition to the CPU and MCLK, SMCLK is disabled, allowing the DCO to also be disabled.  In our program, then, when we enter LPM2 we turn off the clock driving Timer A; Timer A never reaches TACCR0, and an interrupt is never triggered to cause the MSP430 to exit the LPM.  In LPM2, however, ACLK is allowed to continue running.  If we drive Timer A with ACLK, then, we could use deeper modes and consume less power overall!  Less power means more battery life and more efficient use of the resources in the MSP430 design.

ACLK is typically driven at low frequencies (comparatively), and so draws less power than does DCO, further improving our goal of reducing power consumption.  By default, it is set to use a 32,768 Hz quartz crystal.  Your LaunchPad kit came with a crystal that you can solder onto the board to use here.  Alternatively, you can configure the LFXT1 clock source to run from an internal oscillator, similar to the DCO, that operates at a very low frequency (typically 12 kHz).  This oscillator is referred to simply as the VLO.

Configuring LFXT1 and ACLK
If you're planning to use the crystal oscillator on LFXT1, there's likely little that needs to be done.  The crystal that comes with the LaunchPad needs 12.5 pF capacitors for stability, and you might notice the SMD solder pads near the crystal location for capacitors.  You can use discrete capacitors if you like, but the MSP430 is also configured with a few capacitances internally, and 12.5 pF is one of the choices.  Using the crystal is a simple matter of soldering it onto the board and configuring the BCS+ module correctly.  There are a lot of switches and controls involved here, so we'll save crystal control for a later tutorial, and assume for now that we're going to use the VLO to source the Auxiliary Clock.

Section 5.3 in the x2xx Family Guide (starting on page 5-13) holds the necessary information for configuring the BCS+ module.  The registers we need for now are BCSCTL1 and BCSCTL3.  In terms of setting up the VLO, we need the XTS bit in BCSCTL1 (bit 6) and the LFXT1Sx bits in BCSCTL3 (bits 5 and 4).  The XTS bit sets the LFXT1 clock source to low or high frequency.  Many MSP430s in the x2xx family let you use a high frequency crystal for this source; the value line devices, however, only support low frequency (ie. 32,768 Hz) crystals.  When this bit is cleared to 0 we have configured the chip for low frequency ranges.  Some devices, including the value line chips that come with the LaunchPad, allow us to use the VLO.  This mode is selected by setting the LFXT1Sx bits to 0b10, as described on page 5-16.  To do this in C, we again make use of a header file definition:

BCSCTL3 |= LFXT1S1;  // sets LFXT1Sx to 0b10, VLO mode

We don't need to explicitly change the XTS bit, as it defaults to the low frequency setting.  This line is sufficient for setting up the VLO.

With LFXT1 now oscillating at 12 kHz, ACLK can be used for the peripherals.  You may recall from Tutorial 08-a that ACLK only sources from LFXT1, using either a crystal or the VLO.  We can, however, alter the frequency for ACLK by dividing the VLO by 2, 4, or 8.  This is done in BCSCTL1 with the DIVAx bits (5 and 4) with the configurations given on page 5-14.  For our purposes, we'll set ACLK to run at about 3 kHz by dividing the VLO by 4.  We do this with the following code:

BCSCTL1 |= DIVA_2;  // ACLK divide by 4

Keep in mind that you can also divide the clock in the peripheral itself, or further divide inside the peripheral.  For example, we can run Timer A at 750 Hz by dividing by an additional factor of 4:

TACTL = TASSEL_1 + ID_2 + MC_1 + TACLR;  // use ACLK, div 4, up mode, clear

To summarize, we can modify the limboG2211.c code to use the following:

BCSCTL1 = CALBC1_1MHZ; // Running at 1 MHz
DCOCTL = CALDCO_1MHZ;
BCSCTL3 |= LFXT1S1;     // VLO mode


TACCR0 = 14;  // With the Timer using ACLK (12 kHz), this
  // value gives a frequency of 12000/(TACCR0+1) Hz.
  // For TACCR0 = 14, that's 800 Hz.

TACCTL0 = CCIE;         // Enable interrupts for CCR0.
TACTL = TASSEL_1 + MC_1 + TACLR;  // ACLK, up mode, clear timer.

_BIS_SR(LPM3_bits + GIE);  // Enter LPM3 and enable interrupts

This code sets ACLK to run from the VLO (at ~12 kHz) and then uses Timer A to switch the speaker at ~800 Hz.  Most importantly, since we are now sourcing the timer which causes interrupts from ACLK, we can use LPM2 and 3 in our program.  Note that LPM4 would turn off the ACLK; using LPM4 is only feasible if we have some external interrupt source, such as watching for a signal on one of the GIO pins.

We'll return to looking at the low power modes soon; the first real scientific project we'll do will analyze and compare the power consumption of a simple MSP430 design using the various LPM settings.  To do this, however, we're going to need to measure an analog signal and record data.  The next tutorial will start us in this direction by looking at analog to digital conversion.

Reader Exercise:  Suppose your LaunchPad has the crystal soldered onto it, and is being used in a project that does not use ACLK at all.  The crystal will continue to oscillate, and use power (albeit a very small amount) that is not contributing to the overall design.  Note that none of the standard LPMs disable ACLK and the crystal oscillator except LPM4.  Write up the needed line(s) of code that would create a new LPM that keeps MCLK, SMCLK, and the DCO running, but disables ACLK and the crystal oscillator.

01 October 2010

Yes, the blog is officially back!

Thanks, everyone, for your patience.  My research has been moving quite a bit lately and occupied the majority of my time.  Fortunately the 16 hour work-days are over, and I have some spare time and motivation to play with the LaunchPad some more.  I've posted the first part of a multi-part tutorial on Low Power Modes (by popular demand!) and have a bunch of great ideas coming up.  We'll be working toward being able to make your own LaunchPad circuit board (minus the SBW programmer, of course) and communicating with a computer among many other fun things.  Send me a note if you have any particular topics you're aching to learn about.  We'll keep on with LPMs and start ADC soon as I wait for the boards I've designed to arrive.  Watch for some design notes and other posts to come soon!

Tutorial 11-a: Going Low Power

Now that we have some degree of control over the MSP430, it's a good opportunity to introduce the low power mode.  This feature is arguably one of the most important for the MSP430, and is an excellent reason for choosing this microcontroller over many others.  Let's look at how the modes work.

The operating mode of the MSP430 is controlled with four different bits in the status register.  These bits are called CPUOFF, OSCOFF, SCG0, and SCG1.  The first two are fairly self-evident; the first of these controls the power to the CPU of the MSP430.  The second controls the power to the external oscillator (ie. crystal usually).  In addition, these bits turn on/off MCLK and ACLK respectively, since those are associated with the CPU and LFXTL.  The other two bits add more control over SMCLK, the DCO, and the DC generator.

Page from the x2xx Family Guide describing
the low power modes.
In the x2xx Family Guide, page 2-15 shows a diagram and table explaining how the operating modes work.  For our convenience, TI has defined 6 different modes that are easily accessible to us via the header files.  The MSP430 starts off in Active Mode, where the CPU and all clocks are up and running.  This is the mode in which we've been running up until now.  Any time the MSP430 needs to do something, it will be in Active Mode.  That's not to say that peripherals can't operate in the other modes.  There are 5 low power modes, labeled LPM0 through LPM4.  These are the commonly used configurations, and only rarely will you need one of the other 10 possible modes available with a 4-bit configuration.  (One exception to that would be turning off an unused crystal oscillator that's soldered to your LaunchPad, but not being used in your current project.  More on that later.)

the _BIS_SR() function we saw earlier is perhaps the easiest method of using the LPMs.  The header files define a set of names called LPMx_bits to help with the bit management.  To enter a low power mode, simply issue the command _BIS_SR(LPMx_bits); with x replaced by the LPM number you've chosen.  Keep in mind that if you want to use interrupts, you will also have to add GIE to the argument, or at least _enable_interrupt(); before going into the LPM.

Another good thing to keep in mind is that the LPMs are distinct; you don't need to include LPM0 to use LPM1.  In fact, doing so (eg. using a command such as _BIS_SR(LPM0_bits + LPM1_bits + GIE);) would have undesirable side effects by adding the binary values that the header file definitions provide together.

One of the features of the MSP430 architecture is that you don't need to tell the CPU to wake up on the interrupt, nor do you need to put it back in the LPM manually.  All of this is done automatically; when an interrupt is triggered, the Status Register is saved to memory (pushed onto the stack) and reset, waking up the CPU.  Once the ISR has been satisfied, the original Status Register (including the LPM setting) is popped off the stack back into its place, and the MSP430 returns to the low power state.  If you require your program to wake up the chip and stay awake, you will need to include a line in your ISR to do so:


_BIC_SR(LPMx_bits);  // clears the bits corresponding to LPMx and exits the low power mode

Note the different function name; _BIS_SR() is Bit Set Status Register (ie. set to 1) while _BIC_SR() is Bit Clear Status Register (ie. clear to 0).

Example using the Low Power Modes
As an example, I've coded up a simple program that plays a tone on an 8Ω speaker.  The speaker I have has two pins with 0.2" separation, and so it plugs right into the headers on the LaunchPad.  To accommodate the spacing, I'm using P1.0 and P1.2 to drive the speaker.  If you don't have a speaker available, you can simulate the same idea using the two LEDs on the LaunchPad; just follow the instructions in the code and change SOUT to BIT6 and adjust the frequency accordingly.

The idea is simple; we start with P1.0 high, P1.2 low, and switch each at a given frequency.  This method provides a square wave, not a pure tone, but it does work.  Keep in mind that audible frequencies are generally in the 100's and 1000's of Hz.  It might be interesting to see how low of a frequency you can hear (clicking doesn't count; listen for an actual tone) and how high you can hear.  Also, you can keep one pin constantly low and switch only the other if you want to reduce the volume.

There's more to explore with the low power modes, and next time we'll start playing with the low frequency oscillator to drop into the deeper sleep modes.

Reader Exercise:  This tutorial's code uses LPM0.  Try out the other low power modes by using LPMx_bits in place of LPM0_bits.  What happens if you try to use LPM1?  LPM2?  LPM3?  LPM4? Can you explain why some of these work and others don't?  Those that work, is there any actual difference between the modes as implemented for this program?  As you answer these questions, think about what clock is sourcing the timer and what oscillator is used for the clock.

16 September 2010

A Great Example of an MSP430 Based Instrument

I ran across an interesting article in reading the news during my lunch break today. A group at the University of Washington has been doing research in smart sensors that communicate through the established power lines in a house.  The page doesn't say specifically, but given the power consumption they mention I wondered if this was based on an MSP430.  A close up of the photo of the board looks like it might be, and you can just make out the TI logo on the chip.  Digging a little deeper, I confirmed that yes, this instrument is based on the MSP430.  The team is using a surface mount variation of the MSP430F2013.  This chip is also available in a 14 pin DIP package that is compatible with the TI LaunchPad.  Very cool idea.

In other news, my project is now at integration, and I have some extra time on my hands.  Watch for a couple new tutorials coming this week!

21 August 2010

Still Alive

I've had a number of people ask about the long delay since my last post, so I thought I'd put a quick note up to give you an update. My deadline to deliver the instrument I'm building for my Ph.D. research is coming up in a couple of weeks. As such, I'm spending 10-14 hours a day in the lab, and haven't had a moment to think about the blog in a while. Once the instrument is delivered, however, there will be lots of time opening up. I have had lots of ideas and do have lots of plans for this site, so thanks for your interest and patience! I'm really encouraged by the good reviews I've gotten for what I've written up so far. I do really think the MSP430 can be a very important tool in developing instruments for use in or out of a laboratory, and we'll get to try some out soon.

03 August 2010

Tutorial 10-b: Interrupt Examples

GPIO Interrupt Example
The first example we'll do uses the Port 1 interrupts; this code is easily changed for any port number used in your particular device.  This code will show how to do the DCO example we did in Tutorial  08-b, which demonstrates changing the DCO, using interrupts.

First, we need to configure the port to use interrupts.  The LaunchPad button is on P1.3, so all of our concern will be on that pin.  The pin needs to be configured as an input.  Since the default state of the pin is logic 1, a high-low transition (a drop from 1 to 0) should be used to signal the interrupt.  We can code this using:
P1IES |= BIT3;   // high -> low is selected with IES.x = 1.
P1IFG &= ~BIT3;  // To prevent an immediate interrupt, clear the flag for
                 // P1.3 before enabling the interrupt.
P1IE |= BIT3;    // Enable interrupts for P1.3

We've enabled the interrupt for P1 now, and a high-low transition caused by the button press will set the interrupt flag in P1IFG.  The processor, however, isn't set to recognize maskable interrupts like P1IFG.  We can turn on the interrupts with:
_BIS_SR(GIE);

or equivalently:
_enable_interrupt();  // Note the singular name here!  It's not interrupts.

The first method parallels the bis.w instruction in assembly used for this command, and can be used to configure the SR in one step with other options, such as low power modes.  The second method is a little more human readable, and works well enough if you don't need to enable any LPM's.

Next we need to write the ISR.  Something like this will work:
#pragma vector = PORT1_VECTOR
__interrupt void P1_ISR(void) {
    switch(P1IFG&BIT3) {
        case BIT3:
            P1IFG &= ~BIT3;    // clear the interrupt flag
            BCSCTL1 = bcs_vals[i];
            DCOCTL = dco_vals[i];
            if (++i == 3)
                i = 0;
            return;
        default:
            P1IFG = 0;    // probably unnecessary, but if another flag occurs
                          // in P1, this will clear it.  No error handling is
                          // provided this way, though.
            return;
    }
} // P1_ISR

The port interrupts can be sourced from 8 port pins, and so the ISR needs to decide what to do with each possible interrupt.  The switch statement in C is ideal for this task, and is used here to single out a BIT3 flag.  If, for some reason, the MSP430 is flagged with a different Port 1 interrupt, it simply clears the flag and moves on.  Since none of the other flags are enabled, this should never happen, but it's good coding practice to include something like this.  Error handling would be ideal, but it's not done here.

Note that since the P1 interrupt has 8 sources and individual flags, you need to clear the flag manually.  Don't forget to do this, or your code will continually keep interrupting!  This code makes use of three pre-stored values for BCSCTL1 and DCOCTL and increments through them each time the interrupt is called.  These values, as well as the counter i, need to be global for the ISR to see them, and so they are declared outside of the main() function.  See the whole code put together in interrupted-1_G2211.c.

Timer_A Example
As a second example, we'll do something similar to a project I'm working on and turn a light on and off using a relay switch.  I've coded this using a switch on P1.6 so that you can observe its behavior on a LaunchPad using the green LED instead of the actual relay.  If you have a relay, be sure to connect it correctly to prevent too much current draw from your MSP430.  Using the 1 MHz calibrated DCO divided by 8, Timer_A will count up to 62,500 in 0.5 s.  In my actual application, I'd like to turn the light on for a few hours, then turn it off for a few hours.  That's easier to do with a slower clock, and an ideal application for the LFXT1 clock source.  But, since we haven't covered that yet and many people likely do not have the crystal soldered to their LaunchPad's, we'll do more frequent on/off cycles to simulate the actual process.  We'll use the DCO to turn the light on and off in 1 minute intervals.  To do this, we'll make use of the Timer_A up mode and interrupt using the CCR0 registers.  (Yes, this is essentially a fancy version of blinky.  Turns out "Hello, world!" is actually useful in microcontrollers!)

We configure the timer with the following:
TACCR0 = 62500 - 1;  // a period of 62,500 cycles is 0 to 62,499.
TACCTL0 = CCIE;      // Enable interrupts for CCR0.
TACTL = TASSEL_2 + ID_3 + MC_1 + TACLR;

The long string of assignments to TACTL are, in order, select SMCLK as the clock for Timer_A (runs off the DCO by default), select input divider of 8 (1 MHz SMCLK becomes 125 kHz), select up mode, and clear the count in TAR.  These values are defined in the device header file so that you don't have to constantly manipulate bits by hand.  The mnemonics are easier to use most of the time.  (For other configuration options, see the Timer_A section in your device's header file.)

The ISR may look something like this:
#pragma vector = TIMERA0_VECTOR
__interrupt void CCR0_ISR(void) {
    // no flag clearing necessary; CCR0 has only one source, so it's automatic.
    if (++i == 120) {
        P1OUT ^= RLY1;
        i = 0;
    }
} // CCR0_ISR

Again, we're using a global variable i as a counter, and presumably have defined RLY1 to be BIT6 in the program header.  Every time a flag occurs (twice a second) the counter is incremented.  If we've reached 120 (60 s at 2 Hz) the relay control is toggled and the counter resets.

The complete code for this example is in interrupted-2_G2211.c.  For you impatient folks, feel free to adjust the timer period to whatever value preserves your sanity.

These two examples should get you started with interrupts.  As always, feel free to ask questions or suggest other helpful tips!

Tutorial 10-a: Something Completely Different (Interrupts)

I realized half way through the last tutorial that we need to take an aside for now.  One of the unfortunate aspects in microcontrollers, especially for those with no prior experience, is that you run into chicken-egg dilemmas all the time.  How can you teach timers without interrupts?  How can you teach interrupts without something to cause interrupts, like timers?  It takes some patience, but with some experience (and lots of examples!) things start to settle into place.  In the mean time, I apologize for the occasional jump in topic.  For that matter, we're not entirely done with previous topics either, and will revisit some of the more advanced concepts of GPIO, Clocks, and so forth in the future.

So what exactly is an interrupt?  Hopefully you're familiar enough with C programming (if not, I highly recommend spending some time with a good book; I suggest the C Primer Plus (5th Edition)) to have a good handle on function calls.  Microcontrollers use function calls as we've seen before, just as your personal computer does.  But microcontrollers also interface with the outside world, and sometimes you need to perform a specific task based on what happens outside the circuit.  One option would be to continuously poll an input (or sequentially poll a set of inputs) to see if anything needs to happen and call the appropriate function accordingly.  Unfortunately, this ties up the processor so that it can't do anything useful in the mean time.  Perhaps worse, the processor keeps chugging along, using up power doing nothing but waiting to see if it's got a job to do.  The better option is to have the outside signal interrupt the processor (from its current task or its nap) to get a task done and then allow the processor to go back to what it was doing.  This ability is implemented in the aptly named interrupt service routine (ISR).

The Interrupt Handling Procedure
In order to control multiple sources at once, the MSP430 needs to have some definite organization; who gets priority over the other peripherals?  How do we keep track of where we were before?  To do this, the MSP430 is designed with a clean and efficient procedure to handle interrupts.

  1. If a peripheral's interrupt is enabled, the appropriate signal sets the interrupt flag in one of the peripheral's registers.
  2. If the processor is allowing interrupts, the presence of a peripheral interrupt flag sets a general flag to the processor.
  3. The processor finishes any instruction it's currently doing.
  4. The processor saves it place by copying the address where it's currently executing instructions (the value in the Program Counter (PC) register) to the memory stack (this is called "pushing onto the stack").
  5. The processor saves its current status by pushing the Status Register (SR) onto the stack.
  6. The interrupt that currently has the highest priority is selected if there are multiple flags set.  Check your device's datasheet for a list that shows the priority of the possible interrupts.
  7. The interrupt flag is cleared, unless the peripheral has more than one type of interrupt.  In that case, you have to clear the flags manually.
  8. The SR is cleared, which disables any further interrupts during the ISR handling and wakes up the processor from any low power mode (LPM).  Note that only "maskable" interrupts are disabled by the SR clear; this means "non-maskable" interrupts, such as a reset, are still possible during an ISR.
  9. The address of the interrupt vector is copied to the PC, directing the processor to start executing code from that address on.
From the start of an interrupt signal to the start of ISR execution can take anywhere from 6-12 clock cycles of the processor, depending on exactly what's going on when the interrupt is flagged.  (This latency isn't much, but must be handled differently for time-critical event handling.)  If the chip is operating at 1 MHz, that's anywhere from 6-12 μs for the processor to respond to an event.

When the ISR finishes, the processor executes the return from interrupt sequence, which consists of just two steps:
  1. Move the original SR value from the stack to the SR (this is called "popping" from the stack).
  2. Pop the original PC value from the stack to the PC.
This sequence takes another 5 cycles to complete, after which the processor returns to what it was doing.  Note that if the MSP430 was in an LPM before the interrupt, it returns to the same LPM after the ISR handling with no further instruction from the code necessary.  You only need to give a different instruction if you don't want the MSP430 to reenter the LPM.  We'll see how to do that soon, when we discuss the low power modes.

Coding Interrupts
Writing an ISR is very similar to writing encapsulated functions in C, but requires some special syntax that you may not have seen before.  Every ISR has this structure:
#pragma vector = <VECTOR_NAME>
__interrupt void <ISR_NAME> (void) {
    ISR code here
}

The keyword #pragma is used in C to signify a special operation peculiar to a compiler.  (If you were to compile your MSP430 code with another compiler, such as gcc, it would simply ignore this line, leading to potentially unexpected errors.)  In this case, it tells the MSP430 compilers that the following code is to be referenced for the particular interrupt named.  VECTOR_NAME is essential, and must follow the conventions for the particular peripheral interrupt being written used in your device's header file; the address of the start of the ISR in the code memory is recorded in the address defined by the header as VECTOR_NAME.  Take careful note that the #pragma line does not have a semi-colon at the end.

__interrupt signifies the start of the ISR.  You can name the ISR anything you'd like, but conventionally coders use something descriptive, such as P1_ISR for a Port1 interrupt, or TA0_ISR for a Timer_A interrupt.

Beyond that, everything remains the same as we're used to seeing.  There's no special code needed in C to start the return sequence, but in assembler you need to manage this using the reti instrunction.

Unused Interrupts
What happens if an interrupt is called and you don't have an ISR written for it?  The results are unpredictable, depending on what value is inside the interrupt vector.  The safest method to protect from this is to write an ISR for every interrupt, doing nothing, or perhaps entering an infinite loop, for interrupts not used.  (The infinite loop method makes debugging clearer; it's obvious where you get stuck that way!)  This convention doesn't take much code space in the MSP430, but can make your simpler projects a little more complicated to the outside viewer.  Another way to handle this problem is to be certain that unused interrupts are disabled so that they can't ever flag the processor.  Not controlling interrupts can cause serious problems, however, so be sure to try to use good coding practices whatever you do.

This part of the tutorial on interrupts is long enough, so the following post will give a couple of examples to get you started using what we've learned here.