29 September 2011

Tutorial 15a: Analog Signal Conversion

Looking back on the past tutorials, we really only have two more major peripherals to learn. Today, we'll start taking a look at the Analog to Digital Converter (ADC), then learn about serial communication methods in preparation for an actual scientific experiment.

A corrolary to the Analog to Digital Converter is the Digital to Analog Converter. Unfortunately, it's very difficult to fully understand either of these without understanding the other, but we can learn a great deal about each to start. To understand the actual inner-workings of an ADC or DAC system, we can start with the basic ideas and then learn how they are implemented. So first, let's examine what it is that's different between an analog and a digital signal.

An example of an analog signal
An analog signal is what we're most likely to experience in the physical world. An incandescent light bulb can be put on a circuit where by rotating a knob the brightness can be adjusted. The oven in your kitchen can adjust its internal temperature to any value between about 170 and 500 deg F. The music you listen to pulls the membrane of a speaker in and out to create pressure waves that our ears interpret as sound. For the most part, the universe around us is analog: any measurement can take any value within a continuous range. As a visual example, consider the sine wave. No matter how closely you look at this function, it's always smooth--each of the infinite number of values between -1 and 1 is found in the curve.

While there are digital equivalents in the universe, for the most part our common encounters with digital signals reside in the realm of computers and electronics. The key difference is that measurements can only take discrete values; it's like saying the value can be 1, 2, or 3, but not 1.3 or 2.14. Consider the discrete version of the sine wave shown here.
A digital representation of the analog signal

The red lines represent the digital values that approximate the sine curve (shown in cyan for reference). While this example may not look so great, picture what would happen if we can have more than the 9 possible values available in this example---you can probably imagine that more values in the discretization would give us a better approximation. The simplest ADC peripheral in the MSP430 is a 10 bit system, which gives us 2**10 (or 1024) values. The sine approximation looks quite good with this set:

10-bit digital approximation of the analog signal

Obviously more bits gives a better representation, but it does come at a cost, in both complexity and speed. The reasons for that are more apparent when we understand how an ADC comes up with its values, so let's take a look at the ADC itself.

In reality, we've already looked at elementary ADC by using the comparator. When we convert an analog value (in this case a voltage) to a digital value (a number), the result tells us something about the magnitude of the analog signal. For the comparator, a particular voltage threshold is set for the analog value, and the number is either 0 or 1, depending on if the signal is greater than or less than the threshold. This makes a 1-bit ADC; the number is expressed in a single bit.

While very useful for more applications than you might expect from a single bit, the comparator is limited in how  much it can say about the analog signal coming in. If the signal changes about the threshold, we see the bit change between 0 and 1. But if the signal is changing above or below the threshold without crossing it, we have no way of seeing that occur.

The simple-minded solution would be to add another comparator with a different threshold. If we set the threshold on the first comparator to 1 V, and the second to 2 V, with both returning 1 when Vin is greater than the threshold, we would have the following possible results:

  • 0,0:  both comparators are below threshold, so the voltage must be less than 1 V.
  • 0,1:  the first comparator is above threshold, but the second is below, so the voltage must be greater than 1 V, but less than 2 V.
  • 1,1:  both comparators are above threshold, so the voltage must be greater than 2 V.
This setup would work, but notice that it's not completely efficient. Particularly, it is impossible to get a result of 1,0, because the voltage cannot be greater than 2 V but less than 1 V. So adding comparators can give you a broader view of the analog signal, but it's not the best way to do it.

The MSP430 ADC10 peripheral uses a Successive-Approximation-Register ADC, or SAR ADC. This fancy name is simply a description of how the ADC makes its measurement. Have you ever played the number guessing game? Say I ask you to guess the number I'm thinking of between 1 and 100, and I'll tell you if you're low or high. What's the most efficient way of getting there? If you guess 90, and I say you're low, then you've narrowed it down to 10 possible values in just one guess! On the other hand, if I say you're high, then you've only eliminated 10 possible values. When you consider that compromise, it's clear the best starting guess would be 50-- you're guaranteed to eliminate half of the possibilities. What next? Well, it would make sense to cut the remaining possibilities in half-- if 50 was low, guess 75; if high, guess 25. If you continue on with this algorithm, it won't take you too long to come up with the number I'm thinking of. (It will take you at most 7 guesses.)

SAR works in the same way; note that in any binary representation, a 1 followed by zeros is half the total possible range in the same number of bits. (Eg. 0b1000 is 8, while the upper limit 0b1111 is 15.) If we take a single comparator and use half of our reference voltage, we get our first bit-- if it's above 1/2 Vref, set it to 1; if below, set it to 0. Then we set the comparator reference to either 1/4 or 3/4 Vref (depending on the value we just got), and compare again to get the next bit. Using this method, you can come up with the digital value in as many measurements as you have bits-- in the case of ADC10, it takes 10 measurements.

Note that instead of adding another fixed comparator, we use only one as opposed to the 1,024 we would have needed to get the same resolution. The compromise is that now we have to change the comparison voltage and make multiple measurements. These two factors lead to a limit on how quickly we can make a measurement; to get very fast measurements, we need fast settling times on both the reference divider and the recording to the data register (which depends on the number and frequency of clock cycles in the CPU, of course). The ADC10 is rated to measurements up to about 200,000 samples per second (or 200 ksps, in the nomenclature used for the datasheets).

The actual mechanism used to make the measurement is pretty simple; you use a DAC of some sort to set the reference according to the bits we've already set. The details are fascinating, but beyond the scope of this particular tutorial. Feel free to read in the Family User's Guide or in a copy of MSP430 Microntroller Basics to get more information. Search online as well. That concludes our introduction to ADC. This is only a basic introduction, of course, and the ADC10 has a wealth of powerful operating modes. Next time we'll look at how to configure the ADC10 peripheral.

13 September 2011

Tutorial 14b: Adding a New Library

Before I start this tutorial, let me add a caveat: I have a feeling this is not the best way to build a library in CCS. It is, however, the only way I could get it to work reliably short of copying the code into every project I use it in. If anyone has some experience with this in CCS, please send a comment and let me know!

We have code that will let us easily send text to the LCM, which would be very useful to have in a library that can be called up as needed, without having to rewrite (or copy-paste) the code every time. The C language makes doing this fairly easy, and so we'll look now at moving the LCM code into a library and go through how to configure a project in CCS to use the library. You should be able to add any code you'd like to reuse to this library and be able to call it up whenever needed.

First: choose a location to keep your library. It's not important where this library resides (from the compiler's point of view), but it's best to have it somewhere easy to get to when you add/change code in your library. At the same time, it should be somewhere safe, where it won't be accidentally deleted, moved, or changed in any unintentional way. I chose to create a folder in my workspace directory called 'library'.

Second: copy any #include, #define, function prototypes and global variables into a new header file. For this library, I've called it simple_LCM.h. If you're going to use definitions specific to the MSP430, you will need to include the MSP430 header as well. To keep your library general, rather than including the header file for a specific device, just #include <msp430.h>.

Third: copy the remaining code (the encapsulated functions) into a new .c file with the same name (ie. simple_LCM.c in this case). At the top of the file, you should add #include <filename.h> (replacing filename with the name of your library file). Note that this file should not have a main function in it.

Fourth: in your new project, right click the project folder and select new → folder. Click the [Advanced >>] button, and select "Link to folder in the filesystem". You can then browse to your library folder and finish adding the folder.

Any files in your library directory are now available for use in your code; the compiler, however, needs to be aware of the path to this folder to find it. (This is the part I don't like; this has to be done for every project, and I'm unable to find a way to make this path be a default in CCS for every new project.)

Fifth: right click your project folder and select properties. Open the C/C++ Build window, and in the Tool Settings, look for MSP430 Compiler → Include Options as well as MSP430 Linker → File Search Path. Both of these need to have your library folder added to the list in order to compile your code.

One shortcut I've found: In CCS, go to the menu Window → Preferences, then navigate to General → Workspace → Linked Resources. Here you can define a path variable (eg. My_Library) that links to your library directory. When you add a new folder to a project, instead of browsing to the folder location, you can click [Variables...] and select it from the list; it's much quicker that way. Unfortunately, I can't seem to get the project properties changes to recognize the path variable, though it seems it's supposed to.

Now we should be ready to build our capacitance meter using the LCM. The code I've written in CMeterLCMG2211.c demonstrates a number of new ideas using the LCM. Browse the code and examine the comments to see how it works. Note the use of MoveCursor(row,col); and the particular commands sent to configure the LCM.

While the simple_LCM library has a routine for printing strings, what happens when we want to print an integer value like the recorded value in the time variable? One intuitive option (at least if you're accustomed to programming in C) would be to use the stdio library and the function sprintf();. All we would need to do is set up a character array such as print_time[10], and use sprintf(print_time, "%d", time); to put the integer into the print_time string and pass it to PrintStr(). Unfortunately, this method has some serious problems for microcontroller use. First of all, even with the heavy streamlining done in CCS to reduce its size, any code using a printf function will be large. In this program, it would exceed the 2 kB of size available in this device. Second, the streamlining makes it difficult to format correctly; ideally, we'd use a %10d format specifier to put time into exactly 10 places to fit the print_time size. We can't do this with the streamlining implemented. We can change the printf assumptions in the project properties, but that makes the function use even more of our severely limited code space.

Fortunately, there are some ways around this problem. For an integer, we can pick off the individual digits by using the mod operator and integer division. x%10; will return the last digit of the number stored in x. x/=10; will remove the last digit and leave up to the second to last. By running a loop over the number until we reach a condition of x == 0 (no more digits), we can pick off each digit to print one by one. The ASCII codes (and the codes for the LCM) are arranged in a way such that the lower nibble corresponds exactly to the digit's value, so 0x30 + 0 is "0", 0x30 + 7 is "7", and so on.

The disadvantage to this loop technique is that the digits are picked off in reverse order--from right to left. The LCM has a mode that allows you to decrement the cursor position when you send characters, however, so it's possible to print from right to left in this way. (In fact, this ability is used in many hand-held calculators.) See the code for the exact code needed to configure the LCM for this mode.

And there's our first complete scientific instrument using the MSP430. We use a combination of the timer and comparator with a calibrated clock to measure the decay time in an RC circuit. The LCM displays the measured time in microseconds. Knowing the value of R and the reported time, we can calculate the actual value of C measured by the meter.

Reader Exercise: This works fine, but wouldn't it be nice to have the LCM display the capacitance rather than the time? You can do floating point operations in the MSP430 (albeit inefficiently), but how would you display a floating point number on the LCM? If sprintf was to big for the program above, it will definitely be too large in this case. Can you come up with a way to display the capacitance without exceeding the 2 kB limit for the G2211 device? If you get stuck, one way is demonstrated in CMeterLCMFull.c. It also has the benefit of being auto-ranging. This code takes up 1934 bytes of space-- just barely enough to squeeze into the G2211!

10 September 2011

Tutorial 14a: The Alphanumeric LCD

We're almost at a point where we have built a complete scientific instrument. The one thing the capacitance meter lacks is a way to provide the measurement outside of the debugging environment-- not very convenient for working in the field. There are a number of ways we can transfer the data somewhere usable. One way that is useful for single measurements is by displaying the result on an LCD display, much as consumer meters do. We're now going to look at using a standard alphanumeric LCD module with the LaunchPad. This project will also introduce the concept of building a custom library; by the end of this tutorial, you will have a library that you can import into future projects to add an LCD display without having to re-code the entire thing.

The LCD Module (LCM)

One disadvantage to this tutorial is that it require having an LCD display, which you might not have. If not, and are willing to purchase one, I would recommend doing so. These displays can be very useful, and are not very expensive. They come in a variety of sizes and styles-- for this tutorial we will use a standard 16x2 character alphanumeric display modules, such as those found at SparkFun.com. SparkFun carries a variety of these modules; feel free to pick one to your liking, but be certain of a few things: it needs to be configured to run on 3.3 V and should not have been modified to accept serial input. If you'd like a larger module (such as a 20x4 display), it's up to you, as they all work the same way. Get whatever color you'd like.

The SparkFun LCM's utilize an ST7066 chip as the interface to the display, which is based on the ubiquitous HD44780 interface. (If the names make this sound technical, don't worry too much about them-- the important thing here is that we have an interface that translates data from the MSP430 into the commands and characters needed to control the LCM.) This interface uses an 8-bit parallel transmission for sending data to/from the display. As you can imagine, with 8 bits for data, plus another 3 bits for control, you can very quickly run out of GIO pins on your MSP430. In fact, even if we use the G2211 device without a crystal so that P2.5 and P2.6 are available, we only have 10 GIO pins available in total, so we're short 3 pins to control the LCM (needing 11 pins) and the comparator interface (needing 2 pins) for our meter. Fortunately, the HD44780 interface (and thus the ST7066) provides a means of sending data in two 4-bit chunks, and as long as we have no need for reading data from the LCM, we can get by with 6 pins for LCM control, allowing us to just fit the comparator and the LCM into the 8 GIO pins for P1 on our G2211. We're stretching the limits of this chip at this point, which is excellent motivation for expanding to other MSP430 devices in the future!

Connecting to the LCM

The standard LCM module has 16 pin connections (14 without a backlight). The first few connections are for power (possibly in two places, if the LCD is also backlit) and contrast adjustment. Pin 1 (labeled as Vss) should be connected to your LaunchPad ground. Pin 2 (Vdd) is connected to the LaunchPad Vcc. If you are using the backlight, pin 15 (LED+) is also connected to Vcc and pin 16 (LED-) to ground. (This is most easily done on a breadboard. If you find yourself losing track of this description, a good guide to follow is one written by LadyAda.) Pin 3 (Vo) controls the contrast of the screen. If you have a 10k potentiometer available, tie it to the wiper and tie the two ends to Vcc and ground for an adjustable contrast. If not, you can just ground this pin; it probably won't look as good as it could, but it will work.

That leaves 11 pins for the control and data lines. The three control lines are pins 4 (RS), 5 (R/W), and 6 (E). The read/write (R/W) pin is not necessary here, and by tying it to ground we keep the LCM always in write mode. We won't be able to read anything from the LCM (such as the address of the cursor, the busy state flag, etc.), but it saves us a pin on the MSP430. The Register Select (RS) and Enable (E) pins are what we'll use to control the LCM. Finally, pins 7-14 are the data lines D0-D7 respectively. You can consider these pins much like the P1 pins on the MSP430-- D0 is the first bit, D1 the second, and so on. If we used an entire GIO port on an MSP430 to control the data lines, we could connect Px.n to Dn, and by writing a value to Px, we can write the same value to D (conveniently saving us from any strange coding to accommodate changing the order). Since the G2211 doesn't provide enough ports to do this, we'll use the 4-bit mode instead. This mode uses only D4-D7. Leave D0-D3 unconnected for now. (Doing so prevents accidentally writing commands we don't intend.)

For the capacitance meter, we're going to change some of the pin arrangements to accommodate the LCM. We'll use P1.1 as TA0.0 rather than CA1, and use P1.2/CA2 as the input to V+ on the comparator. P1.0 will control RS, P1.3 will control E, and P1.4-7 will control D4-7.

Note: P1.3 is also connected to the button-- this shouldn't affect the code, but since there is a pull-up resistor on P1.3, there will be excess current whenever we drive E low. Unfortunately, the LaunchPad is not designed with a jumper like on P1.0 and P1.6 for the LEDs, so we'll just have to live with this. While we're on the topic, be sure to remove the jumpers for the two LEDs and on the TXD/RXD pins.

Sending Commands to the LCM

Once we're wired up, sending commands or characters to the LCM is a straightforward task. In fact, it can even be done by hand, without a microcontroller at all! (If you're interested in this, or would like to know more about what's going on, see the Reader Exercise below.) The basic idea is that we write an instruction to the data pins and pulse E. The instruction is sent on the falling edge of E, which is why it's pulsed. The instruction issues a command if RS is low, and sends a character if RS is high.

As an example, let's look at the commands we need to set the LCM in 4-bit mode. The 8-bit binary instruction 0b001nnnxx is the "Function Set" instruction. (Here, the n's represent values we choose for the configuration, and the x's imply an unused bit-- these can have either 0's or 1's and not affect the instruction.) Bit 4 in this instruction sets the interface mode: a 1 sets the LCM to accept 8-bit instructions, and a 0 sets it to accept 4-bit instructions. So by sending the instruction 0b00100000 (or 0x20), we configure the LCM to accept commands and characters in two 4-bit chunks instead of one 8-bit chunk. This command must be issued first in order to do anything with our 6-wire setup. We first set the data lines with P1OUT |= 0x20; (which also sets RS low (command mode) and E low in this wiring scheme) and then send the command by pulsing E.

The LCM does not respond instantly to the command, and there are some strict timing requirements in order for it to work correctly. Specifically, RS must be set low a certain amount of time before beginning the pulse on E. The data lines must be set a certain amount of time before the falling edge on the pulse, and must be held at that value a certain amount of time after the pulse. Then a certain amount of time must elapse before we can pulse E again. Fortunately for us, the only timing value of major concern is the time between command pulses. The other times are on the order of a few hundred nanoseconds, and at the processing speeds of the MSP430 there is enough latency to accommodate them. The amount of time needed to complete a command before accepting another can be on the order of 150 milliseconds, however, and so delays must be incorporated to handle them.

So, to recap, here's the set of instructions needed to set the LCM in 4-bit instruction mode:

__delay_cycles(10000);   // wait for the LCM to settle on power-up
P1OUT |= 0x20;   // set to 4-bit instructions
P1OUT |= BIT3;   // E high
__delay_cycles(200);
P1OUT &= ~BIT3;  // E low
__delay_cycles(200);
P1OUT &= 0x0F;   // clear the upper 4 bits

Though E can be set high before setting the data lines, it's convenient to switch the order to prevent any timing mismatches. Note that if you use different pin connections, or especially if you use multiple GIO ports, this code won't work exactly as is; it's convenient to use P1.4-7 for D4-7 to be able to assign directly to P1OUT, but this is not general. If we were to swap the order, for example, to P1.4-7 as D7-4, then we would be writing 0b0100 instead of 0b0010 on the data line with this code. So be careful; either use the pin connections I've suggested here, or assign the data line bits individually as needed. The final line clears the data line bits to make it easier to set the next command properly.

Other Initializations: Sending Commands in 4-bit Mode

Now we have our LCM ready to accept 4-bit commands. This mode works by sending the upper 4-bits (or nibble) with a pulse on E, and then sending the lower nibble with a second pulse. With our wiring scheme, we can do this easily by the following code:

P1OUT |= ( & 0xF0);  // send upper nibble
pulse();
P1OUT &= 0x0F;   // clear
P1OUT |= (( & 0x0F;) << 4);  // send lower nibble
pulse();
P1OUT &= 0x0F;   // clear

I'm assuming here that I've lumped the commands to pulse E with the incorporated delays into a function void pulse(void).   refers, of course, to whatever 8-bit command or character we're sending to the LCM. If we encapsulate this set of commands into a function void SendByte(char),  then we can issue the next initialization commands as follows:

SendByte(0x28);   // Function Set 4-bit, 2-line mode (for 2-line displays, of course)
SendByte(0x0E);   // Display on, underline cursor on, non-blinking
SendByte(0x06);   // Character entry mode: increment address, no display shift

After sending these commands, our LCM is ready to display whatever characters/text we want to send it. Note that to send characters, the commands are similar to above, but P1OUT must also set BIT0 (RS) to tell the LCM to receive character instructions rather than commands. In lcddemoG2211.c, I demonstrate this with a more generalized version of SendByte that lets you send commands and characters. It also demonstrates other commands, such as clearing the display and moving the cursor. If you have an LCM, try out the code yourself. I wouldn't use a DCO faster than about 2 MHz with the selected delays, so if you play around with the code keep that in mind. In the next tutorial, we'll look at how to encapsulate all of this into a custom library that we can keep on hand and how to import it into our capacitance meter project.

Reader Exercise: Not really an exercise-- more suggested reading. If you'd like to know more about how the modules work and the specific commands and characters that can be sent, I suggest reading the following two articles from Everyday Practical Electronics:
        How To Use Intelligent LCDs: Part One
        How To Use Intelligent LCDs: Part Two
These articles are very easy to understand, and do a great job of explaining how to use the LCM.

09 September 2011

Return of the Blog

To all those who have been so patiently waiting: thank you for coming back. As you can see, another tutorial has been posted, and more are on their way. I've not yet finished my dissertation, but I'm making substantial progress, and in a few months I'll finally be a free man!

In the mean time, as I'm coming back to this blog, I've decided it's in desperate need of an interface overhaul. So I'm posing a question to my readers: what would you like to see in the interface? How would you like to have the tutorials presented so as to make them more accessible?

I will likely go back through the past tutorials and clean things up, clarify specifics, and generally improve the quality of information in them as well as bring back some consistency in style and presentation. What else can I do to help this community effectively?

Tutorial 13b: Interfacing the Comparator A+ and Timer A Modules

The idea behind the capacitance meter is simple, but (as may be evidenced in part by the time it took me to get to this) there are some particulars that need to be resolved.

First: how do we minimize any delay in the timing due to delays from carrying out instructions? If we're not careful, a non-negligible amount of time can pass between when we start the capacitor discharge and the timer, or between the comparator trigger and the timer capture.

Second: how do we determine what capacitances can be measured for a given configuration? Smaller capacitors will discharge more quickly, leading to shorter measurement times (meaning more error due to the digital nature of the timer). Larger capacitors take more time to charge up, and may not be fully charged when we start discharging.

The first issue is easily resolved by using features built into the Timer_A module. The second is less easily resolved, but easily understood, so we will know in advance the limitations of our code. There are a couple of things we'll be able to do to improve it generally, but for our purposes here we won't be too concerned about it.

New Feature of the Timer_A Module: Output

Let's introduce here two features in Timer_A we haven't used yet. First off, let's look at how we can use the timer to change an output. Recall that the Timer_A module has a certain number of "capture/compare" registers built into each MSP430 device. (The G2211 and G2231 have two.) Each of these registers can drive their own output; we can program the MSP430 to adjust the output every time the timer reaches the value stored in the register. For example, we can set the output TA0.1 to set the output (to 1, that is) every time the timer reaches the value set in TACCR1. Or we can toggle the output TA0.0 every time the timer reaches the value set in TACCR0. We also have modes that allow us to use both registers on the same output, giving one result at TACCR1 and another at TACCR0. (This ability is used for pulse width modulation, or PWM. We'll talk about that in an upcoming tutorial!)

Take a look at table 12-2 in you x2xx Family User's Guide:
This table lists all of the possible modes we can use to work with the timer outputs.

New Feature of the Timer_A Module: Capture

So far we have only discussed uses of the timer in compare mode. The other mode, capturing, can be used to do precise timing of events. In capture mode, the timer records the value in TAR into TACCRx at the moment when the capture is triggered. This trigger can come externally, or it can come from internal connections to other modules, including the comparator. By configuring the timer in this way, we can record the timer value when the comparator output provides either a rising edge (going from 0 to 1) or a falling edge (from 1 to 0).

Putting It All Together

Here's the general concept used in the capacitance meter. Note that accurate timing requires a calibrated clock, so we'll use the calibrated 1 MHz DCO for this project. First, we connect the resistor to a timer output. (For this purpose, we'll use the TA0.0 output.) The junction between the resistor and capacitor is tied to a comparator input, and the other end of the capacitor is connected to ground. We start charging the capacitor by setting TA0.0, and wait some specified amount of time for the capacitor to charge. The output is then reset (grounded) at the time specified in TACCR0. While the capacitor's voltage is above the reference voltage, the output is set at 1 (assuming we tied the RC circuit to V+ and the reference to V-). When it drops below that value, the comparator output falls, triggering a capture in the timer, recorded in TACCR1. The difference in time between TACCR1 and TACCR0 is an accurate measurement of the decay time of the RC circuit from Vcc to Vref. (Note that if TACCR0 is 0, no subtraction is needed.)

Obviously the longer the time it takes to fall, the more accurate our timing measurement will be overall. But what happens if the time is longer than 2^16 microseconds? TAR rolls over, and starts counting over again; so in our code, we'll need to account for any rollovers that may occur.

Let's examine the comparator configuration used in the code:

void CAinit(void) {
    CACTL1 = CARSEL + CAREF_1;  // 0.25 Vcc ref on - pin.
    CACTL2 = P2CA4 + CAF;       // Input CA1 on + pin, filter output.
    CAPD = AIN1;                // disable digital I/O on P1.1 (technically
                                // this step is redundant)
} // CAinit

This sets up the comparator to use CA1 on the V+ input. If you check the MSP430G2211 datasheet, CA1 is connected to P1.1. Looking up the register description in the Family User's Guide, we configure for CA1 on V+ by setting P2CA4. (P2CA0 also controls V+, and for CA1 should be clear.)

Now let's look at the timer configuration:
void TAinit(void) {
    TACTL = TASSEL_2 + ID_0 + MC_0;     // Use SMCLK (1 MHz Calibrated), no division,
                                        // stopped mode
    TACCTL0 = OUTMOD_1 + CCIE;          // TA0 sets VCTL at TACCR0
    TACCTL1 = CCIS_1 + SCS + CAP + CCIE;       // Use CAOUT for input, synchronize, set to 
                                        // capture mode, enable interrupt for TA1.
                                        // NOTE: Capturing mode not started.
} // TAinit

The timer is set up without starting. Setting TACCTL0 to OUTMOD_1 sets the output TA0.0 when TAR reaches TACCR0, which is 0 by default. Enabling the interrupt lets us keep track of overflows. In TACCTL1, we change to capture mode by setting CAP. To know how to connect the comparator, we need to check the device datasheet. Find the table called "TIMER_A2 SIGNAL CONNECTIONS" and make sure you're looking at the one specific to devices with COMP_A+. In the Device Input Signal column, find CAOUT (internal), and note the Module Input Name in the column next to it: CCI1B. The CCISx bits in TACCTLx select the input, and in the Family User's Guide, we see that these two bits should be set to 0b01 to select CCIxB. In the device's header file, we find that we can set these bits with CCIS_1.

Also note that by setting SCS, we synchronize the capture to the timer clock. We haven't started capturing yet, just as we haven't started the timer. The code is set up to wait for the user to push the button connected to P1.3. Doing so exits LPM0, and continues the main code. The following then happens:
First, the timer is turned on. When the timer rolls over the first time, TA0.0 (on P1.5 in this code) is set, charging the capacitor. We want to wait long enough for the capacitor to charge. The code is set to wait for 10 overflows, which corresponds to about 655 ms. At this point, the comparator is turned on, and the timer is configured to reset TA0.0 at the next overflow (so we've actually charged for 11 overflows at this point). We let the timer capture the next event, or when the voltage at the capacitor (on P1.1/CA1) drops to the value at Vref, or 1/4 Vcc. At this point, an interrupt is triggered. The interrupt routine turns off the captures and the timer and returns to the main code. The code loops back, and starts the process again, waiting for the user to press the button to start a measurement.

Note: Before running the code as set up, keep in mind we're using P1.1; what else is this pin used for? You'll want to remove the TXD jumper to get the project to work properly. Thanks to RobG over at www.43oh.com for pointing this out to me... I was really puzzled by it for an embarrassingly long time!

Try running the code found in CMeterG2211.c. To do this, you'll need a resistor and a capacitor. Use a 10 kO resistor and a 100 nF capacitor (it will have a label that says 104 on it) if you can. In the debugger, set the code to run freely, and push the button. The led should switch from green to red, then back to green, indicating the measurement is done. The timer has captured the event and recorded the time in TACCR1. Unfortunately, there's no way to see this as is yet! Pause the debugger, and examine the timer_a2 registers. The time is recorded in TACCR1. For the suggests RC combination, you should have a value somewhere around 1400. (You can change from the default hex format to decimal by right-clicking the register and selecting decimal in the format menu.)

Try increasing R to 100 kO. You should see the time increase by a factor of 10. Try using a 1 uF capacitor. (You might need to increase the number of overflows to wait while charging to get something accurate here.) In the watch window, we can view the value in the overflows variable. To do this, click where the window says , and type in the variable name. With such a large capacitor, you should see the number of times the timer wrapped around before stopping. With the measured time and the known resistor value, you should be able to use the formula provided in the previous tutorial to calculate the value of the capacitor. Feel free to experiment with this program. In particular, how consistent are your timing measurements?

Aside from the lack of ability to see the timer value without using the debugger, there are a few issues to work out still in this meter. We'll take a careful look at some of these in the future, and bring back this code to demonstrate ways we can see data and ways we can improve the timer.

Reader Exercise: Given the discussion in the previous tutorial about the accuracy of the meter, and from your own experimentation with the program, where are the major sources of error in the measurement? How consistent is the timing? What might cause the inconsistency? What assumptions have we made in the way we measure the capacitance? Once you've built an instrument to make any kind of scientific measurement, it's important to identify all of these aspects. By doing so, we identify the limitations of the instrument, both those we can fix and those we have to live with.