29 September 2012

Tutorial 20a: Introducing I2C

The SPI protocol is a simple and useful system, but is not without its disadvantages. In the example we looked at, we noted that at any given time, despite the ability to exchange messages simultaneously, only the master or the slave was sending any meaningful data. The system is capable of linking multiple devices together, but the technique is much like an old switchboard operator: each devices gets its own unique and private line, and the master selects which device it is talking to at any given moment. In the mean time, lines not being used are taking up space and resources that could be allocated to other tasks. This technique is not the only way to communicate, however. What if instead of a switchboard model, we looked more to radio communication: if you tune in to a specific frequency, anything transmitted can be heard by all, and (at least at some frequencies) all can transmit at any time. This type of system is far more conducive to linking multiple devices together as it greatly simplifies the connections, both physically and conceptually.

In electrical systems, we call any line that links multiple parts together a "bus". In the sense of serial communication, a bus is a line on which devices can watch for signals, or generate signals of their own. A bus-type system reduces the number of connections needed between components and links multiple systems together in potentially complex ways. One of the most popular implementations of a true serial communications bus was developed in the 1980's by Philips Semiconductors: the Inter-integrated Circuit Bus, or I2C.

Problems With a Serial Bus

As you might expect if you've ever heard radio interference, some significant issues come up when rather than each device getting its own, private communication line they have to share a line. Much like a crowded household of entitled teenagers (at least before cell phones), a crowded bus in an electrical system needs to lay down rules for who can talk and when.

Problem 1: Since multiple devices control the same line, what happens when one device actively pulls the line low, while another actively pulls the line high? This creates a short between the low and high states, likely causing irreparable damage to the system. To get around this, the I2C specification requires devices to only actively pull a line low. The line is tied with a resistor to Vcc, so if no device is active it defaults to a high state. (This reason is similar to the need for the resistor(s) in the SPI example.) In terms of the MSP430 GPIO, think of it as setting the output of a pin to 0, then toggling whether the pin is an output (pulling the line low) or an input (allowing the line to be pulled high). In fact, if you ever find yourself required to bit-bang I2C, this is exactly the technique you'll have to use to prevent any damage to the systems involved.

Problem 2: As a result of the use of resistors to pull the line state high, we are limited on the speed at which we can communicate with I2C. Any capacitance in the line, combined with the resistor, will lengthen the amount of rise time in the line.  Too much resistance, and the line doesn't pull high soon enough to get the right message sent. Too little resistance, and you draw far too much power through the resistor when the line is pulled low. The standard specification for I2C limits transmission speeds to a 100 kHz clock. For the 3 V power used on many MSP430 designs, a resistance between 1 and 10 kΩ is typical; if you're concerned about speed, aim for the 1 kΩ end. Other specifications allow for clock speeds of up to 400 kHz (fast mode), or 1 MHz (fast mode plus). These modes will require smaller resistors, and inherently use more power than standard mode.

Problem 3: Since all devices are listening in on the same line, if the master asks for a data value to be reported, which device responds? I2C assigns a call sign, of sorts, to each device in the form of a 7-bit address. (An 8th bit is added to specify if the master wants to read from or write to the device.) This address is usually hard-coded into the device, and reading its datasheet will give the information needed to address it correctly. Some devices hard code some of the bits, allowing the user to select the specific address by setting the other bits accordingly. This technique allows the use of more than one of the same device in a system.

Problem 4: In addition to knowing who needs to respond, devices (including the master) need to know when they can send signals; if the line is tied up by another device, other devices must hold on their own messages until the line is signaled as being free. This coordination is effected in I2C by the timing of changes in the data line compared to the clock line. Communication in I2C is initiated by a falling edge in the data line, and marked complete by a rising edge in the data line, much like the use of the chip select in the SPI example we did. Since this is the same line where data is transmitted, I2C specifies that a "start condition" occurs when the data line is pulled low while the clock is high. A "stop condition" occurs when the line is pulled high while the clock is high. Data transmission occurs between these two conditions.

Data is sent after signaling a start condition by changing the line state while the clock is low, and the listening device reading the state while the clock is high. (Note that this is essentially equivalent to Mode 3 for SPI.) It is essential that devices sending messages do not change the state of the data line while the clock is high unless marking a start or stop condition. Other devices need to be aware of start and stop conditions to avoid sending messages of their own at the same time. If a device sees a start condition, it will listen for the address. If not its own, it must wait until the line is freed up by a stop condition before sending its message.

I2C in Action

If after reading all of that you feel like I2C is really complicated, it's not. Well, it's certainly more complicated than SPI, but once you see how the protocol works it's not too difficult to understand. So let's look at a typical I2C transmission and analyze what's going on.


Look at this image of the first part of an I2C transmission-- this portion highlights the start condition and the addressing portions. Note that the state of the clock (bottom curve) is idling high. The clock does not start until after the master pulls SDA low. The start condition is signaled by the falling edge on SDA while SCL is high. The start signal is followed by 9 pulses of the clock on SCL. Remember: at this point, neither the master nor the slave changes the state of SDA while the clock is high. Notice that the changes in SDA sending the data occur between pulses-- you can read out the transmitted value at the points where the clock is high. In this example, the data reads 0b01000001. The first 7 bits of this value are the address of the slave (in this case, 0b0100000). These bits are followed by a final 1, which designates a read command. The following data will be sent by the slave, reporting the data it has ready to send.

Did you note that there were 9 pulses, but only 8 bits? The 9th clock is done for some basic handshaking, and is called the "acknowledge" bit. In this case, the master addresses the slave at the specified address and releases the line after sending the 8 bits. If the slave recognizes the call, it pulls the line low; the master reads the 9th bit to confirm that the slave has heard the instruction. What happens if the slave doesn't hear, or fails to acknowledge the signal? Since the line is tied high and the master has relinquished control, the line automatically pulls high. If the master reads the 9th bit and sees it high, it aborts the transmission. (Whether it tries again or not depends on how the master is built, of course.)

At this point (assuming the slave acknowledged the instruction), it is important that the master not signal a stop condition (by sending a rising edge on SDA while the clock is high) to give the slave the time to report back the data it was asked to read. The remainder of this example looks like this:
How we interpret the remainder of the instruction depends on the exact device being read. For simplicity, let's assume that we're dealing with a device that has a single, 2-byte register. No further addressing is necessary, so when the slave receives the instruction to read, it reports back the 16 bit value it has. Data is transmitted one byte at a time, with an acknowledge bit between bytes. In this example, we see the slave reporting back the two byte value corresponding to the ASCII characters "%%". After the first byte, the slave relinquishes SDA and watches for the master to acknowledge receiving the data (again, by holding SDA low). After the final byte, notice that the acknowledge bit is now high. On the last cycle, the master does not send an acknowledge bit, indicating that no more data is expected.

Finally, the master pulls SDA low again, then releases the clock so that SCL is high. The master then releases SDA to give a stop condition.  At this point, any other devices needing to start a transmission are free to do so; if between the start and stop any other device has a message to send, it must wait until it sees the stop condition before doing so.

Now that we've got a handle on some basic I2C formatting, we'll turn our attention to the USI module and how it's used in I2C in the next part of this tutorial.

Reader Exercise: Using the second image, identify which bits (including acknowledge bits) in the data stream on SDA are sent by the master, and which are sent by the slave, according to the description given in this tutorial. What is the slave doing while the master is sending data? What is the master doing while the slave is sending data? Who has control of SDA at what times?

21 September 2012

Tutorial 19c: The 25xx080

Now that we have a handle on configuring the USI module to communicate using the SPI protocol, we can implement it in a real situation. Today we'll be using a Microchip Serial EEPROM (I'm using specifically the 25AA080C, though in principle this should work with any Microchip SPI EEPROM).  Looking at the datasheet for this chip, there are a few things to understand.

Instructions and the Status Register

This chip has 6, 8-bit instructions.  In this design, the Chip Select pin is actually used to mark the end of an instruction, and so is a necessary signal that should be enabled (set to 0) before and disabled (set to 1) after each of the following:

  • READ (0x03): Sending these 8 bits followed by the 16-bit address of the location in memory you want to read instructs the EEPROM to send the 8-bit value at the specified address on the next 8 clock cycles.  The whole instruction takes 32 clock cycles (8 for the command, 16 for the address, and 8 for the read-back).
  • WRITE (0x02): This command can be used in two different ways. First, after sending the command, a 16-bit address is sent followed by the 8-bit value to write. Second, rather than write single bytes at a time, the chip can write a group of bytes (called a page) at once. The 25AA080C has a page size of 16, so up to 16 bytes can be written in one instruction.  This mode uses the command bits, followed by the initial address (each byte is written in the subsequent address of the last), and then the values for each byte to write.  Note: writing does not occur until the chip select has been disabled (set).  In addition, the chip needs a small amount of time (about 5 ms, according to the datasheet) to perform the writing. Any subsequent write commands must be sent after the settling time to prevent interruption. We'll examine this point a little more later. This instruction takes 24 + 8n clock cycles, where n is the number of bytes being written (max of 16 on this chip).
  • WRDI (0x04): This simple, 8-bit only instruction disables writing to the EEPROM. Data can still be read, but write instructions will have no effect. This instruction takes only 8 clock cycles.
  • WREN (0x06): The opposite of WRDI, sending these 8 bits enables writing to the EEPROM. When a write cycle completes, the write-enable latch is reset, so this instruction must be issued before every write instruction. This instruction also only takes 8 clock cycles.
  • RDSR (0x05): The EEPROM also includes a Status Register that indicates the configuration of the chip. The 8-bit value can be read by issuing this command followed by 8 clock cycles to read the value back. This instruction takes 16 clock cycles.
  • WRSR (0x01): The Status Register can be written directly under certain circumstances. When those conditions are met, a write is done by issuing a WREN instruction, followed by this command and the 8 bits to write to the Status Register. This instruction takes 16 clock cycles, but like the WRITE instruction must be preceded by a WREN.
The Status Register uses 5 of the 8 bits in this EEPROM chip:
  • WIP (Bit 0): This bit is a flag that is set when the chip is in the middle of writing to the flash. Write instructions should not be issued until this is clear, which should take no more than 5 ms.
  • WEL (Bit 1): This bit flags when writing is enabled on the chip. A WREN command will set this bit, while a WRDI will clear it. Writing to the flash only occurs if this bit is set. Writing to the Status Register may be possible while set, depending on the chip's configuration. (See WPEN below.)
  • BP0 and BP1 (Bits 2-3): These bits enable write protection for individual blocks in the EEPROM. The 25AA080C is built with two blocks, corresponding to the upper half and lower half of the flash memory respectively. Setting both BP0 and BP1 will protect the entire chip from being over-written. These bits are set through WRSR instructions.
  • WPEN (Bit 7): This bit determines whether the Write Protect pin affects the writeability of the Status Register. If this bit is clear, the Status Register can be written to regardless of the state of WP (as long as WREN has been done, of course). If this bit is set, then the Status Register can be written to if WP is held high, but is protected if this bit is held low.
All of these instructions and register definitions can be encapsulated in a C header file. As an example, look at 25xx080c.h. This file was written with this single device specifically in mind, but can be expanded to generalize to any SPI EEPROM from Microchip. I will be using this header file in all of the example code below, in addition to the calibrations.h header file. If you run these code examples, be sure to include the two header files. If they are linked to, be sure to adjust the CCS project properties to search for the directory they reside in for both the compiler and the linker, and set the debugger to clear only the main memory so the DCO calibration doesn't get overwritten.  (If that happens, go back to the flash memory programming tutorial and re-calibrate your MSP430.)

MSP430 Issues

As you get more involved with MSP430 design, you'll want to become aware of problems in the hardware itself. Every device on TI's website has a link to a "Device Errata", that details known problems with the hardware. The MSP430G2231 Device Errata lists a known problem labeled as "USI5", which applies to using the SPI protocol. For some reason, this device will send an extra clock cycle the first time it is used; so instead of sending 8 clock cycles after writing 8 to USICNT, it will send 9. There are two ways to get around this: the errata suggests writing one less to USICNT the first time, so writing 7 instead of 8. I think that makes for messy code, since the first transmission has to be treated differently, so instead I clear the bug in initializing USI. Before enabling the SDO and SDI pins on the MSP430, but after starting the USI, I send a command to transmit a single bit. Two pulses are actually sent, due to the bug, but since P1.6 and P1.7 haven't been enabled in USI yet, it has no effect on any devices attached to the MSP430. Once the two pulses have cleared, the pins are enabled, and the MSP430 is free to use the module as expected. The code I used to do this looks like this:

void USI_init(void) {
    USICTL0 = USIPE5 + USIMST + USIOE + USISWRST;
        // Enable SCLK, Master mode, enable output and reset USI
    USICTL1 = USICKPH + USIIE; // Mode 0 requires CKPH=1, enable interrupt
    USICKCTL = USIDIV_3 + USISSEL_2;    // SMCLK div 8 -> 921.6 kHz USI clock
 // One write command should take ~50 us at this rate,
 // while 1 bit via UART @ 9600 should take ~100 us.

    USICTL0 &= ~USISWRST;        // Clear USI for use

    USICNT = 1;  // clear 1st transmit due to errata USI5
    __delay_cycles(50);          // finish clearing (minimum (n+1)*16 cycles)
    USICTL0 |= USIPE7 + USIPE6;  // Enable SDI/SDO pins.
    USICTL1 &= ~USIIFG;
} // USI_init

Another technique you will see used in these examples was used in the UART tutorials: a custom flag is used to indicate when SPI transmission is occuring. This flag is polled to hold the program until the transmission has completed, ensuring that the USISR is not changed until all bits have been transmitted.  This flag is cleared in the interrupt routine for the USI.  The chip select is done manually in each example below.  See the Reader Exercise at the end of the tutorial for an idea on a better way to handle the chip select.

Example Code

Writing, Method 1

First up, eepromwrite_spiG2231.c demonstrates writing to the EEPROM device. The code uses P1.4 as the chip select signal, and that pin should be connected to pin 1 of the EEPROM. Be sure to connect P1.5/SCLK to SCK (pin 6), P1.6/SDO to SI (pin 5), and P1.7/SDI to SO (pin 2). Recall that the SCLK, SDO, and SDI functions are enabled in the MSP430 in the USI registers, not in P1SEL. It might not hurt to remove the jumper to the LED on P1.6 on the LaunchPad.  In addition, though the code may work without it, it's a good idea to tie the SDI-SO line (pin 2) to Vcc. The MSP430 does not automatically set this line when idling, as one would expect, so a simple resistor (say ~10k) will do the trick.  Finally, be sure to tie HOLD (pin 7) to Vcc as well.

RealTerm lets you send data from a text file, and
add the necessary 5 ms delay between characters.
Once running, this code will write the first 1024 bytes received by UART (at 9600 baud) to the EEPROM. Once that has completed, it lights the LED on P1.0 and goes into a low power mode, signaling that the write process is done. Now, if you think about it, there's a problem with this code. At 9600 baud, each byte takes just over 1 ms to transmit. While that's more than enough time to send the write command to the EEPROM at the USI clock rate being used, it's not enough time for the write to settle; there should be roughly 5 ms between write commands. If you are transmitting each character by hand, you'll probably be ok. If you're like me and really don't want to press keys 1024 times just to test this code, you'll want to write a 1024 character text file, and transmit that directly. For that to work, you need to have some delay between characters in the transmission. I used the Windows program RealTerm, which in addition to having a feature to transmit from a file has a feature to introduce a manual delay between characters. With that configuration, I was able to transmit the file mspsci.txt and have it write successfully to the EEPROM.

Reading

To get this file to display nicely, you need to enable the
newLine mode in RealTerm. Displaying an extra line or
two also helps.
Second, eepromread_spiG2231.c will read back the contents of the EEPROM and send them via UART (at 9600 baud) for display. If you run this code before any writing, it will display whatever the contents of your chip are prior to doing either of the write programs. If your chip is new, it will likely be very boring, consisting of the value 0xFF in every address.  If you run either of the write methods, running this program should result in a display much like what is shown here.

If you're using my text file and RealTerm, note that I've enabled newLine mode; the character being transmitted by default only initiates a line feed, without a carriage return. This mode adds the carriage return, so that it displays properly. If you lose a line of the display, increase the number of rows as well.

Writing, Method 2

Having to wait 5 ms between characters is a pain; we've effectively reduced our transmission rate to a crawling 200 baud. Fortunately, being able to write up to a single page at once saves us, since even after writing 16 bytes the settling time is still only 5 ms! At 9600 baud, each character takes just over 1 ms to transmit, so as long as we write more than 5 characters at a time, the amount of time it takes to transmit and store those characters is longer than the settling time needed between write commands. The disadvantage, of course, is that we need to employ a buffer to hold all of those characters in memory in the MSP430 while we wait. The MSP430 devices should have sufficient RAM to do this, however, so it's not much of a sacrifice. (But it is something of which we need to be aware in more complicated programs that write to EEPROM!) 

In eepromwrite2_spiG2231.c, I implement the same technique as before, but by writing a full page of 16 bytes at once. Received values are stored in the buffer[] array, and then transmitted to the EEPROM to be written. The amount of time it takes to send the complete write command is less than the time it takes to receive the next character, so the code returns to the for loop waiting for the next 16 characters before the next character is received. If we operate SPI at a slower rate such that this condition isn't met, we can run into a race condition. 

SPI Signal Details

Let's take a look at some of the details of the signals being passed back and forth in these programs.
These two images show signals from the first program, eepromwrite_spiG2231.c. The SPI lines are labeled from the perspective of the EEPROM, the UART from the MSP430. Notice in the first panel that the SPI lines only operate every 5 ms, between received characters.  There's a lot of wasted time in this method. The second panel shows the important signal lines in detail. Note that there are two instructions being used, since CS shows two pulses. The SCLK is configured correctly for the chosen mode, idling low and reading on the rising edge of the clock. In a write command, the EEPROM is sending nothing back, so SDO is high throughout the instructions. The EEPROM sees the instruction 0x06 (WREN) followed by 0x02 (WRITE). Then the 16-bit address 0x06 is received followed by the value 0x2A to write to that address. (0x2A corresponds to the asterisk symbol.)

For the program eepromread_spiG2231.c, the UART signals now follow the SPI instructions (as makes sense; the UART is transmitting the values read). There is much less dead time in this program, since no settling is required between reads as there was between writes. Zooming in on the bottom panel, we see a single instruction. 0x03 (READ) is followed by an address, 0x08 in this case, then 8 dummy bits. At the same time, the SDO line idles until the last 8 bits, where it reports the value 0x2A as the value stored at address 0x08 in the EEPROM. After a short delay (due to steps taken in the MSP430), the next UART transmission is begun.

One thing to note in this chart; the SDI line is not idling at high all the time. This is due to the same reason we wanted to put a resistor on the SDO line to tie it to Vcc; likely it's a good idea to do this to both lines. By leaving it off, I was able to demonstrate that the process still works fine; it's only convention that requires us to have a specified idle state.

Finally, we have three panels to illustrate the eepromwrite2_spiG2231.c program. The first and third are analogous to those shown previously, giving a view of the overall signals being sent and a zoomed in picture of the SPI signals themselves. Notice there is almost no dead time in the UART signals received. The middle panel shows that even though we now have to send 16 bytes of data to write, the total length of the write instruction on SPI is less than the time to receive a single byte via UART. If this were not the case, and a UART transmission were to complete first, it could mess up the transmission by changing the values in the buffer array. Fortunately, SPI can operate very quickly compared to this transmission rate, even faster than is implemented in this code.

This post completes the tutorial on SPI (for now, anyway!), and next time we'll switch gears and learn to use USI with the I2C protocol.

Reader Exercise: There's a lot of commands that are retyped in each of these examples... wouldn't it be nice if instead of manually writing each instruction you could call a function that handles it for you? Write a C function that handles write instructions and read instructions, passing the address of interest, and the value to write (in the write instruction case) as parameters. A general write function for multiple bytes may be tricky to do; can you write one that handles both single-byte and multiple-byte cases?

08 September 2012

Tutorial 19b: USI SPI

Previously, I hinted at the variety of configurations possible for SPI communication. The MSP430's USI peripheral is very flexible for all of these configurations, so which we use will primarily be determined by the devices we connect to it. That being said, it's important to know how to decide which configuration we need to use.

SPI Modes

There are four primary modes for SPI, depending on the signal's polarity (whether it idles high or low) and its phase (do we read when the clock is low and write when the clock is high, or vice-versa). Common notation for these two values are CPOL and CPHA, respectively. TI, however, uses the values CKPL and CKPH, with CKPH being inverted from the standard definitions for CPHA. (That is, if CPHA = 0, CKPH = 1 and if CPHA = 1, CKPH = 0.)

When CPOL/CKPL = 0, the line idles low. An example of the timing of a mode using low polarity and using clock high to read is shown here. (These example diagrams come from John Davies' excellent book MSP430 Microcontroller Basics.)  Note that we determine the phase by looking at the edge that appears in the middle of a bit. In this example, we see a rising edge in the middle, followed by a falling edge between bits. Whichever edge occurs in the middle of the bit is a read, and the edge between bits is a write, and the order these occur (not which direction the edge is!) determines the phase. This tells us we want to use CPHA = 0 (or CKPH = 1 for the MSP430) which reads first, then writes.  This mode is often referred to as either Mode 0,0 or Mode 0.
Mode 0 Timing Diagram
From [Davies, 2008].
Here's another example using CPOL/CKPL = 1, with the line idling high. In this example, the rising edge is still in the middle of the bit, and the falling edge is between, but the write is first and the read second.  For this setup we would use CPHA = 1 (or CKPH = 0 for the MSP430). This mode is called Mode 1,1 or Mode 3 (as in 0b11 = 3).
Mode 3 Timing Diagram
From [Davies, 2008].
Now let's look at a real-world example. The Microchip 25AA080C chip is an SPI EEPROM with 1 kB (1024 bytes) of memory. In its datasheet, we see this timing diagram:
The diagram specifies Mode 0,0 (alternatively Mode 1,1), but we can verify that ourselves because (1) the line idles low, and (2) the read occurs before the write. For this device, we want to use CKPL = 0 and CKPH = 1 for the MSP430. Note also that the order of the transmission is specified as MSB first.

Configuring the USI

The USI uses 6 registers in the MSP430. One new thing about these registers that we haven't seen before is that, since each register is only one byte in size, we can also access them as 3 2-byte registers: the USI Control Register (USICTL), the USI Clock and Counter Control Register (USICCTL), and the USI Shift Register (USISR). (Alternatively, you can manipulate each register individually. There are convenient times to use both methods.)

USICTL

The control register is comprised of two parts: USICTL0 and USICTL1.  The pertinent bits are described here.

USICTL0 (lower byte)

  • USIPEx (bits 7-5): these bits enable the USI functions on the MSP430 pins. (The MSP430G2211 and G2231 use pins P1.5-7 for USI functions.) These pins are already connected to other peripherals with the P1SEL register, so they are configured for USI through its own register, each pin individually.
  • USILSB (bit 4): when set, data is transmitted least significant bit first rather than the default most significant bit first.
  • USIMST (bit 3): when set, the MSP430 will act in the master role, and SCLK is connected to the USI clock as an output. When cleared (the default configuration), it's in slave mode, and SCLK is an input.
  • USIOE (bit 1): when set, output is enabled. This function is equivalent to the chip select in other devices; since the MSP430 doesn't have an explicit pin configuration for chip select, it has to be done in software if its use is needed.
  • USISWRST (bit 0): software reset for the USI; when set, operation is held to allow configuration. This bit must be cleared to start the USI.
USICTL1 (upper byte)

  • USICKPH (bit 7): Sets the clock phase; inverted from the standard CPHA. When set, allows modes 0 and 2. When cleared, allows modes 1 and 3.
  • USII2C (bit 6): Clear this bit to use the SPI protocol.
  • USIIE (bit 4): enable interrupts for the USI counter; flags an interrupt when the specified number of bits have been transmitted.
  • USIIFG (bit 0): interrupt flag for USIIE. This flag can either be cleared automatically or manually, though as we'll see later manual clearing is usually desireable.

USICCTL


The two parts of this register are USICKCTL and USICNT, for the clock and the counter.

USICKCTL (lower byte)

  • USIDIVx (bits 7-5): Divide clock by powers of two up to 128.
  • USISSELx (bits 4-2): Source select for the clock. USI has a wide variety of clock possibilities, including the Timer_A capture/compare registers. The variety allows for a lot of fine tuning for the exact transmission speed needed. (These bits are not used if the USI is used in slave mode.)
  • USICKPL (bit 1): determines the clock polarity (set -> idle high, clear -> idle low).
  • USISWCLK (bit 0): One option for the clock is to do everything in software. In this case, toggling this bit serves as the clock.
USICNT (upper byte)

  • USI16B (bit 6): When set, USI will transmit up to 16 bits . When clear, USI will transmit up to 8 bits.
  • USIIFGCC (bit 5): When set, the interrupt flag must be cleared manually.
  • USICNTx (bits 4-0): Writing a value to these bits starts transmission, which continues until the number of bits specified is reached (eg. to transmit 6 bits, write 0b00110 to these bits).

USISR


The two byte-sized registers here are USISRL (the lower byte) and USISRH (the upper, or high byte). USISRH is ignored if the USI is configured in 8 bit mode (ie. USI16B is cleared in USICNT).

For the 25AA080C, we'll configure the MSP430 to be in master mode by setting USIMST, and select an appropriate clock speed for transmission. (At 3.3V, the 25AA080C works up to 5 MHz.) Using Mode 0, we'll clear USICKPL and set USICKPH. The commands (which we'll examine in the next tutorial) are 8 bits in length with MSB first, so we'll use the 8-bit shift register mode by clearing USI16B and use MSB first by clearing USILSB. Since we'll need to connect the two data lines and the clock to the EEPROM, we need to be sure to set all of the USIPEx bits. While not essential, we'll also use one extra P1 output to control the chip select for the EEPROM. Got all that? Great. Next time we'll actually do it!

If you're following along exactly, be sure you get an SPI EEPROM device before doing the next post. These are quite inexpensive, and available directly from Microchip. If you use a size other than the 8 kbit one I'm using, most everything will be the same.

07 September 2012

Tutorial 19a: SPI Theory

When we looked at the UART, we imagined a setup where two people agreed that at a specific time and at specific intervals, one would send a message to the other one letter at a time. Doing so required both sender and receiver to have an accurate clock to prevent frame errors, or mis-reading the message by skipping or duplicating one of the letters. Using a similar analogy, we can think of the Serial Peripheral Interface as having the two people write a message to each other on a piece of paper, then exchange messages by handing them to each other at the same time. As a serial communication, it's still done letter by letter, though there are variations of SPI that allow for exchanging multiple bits simultaneously. We'll focus on single-bit-at-a-time transmission, since that is the only mode available in the USI and USCI peripherals.
There are 3 basic steps in SPI:
(1) Write bit 7 to the output.
(2) Shift register to the left.
(3) Write the other device's output to bit 0.

Let's say our two devices have 8-bit registers. At a given signal, each writes their most significant bit (bit 7) to their output. At the next signal, each shifts their register up one place, and sets the least significant bit (bit 0) to whatever value is on the other device's output. After 8 cycles, the 8 bit value that was in device A's register is now in device B, while the value that was in device B is now in A. Both read the new value (and probably do something with it), and then perhaps write a new message in their registers for the next exchange. This exchange of information makes it possible to very quickly send data from one device to another.

The key to getting the process to work properly is to have all the shifting occur at the same time--the two devices need to be synchronized. This timing is accomplished by sharing a clock between the two devices; one of the two generates its own clock and includes it as an output for the other device's use. By convention, we refer to the device that generates the clock signal as the "master", and any devices listening in as "slaves". Such nomenclature may seem a little non-politically correct, but at the same time it's a reasonable description of how SPI works. We cannot necessarily deem one device as a "sender" and the other as a "receiver", for example, because both devices are simultaneously sending and receiving. Referring to both as "transceivers" doesn't really work either, because the sending and receiving are in fact the same process. Rather, the devices are "exchangers". One device serves as a control of the exchange, while the other depends on the controller in order to make the exchange. Note that, contrary to the connotation of the nomenclature, the master does not necessarily have to be the device that issues commands, nor does a slave have to only receive instructions. In fact, one could envision a system where the clock is external to both master and slave, and neither device operates entirely independently of the other, but rather a third device mediates the exchange between the two by providing the clock synchronization. Generally, however, it's simpler to let one of the exchanging devices mediate, and that device become designated as the master.

You can imagine that the technique used for the SPI protocol lends itself to many variations. (Eg. do we pass the data starting from most to least significant bit or vice-versa? How many bits do we pass at a time?) Do we start the exchange on a rising edge or a falling edge of the clock? (The edge choice also leads to whether a quiet line idles high or low, of course.) To make it more confusing, for whatever reason various manufacturers have created different naming schemes for the lines between the two devices. In particular for our purposes, TI has the three lines between the devices named as Serial Data In (SDI), Serial Data Out (SDO), and Serial Clock (SCLK). Like for UART, the data in line of one device is connected to the data out line of the other: SDI_A-SDO_B and SDO_A-SDI_B for devices A and B. Note that because we must include the clock, SPI requires three lines (plus one more for ground) between the devices as opposed to two lines (plus ground) in the basic UART. (There are some situations where if one of the devices doesn't need to communicate anything to the other ever you can get away with just two lines, but in general you need three.)

The other common nomenclature for SPI connections was given by Motorola: each device has a Master Out-Slave In (MOSI), and a Master In-Slave Out (MISO) rather than SDI and SDO.  In this nomenclature, you connect like pins rather than opposite pins: MOSI_A-MOSI_B and MISO_A-MISO_B. Other devices use a similar nomenclature to TI, dropping the "D" in the abbreviations: SI and SO, connecting as in the TI scheme. You may also encounter SPSCK and SCK for the clock, and devices enabled with a chip select can be labeled as CS, SS (slave select), or sometimes CE (chip enable). Be certain to verify whether tying this pin high or low enables the device. In this blog, I'll stick with TI's nomenclature, and use SDI, SDO, SCLK, and CE.

SPI can also extend to communication with multiple devices by including a "Chip Select" pin-- a slave will only listen when this pin is high or low, depending on the implementation. Thus other peripherals can be attached, and instructions/data can be exchanged only between the master and the pertinent slave. The disadvantage to this means of multiple-party communication is that it requires one more line for each device that needs to communicate independently.

So how do we know what conventions we should use in our designs? Unfortunately, you need to get familiar with reading data sheets, and my experience has been it takes some practice to read data sheets describing exact communication protocols. In the next tutorial, we'll look at how to implement SPI using the USI peripheral, and delve more into the details of how to determine the particular protocol being used and configure the MSP430 properly.

05 September 2012

Tutorial 19: Going Beyond the UART

We've already looked at asynchronous serial communication, and seen how useful it can be for a scientific instrument as a data logging system. Serial communication has a lot more power, however, especially when we begin looking at the "control" aspect of the microcontroller.

There are a lot of sensors and devices designed to work with microcontrollers that use synchronous communication protocols. The primary difference for these modes of communication are the inclusion of a single clock between the sender and receiver, rather than having to rely on precise and accurate clocks. Having to share a clock limits the separation to a fairly close proximity, but it does simplify the communication process a great deal.

The number of protocols designed for serial communication is quite large, but a few have stood out as standard for many devices. The MSP430 has many devices that, for example, have built-in hardware for communication using the Serial Peripheral Interface (SPI) and the Inter-integrated Circuit Bus (I2C or I2C -- pronounced either as eye-two-see or eye-squared-see, your preference).

Most MSP430 devices have one of two forms of serial communication hardware. The less expensive devices have the Universal Serial Interface (USI), which can do SPI and I2C. Larger devices come with the Universal Serial Communication Interface (USCI), in at least one of two flavors: USCI_A handles asynchronous communication (UART), and USCI_B handles synchronous communication (SPI/I2C). If for any reason you must use a device without either of these modules, you can resort to bit-banging, but aside from the previous tutorial on UART we won't cover that any time soon; most modules have at least USI, and it's far more economical to use the built in hardware.

To work with this tutorial, you'll need at least one of the following:

  • Two devices that communicate via SPI and I2C, such as a serial EEPROM produced by Microchip
  • USB-SPI/I2C interfaces, such as the FTDI devices. (Their chips include one that is great for UART at speeds other than 9600 bps too!)
  • A second MSP430 device.
Owners of a LaunchPad already have two devices that include USI, but keep in mind you'll need a few other components to power the chip off of the LaunchPad. I'll do tutorials that will demonstrate all three methods, but for the beginning I will be working with Microchip serial EEPROM chips. (I will use the 25AA080C for SPI and the 24AA08 for I2C, but any size will do.)

Of the two synchronous protocols used by the MSP430, I2C will likely be the one used most frequently (at least by me), for the reason that the protocol is designed to work with multiple devices on a single communication line. Many sensors and external peripherals are already available that use I2C. However, SPI is a little simpler to understand, and we'll start with that. Once I've gone over the USI peripheral, I'll begin working on a new experiment that will make use of a pressure sensor, and design an MSP430-driven 4-digit LED display. Both will communicate over I2C as a digital pressure gauge. The project will require designing and fabricating a couple of printed circuit boards, so we'll go over a little of that process as well.

New Tutorials are Coming!

Hi everyone; it's great to be back. It's been a crazy few months, what with finishing my Ph.D. and all the other changes in my life. But, it's high time I start learning some new things and building some cool toys. I have a lot in mind for the coming weeks, and hopefully you'll find some of it helpful as well.

These tutorials will be a little different; call them "intermediate-level tutorials" if you will. Mostly, these tutorials will require the use of more parts and tools outside of the LaunchPad, much like the LCM tutorial from before. I'll try to keep the tools I use within a reasonable budget for beginners and amateurs, but some of the parts will probably cost a little more. (I just purchased a sensor for the next project that was $35.) If you have any suggestions or requests for topics, let me know!

Thanks, all of you who read this blog; I have a lot of fun writing this, and I'm glad so many of you have expressed your appreciation for its contribution to the MSP430 community. Let's see what more we can learn!

18 August 2012

Experiment: Battery Profiling Update

I want to get the final results of the Battery Profiling experiment put up for everyone to see, as it came up with an interesting result.

150 Ω Circuit

Average of two runs using matched resistors.
The immediate conclusion is that Duracell does in fact last longer than Energizer. But stopping there doesn't really tell the whole story; yes, the Duracells did maintain a voltage for about 10 hours more time, but look more carefully at the initial period-- the Energizers actually perform better for the first half.  In fact, the Energizers stayed consistently at a higher voltage until around 120 hours, where both batteries were found to be at 1.05 V.  At that point the Energizer drops off quickly, while the Duracell holds on for a little longer. Big deal you say? Well, that depends on how you're using the batteries.

Consider a flashlight as a case example. The higher the voltage, the brighter the light. So the Energizer powered flashlight will stay brighter than the Duracell powered flashlight for a significantly longer time. The Duracell powered light may last longer overall, but how useful is that last 10 hours, really?

This behavior is consistent even at higher power draws:

33 Ω Circuit

Average of two runs using matched resistors.
The same result is found for the higher current case, with the cross again occurring at 1.05 V and the Duracell lasting about 10 hours longer.  This result suggests that the Energizer design optimizes maintaining the higher voltage at the expense of overall lifetime.  Integrating the actual current of each circuit over time gives an average energy capacity of 1380 mAh for Duracell and 1340 mAh for Energizer-- roughly the same!  If the Energizer maintains a higher current for a longer period of time, it would make sense for it to finish draining first as it uses more of its capacity during that initial time.

What we conclude from this is that the brand you choose may depend just on your needs-- specifically on the minimum voltage required in your circuit. If you need the voltage to stay above 1 V to power your application, Energizer will give you that power for a longer time.  If you only need the voltage to be above a threshold below 1 V, go with the Duracell.

What Next?

One reason I'm including these little experiments is as a catalyst for others to start investigating. This simple idea could lead, for example, to an excellent science fair project for a young student. Or perhaps someone is curious enough to justify buying lots of batteries to run through their paces. In any case, here are a few ideas of other questions that could be examined.

  • This experiment used a constant resistance circuit-- how do the lifetimes compare in a constant current application?
  • Is the behavior seen here consistent for other sizes of battery? (Be aware that discharging a D-cell through even 33 Ω may take a while...)
  • Do batteries discharge evenly? What happens if two otherwise identical batteries are placed in series? Measure the voltage at both batteries-- ideally the center voltage should be half of the overall voltage at all times. Is it? Is there any difference if you mix brands together?
  • My measurement of the energy capacity of the two brands shows them as being similar, but the Energizer capacity was lower than the Duracell in both cases. Two measurements is not enough for the difference to be statistically significant-- measuring a larger number of batteries could tell you if Duracell does indeed have just a little more capacity. How many batteries would you need to measure to show that?
  • In this experiment, the circuit was constantly on. What happens if the current is only on intermittently? How much does a battery recover after being used for a while?
  • Both runs were done at room temperature. How much of an affect does temperature have on the battery? Be aware that the temperature difference will change the resistance as well, so that should be accounted in the results.
  • (For those with a lot of time to spare:) People claim that batteries last longer in storage if they are chilled. How quickly does a battery sitting on a shelf decay? How about a battery being stored in a cool environment?
I'm sure there are plenty of others; feel free to add any ideas to the comments!

Disclaimer: Electricity can be dangerous, and you should be aware of the hazards of working with even common alkaline batteries. For example, mixing a drained (or even partially drained) battery with a fresh battery can result in leakage, or possibly fire. The materials inside an alkaline battery are not something to mess with if you're not sure of what you're doing-- so be careful, and if you see anything that looks wrong, stop. If you're young, get help from a parent or teacher. Dispose of waste properly and responsibly.

Any experiments operated using this blog as a basis are done at your own risk and responsibility; I am not liable for any damages that may be caused by duplicating this work or running any experiment derived from this work.  You and you alone are accountable for any consequences of your actions, so if you are unsure about anything, find someone who can help. 

20 June 2012

Experiment: Battery Profiling

Background

Most of us probably purchase batteries with little regard to the brand.  We may purchase whatever is cheapest at the time; we may get a particular brand out of loyalty; we may have just had better luck with one particular brand.  Is there actually any difference between them, though?

I had an experience that  indicates there is, though it may not manifest itself in ways that are apparent to the general consumer.  On a sounding rocket experiment, we had trouble with a particular power supply.  Some investigation revealed that the brand of battery in the supply had problems if it was squeezed in a particular way, shorting out the battery internally.  After taking a few batteries apart, we found that they were, in fact, constructed with slight differences.  How those differences affect performance can be examined using a technique that is ideally suited to a microcontroller.

Here's the idea: run a battery through a particular configuration and monitor its voltage throughout.  In this experiment, I'll keep it simple, but you could easily come up with all kinds of scenarios and configurations in which to compare different batteries.  This demonstration uses only the two major brands, in the AAA form factor, and compares the voltage profile over the lifetime of the batteries at equal current draws.  This is done by having two matched resistors (as measured by a multimeter) draining each battery.  If there is any difference between the two brands, it will be seen by a different discharge rate over time.  Four samples are run, using two resistance values.  Each run uses one of each brand, to eliminate temperature differences.  Two samples are taken at each resistance, swapping the circuits for the two brands in each.  The batteries purchased were selected to have the same expiration date marked on the packages.

Searching online, we find that many people have done a similar experiment, though typically done in ways that are more subjective, such as putting different brands in identical flashlights, see which one gets dim first. Using a microcontroller, we can measure the actual voltage at the battery at specified intervals to get a picture of how the energy is drained from the battery over time.

MSP430 Peripherals Used

  • TimerA with interrupts: Continuous mode, interrupts at CCR0, CCR1, and TAR Rollover
  • ADC10 with interrupts: Sequence Mode, Single Conversion
  • Software UART (Full-Duplex)

Equipment Needed

  • LaunchPad with 32 kHz crystal
  • MSP430G2231 (or any device with ADC10)
  • Computer that can be left on for a few days
  • Multimeter
  • Breadboard
  • 2 single AAA battery holders
  • 2 150 Ω, 1/4 W Resistors
  • 2 33 Ω, 1/4 W Resistors
  • DPST Toggle Switch, rated at least 0.5 A @ 6 V
  • Various Wires

Experiment Design

Schematic for Battery Profiler
The circuit is quite simple: R3, R4, and the LED on P1.6 are built into the LaunchPad.  Q1 is soldered to the LaunchPad and used solely to calibrate the DCO; if this is already done, Q1 is optional.  Remove the jumpers for the Rx, Tx, and LED on P1.0 from the LaunchPad, and jumper Rx to P1.4, Tx to P1.5.

R1 and R2 are matched to be equal resistance, measured with a multimeter.  S1 is a DPST or DPDT toggle switch.  Note that you must use P1.1 and P1.0 to use Sequence Mode for the ADC10 module.

The code for the MSP430G2231 is found in battery_profiler.c.  Most of this code should be straightforward for anyone who has followed through Tutorial 18.  There are a few things to point out, though:

  • Each sample is an average of four measurements.  Since floating point math (particularly division) is a bit expensive in the MSP430, you can use a trick: note that shifting right by one bit is dividing by two. If you are averaging a number of samples equal to a power of 2, you can add the samples together and then shift right by the appropriate number of bits to get division.  Rounding can be done by adding 1 to the highest bit not being included-- in this example, using 4 samples, the second to last bit is the highest not included, so if V holds the sum of  4 measurements, ((V + BIT1) >> 2) gives the rounded average.  Since ADC10 uses only 10 of the 16 bits available in the register, you can average 2, 4, 8, 16, 32, or 64 samples with this technique.  If necessary, floating point numbers and division can be used instead, but it does require more resources of your MSP430 device; plan accordingly.
  • Another issue is transmitting the data; you can transmit the raw bytes back easily, but the data is more easily analyzed afterward if the values are sent in ASCII text.  The MSP430 can use the C printf function in the stdio.h library, but this library is large and increases the size of your code significantly.  This code makes use of a slick scheme to reduce the code size-- the tx_uint() function will transmit a 5 character string corresponding to the zero-padded value of whatever value is passed to it by making use of integer division and modulus operations.  Transmitting the floating point value of the measured voltage is a bit trickier, so the ADC10 conversion is transmitted instead.  These values are converted to a voltage during analysis, using 2.5 V = 1024.
  • The code makes use of the Sequence Mode for the ADC10.  This mode samples each channel starting at that specified by INCH_x in ADC10CTL1, and stepping through to channel A0.  In this example, A1 is measured first, then A0.  This mode operates by waiting for the ENC and SC bits to be set, starting the conversions.  When the first conversion is done, an interrupt is flagged.  In this code, the interrupt resets the flag bit in UART_FG, signaling the code to continue to the next step.  The next channel is sampled when ENC sees another rising edge.  This tripped me up for a while; waiting for a rising edge on ENC allows you to control the timing between samples in the sequence arbitrarily.  If you would rather the ADC10 automatically start the next conversion immediately, you must set the MSC bit in ADC10CTL0 as well when initializing the ADC.  Once the whole sequence is done, ADC10 will wait to have ENC and SC set again to start the next sequence.  This code is timed to do one sequence every 10 seconds.
  • Finally, this code uses all three Timer_A interrupts possible on this device: CCR0, CCR1, and TAR overflow.  This example should help anyone trying to understand the various interrupts that can happen for the Timer_A module.

Results

This experiment takes a good deal of time to finish, and I've decided to post the experiment before getting the actual results.  Here is an example of what we'll be looking at to start-- this is a trial run using two random AAA batteries I had on hand, done just to be certain everything behaved as expected.  As you can see, at 150 Ω it takes days to drain the batteries completely in this setup.  After a few days, I decided to call it a good proof-of-concept, and the experiment is ready to run.  I'll let it run for the next little while, and when I have official results I'll post them here, along with a detailed write-up of what is happening.

Don't worry-- I have two LaunchPads, so I'll be able to post a couple more things while waiting for the experiment to run.

Let me know if you like this post design-- is there any more information that you think would be helpful to have here?

29 May 2012

AdSense

If you haven't already noticed, I've decided to try enabling AdSense on the blog.  I figure I'll give it a shot; if it's not too intrusive I'll leave it there.  Send me feedback and let me know what you think-- there may be better ways to fund my hobby.

25 May 2012

Tutorial 18: Finishing the UART Transceiver

This last tutorial in this series will be fairly short, because there's very little to be done! If we combine tutorial 16f and tutorial 17, we're nearly done building a full-duplex UART transceiver.  There are a few little details that need to be explained in order to get it to work properly, however.

  • A bit counter will be needed for both transmitting and receiving, if you're to be able to do them simultaneously.  This takes another 8 bytes of memory, of course.
  • While not necessary for the UART aspect, this code uses interrupts on two pins of P1. Any output on GPIO, even if interrupts are disabled for the pin, will set the corresponding bit of P1IFG on a rising or falling edge, depending on the setting of the corresponding bit in P1IES. Because the two LEDs are being used, any time the LED is turned on we have a rising edge on that GPIO, which sets the bit in P1IFG. The method used in this code to deal with P1 interrupts fails in those cases, since P1IFG would not be exactly P1RX or BTN1.  To fix this, a mask is introduced so the switch statement in the P1 ISR only considers the bits for P1RX and BTN1, ignoring any others set bits of P1IFG.  There is one disadvantage to this particular scheme: if the UART receives a start bit at the same time as a button press occurs, one or both will be ignored (depending on the order and timing of the two events).
  • A new function is introduced to encapsulate sending a string of characters over UART.  This function makes use of a pointer, allowing us to write new values to the variable message. Be aware that other values in RAM could be overwritten if you're not careful.  Also, the function assumes a message length of exactly 16 characters, and will print garbage (or remnants of the last message) if you write a shorter message.  A longer message will be truncated.
  • Because the DCO is executing commands at a faster rate than the transmission, a short delay of bit_time is added to tx_byte().  This delay lets the transmission start before returning control to the main() function. Without it, the code could call tx_byte() again before transmitting actually starts, changing the value of TXBuffer before it has a chance to get sent.  
The transceiver code can be found in uartTXCVRG2231.c.  I've added a few features to demonstrate the full-duplex capability of the transceiver.  The commands 'r', 'g', and 'z' are retained from the receiver tutorial. To this has been added 'c', which prints a continuous message until another command (eg. 'z' to sleep) is sent.  Note that the command can be sent in the midst of a byte transmission and still work, since the receiver is operating on a separate timer/interrupt configuration.  I verified this to be the case using my logic analyzer, and found that a command was correctly received even while starting in the middle of a transmission.

In addition to the 'c' command, another command is set from a button press (using a non-keyboard ASCII character 0xAF), and can be done at any time, showing that the code can also work with physical interface interrupts as well as the serial transmission of commands.  The button will also stop the continual printing of a 'c' command as well, as it also resets the command variable to 'z'.

Remember to use 9600 baud transmission and to configure CCS to build and link to the header file with the UART calibration, as well as not erase the information memory segment containing the UART DCO calibration.

And with that, we've reached the conclusion of what I'll term as the "basic" tutorials for the MSP430.  A big "Thank you!" to all of you; I've received numerous notes of encouragement from many of my readers, and it's been very helpful.  This project and blog have been a great deal of fun, and wer a key addition to the training I received as a Ph.D. student. This isn't the end of the blog, of course.  I'll be back with more advanced tutorials, and, more importantly, examples of scientific measurements and experiments done with the MSP430.  In fact, my next post will start describing a project I've had in mind for a while.  In the mean time, I will start recompiling these first 18 tutorials into a single volume.  I have as-yet to decide just how it would be distributed, and exactly what form it would take. In any case, I hope all of you stay with me and enjoy exploring the MSP430.

22 May 2012

Tutorial 17: The Receiver

Once you've built a UART transmitter, the receiver is not much different!  The way we'll build the receiver here will be done in anticipation of putting both the transmitter and receiver on the same device, and we'll look at a few new things.

What's the Same

We'll use Timer_A to work with the timings, using the same bit_time value as the transmitter.  The timer will need an accurate clock, and we'll use the calibrated UART frequency from last time as well.  The interrupt service routine for the timer will handle all of the work for reading the serial data as it's transmitted to the device.

What's Different

There are a number of differences in how the receiver is handled, but most of them are quite minor.  We'll use interrupts on the GPIO to trigger receiving, for one.  Once we've seen a falling edge on the GPIO (signalling a start bit being received), we need to wait one half bit_time so that we're sampling in more or less the center of each bit, thus we need a definition for a half bit_time as well.  (We could just divide bit_time by 2, but that's actually kind of slow-- it's probably more conducive to just define another variable with the exact value we want.)  All of this will be handled by an interrupt service routine for the GPIO port.

In addition, we want to use TA1 instead of TA0 for the timing-- this will allow us to send and receive simultaneously, as each has its own independent timer.  TA1 has a slightly different way of handling the ISR, however.  It's worth noting that there's nothing special about TA0 for transmitting nor TA1 for receiving-- we could just as easily have reversed the two.  Which one you use depends on which pins you connect for transmit and receive.  On the LaunchPad (the earlier versions, anyway), Tx is connected to P1.1 and Rx to P1.2.  Looking at the datasheet for the devices that connect to the LaunchPad, P1.1 is connected to TA0.0, letting us use the output feature of Timer_A to change the bit automatically.  P1.5 can also be connected to the TA0.0 output, so that is another option.  P1.2, P1.6, and P2.6 can all be connected to the TA0.1 output, and are all possibilities for the transmit pin if you change from CCR0 to CCR1 for the transmitter's timer.  The receiver will be reading a GPIO, and could in principle be used with any GPIO pin.  (We'll look in a short while to how we can do transmitting on any GPIO as well.)

The Specifics

Alright, let's dig into the code.  First, we need to define our bit_time again, as well as a half_bit_time.  For 9600 baud at the UART calibrated frequency (7.3728 MHz), these correspond to 768 and 384 respectively.  We'll make use of the UART_FG flag variable again, leaving BIT0 for a transmitting flag and using BIT1 for a receiving flag.  The data will be loaded into a buffer again before being saved, using the int value RXBuffer.  The bit_count variable comes into play again, and will be used to count down the bits as they are received.  When we combine the transmitter with the receiver, we'll need one of these for each of the parts so they can count independently.  For now, I've just used the same variable name bit_count.

The DCO and Timer are initialized identically to the transmitter-- the differences in the code happen in the interrupt routines.  P1 is configured to read from our chosen receive pin (P1.2), enabling interrupts on a falling edge.  When the interrupt occurs (presumably at the start bit of a transmission), CCR1 is initialized to a half bit-time later, CCR interrupts are enabled, and P1 interrupts temporarily disabled until the data has been received.  This method precludes having to wait for the receive flag to clear before the next P1 interrupt, so no while loop is needed here.

The CCR1 interrupt is handled differently than the CCR0 interrupt.  For one, CCR0 triggers the interrupt flag TAIFG in the TACTL register.  All other capture/compare registers in a device will trigger flags in the TAIV register.  There is a single interrupt for this register, and so TAIV must be read to know which CCR caused the interrupt.  (Though in the LaunchPad devices there is only CCR1, the interrupt must be handled the same way as though there were further CCR's in the device.)  I've done this by using a C switch statement, looking specifically for a CCR1 flag, which is marked by bit 1 in TAIV.  TAIFG also appears in TAIV, but as the value 0xA rather than 0x2, so a case 2: is sufficient for identifying a CCR1 interrupt flag.  The flag is automatically cleared with the interrupt is serviced.  The bits are then read in bit_time intervals from the GPIO input.  When all 10 bits have been read, the timer interrupts are disabled and P1 interrupts re-enabled.

Now that we've covered essentially how the code works, you can test it out with uartRXG2231.c.  (Don't forget to configure it to not erase the information segments!)  Look at the main function here-- it's set up to look for single-character commands, recognizing the characters 'r' to toggle the red LED, 'g' to toggle the green LED, and 'z' to do nothing but go into a low power mode and wait for a command.  If an invalid command is sent, the code holds on to the current state of P1OUT and flashes the LEDs to signal an error and returns to the saved state.  After each command, the device returns to a sleep mode.  To use the code, be sure you have at least exited the debugger-- you may find that serial terminals don't like trying to communicate through the same port that is opened in CCS in debug mode; exiting debug mode releases the serial port for use. When connected to the proper port (at 9600 baud, of course), you should be able to send single character commands to toggle the red and green LEDs. Try sending an invalid character to see the error signal.

This is the simplest way of sending commands to the MSP430.  Obviously there are uses for multiple-character commands, or sending data directly.  We'll look at those techniques at some point in the future, but next time we'll combine the two parts into a full-duplex transceiver.

Reader Exercise: Add a command to clear both LEDs. See if you can come up with another function to add a command for.

19 May 2012

Tutorial 16f: The Transmitter

We now have all the tools to build a UART transmitter on the MSP430. We have an accurate clock, which operates at a frequency that gives us the best accuracy on standard transmission rates with the DCO. The best way to control the timing of our serial transmission will be to use the Timer_A peripheral, so let's look at how to configure it.

First, we need to ensure we have our DCO set to our custom calibration. The way I've chosen to do this is to use definitions in the header:
   #define CALDCO_UART  *(char *)0x10BE
   #define CALBC1_UART  *(char *)0x10BF
Then in our code, we can set the DCO just as we would for the 1 MHz calibration:
   BCSCTL1 = CALBC1_UART;
   DCOCTL = CALDCO_UART;
To make this even easier, you can put the #defines in a header file (I've called mine calibrations.h), and then include it in any program where you need to use the custom DCO calibration.

Now to set up our timer. First, we need to choose our transmission rate. The commonly selected rate is 9600 baud, and if you use only the LaunchPad's USB connection it may be the only rate that works.  (It's a little unclear still how the USB connection is set up-- the MSP430 UART connects to the MSP430 in the emulator, which has separate pins to forward the data to the TUSB chip interfacing with the USB port.)  This DCO frequency can reliably do transmission up to a rate of 921,600 baud. Any faster, and there may not be enough time to run the transmission code between bits.  The code you can download at the end of the tutorial is configured for 9600 baud.

The next thing we need is to know how many clock cycles occur during the time to transmit one bit. We'll transmit at 9600 bits per second, and our clock oscillates at 7,372,800 times per second, so there are 7,372,800/9600 = 768 clock cycles in each bit. (Note that this is exact; there's no fractional part being truncated in this division, which is why we chose this DCO frequency to start with.) This period is often called the bit time.
   bit_time = 24576;  // bit time for 300 baud
   bit_time = 768;    // bit time for 9600 baud
   bit_time = 64;     // bit time for 115,200 baud

The LaunchPad is set up to send the transmission over P1.1. Looking in the datasheet, we see that this pin can be used as the TA0.0 outputusing Timer_A, we can toggle this output when the TAR counter reaches the value stored in TACCR0. We have two options for this: we can use the timer's up-mode so that the counter resets after reaching TACCR0 of bit_time, or we can use continuous mode and reset TACCR0 to be bit_time cycles beyond the current value of TAR when it triggers an interrupt. (Doing this automatically accounts for roll-over.) The first would be an easy solution for our transmitter, but as we're working towards a full-duplex receiver/transmitter, and the receiver looks at P1.2 (using TA0.1, based on TACCR1 for timing, of course), it makes more sense to use the second method in anticipation of setting up the receiver next time so that we don't have conflicts in using the timer for both tasks.

The idle state for UART is logic high. When we configure the timer, we'll ensure that the TA0.0 defaults to setting P1.1. There's no need to start the timer until we're ready to transmit, but on the other hand there's no need to stop it unless you're concerned about power consumption. We'll go ahead and let the timer run for now, since as a peripheral it runs independently and won't interfere with any code running. We will, however, wait to enable interrupts until we're ready to transmit.

Once we're ready to transmit a character, we need to enable interrupts, and configure Timer_A to reset the TA0.0 output to signal the start of a character. TACCR0 is incremented to bit_time counts later, so the next interrupt occurs at the timing necessary for our chosen transmission rate. We then step through the bits being sent and tell the MSP430 whether the next bit should be set or reset, depending on our encoding. We'll use the standard 8N1, little-endian encoding, so it is determined by the lsb of the character we're sending. When all 8 bits have been sent, we then set TA0.0 to mark a stop bit, making a total of 10 bits for each character. Interrupts are then disabled until we have another character to send.

Take a look at the code in uartTXG2231.c. Note first of all the routine DCO_init(). This includes a trap–since we're accessing the flash memory directly, we run the risk of setting the DCO to its highest setting if we use a device that hasn't had the DCO calibration written to that memory address! This type of check will prevent that, and is not a bad thing to include even when using the factory calibrations. I've created an LED signal specifically to indicate a DCO calibration error: three flashes of LED1, repeated with a pause between sets. If you try this code with an uncalibrated G2231, it should immediately indicate this error. Note that it cannot tell if a written code is correct or not, only if the addresses we're accessing have been erased.

If you've jumped right in and tried to run the code after calibrating your DCO, you may still encounter the error.  CCS by default erases both the main memory and the information memory segments (except for INFO_A) when you program the chip; so your calibrations in INFO_B have been erased and the code won't run.  Rerun the UART calibration code, and then open the project properties.  (When uartTXG2231 is the [Active -Debug] project, you can find the properties in the File menu, or right-clicking the project name in the Project Explorer tab.)  In the menu on the left, select Debug.  In the window that comes up, select MSP430 Properties.  Here you'll see a list of Download Options; be sure to choose "Erase Main Memory Only" and close the properties window.  Now when you load this project into your device, it will only erase the Main Memory and leave the information memory segments alone.

This code is set up to demonstrate a few ways to transmit data.  Each loop is initiated by pressing the button on P1.3.  First, a string is stepped through and sent over UART character by character.  Individual characters are also sent, as is the value of a variable count, which is set to repeatedly count from 1 through 9.  Single digits can be sent as characters easily as they appear in order in ASCII-- the digit 0 is ascii code 48 = 0 + 48, 1 is 49 = 1 + 48, and so on.  A multiple digit number could be pushed through using code similar to what we used for the LCM.  These are some simple ways of putting data and messages through UART that take very little code space in your device.

The real magic happens in the tx_byte() and CCR0_ISR() routines.  When tx_byte is called, it first polls the UART_FG flag and waits for the TXbit to clear.  The byte being sent is loaded into a buffer and formatted to include the stop bit. The TXbit is set in UART_FG, an LED turned on to indicate transmission, and the timer is configured to reset at the next interrupt.  A character cannot be transmitted until at least bit_time after the previous transmission; since the MSP430 clock is so much faster than the data rate, you could potentially run into a problem of initiating a new character send microseconds after the last, rather than leaving at least one bit_time space between.  To prevent this, any present interrupt flag is cleared and the next interrupt is set for one bit_time after the current time.  This configuration leaves just slightly more than one bit time between characters.  The interrupts run the CCR0_ISR routine, which sets the next interrupt to be bit_time later, configures TA0.0 to the next bit state for the next interrupt, and shifts the transmission buffer down to pull the next bit to the front.

To see all of this happen, you'll need a serial terminal, such as RealTerm or PuTTY.  When your terminal is directed to watch the port your LaunchPad is on at the 9600 baud rate, you should see the message display every time you push the button.

Next time we'll use Timer_A to receive data, getting ready for a complete UART transceiver.

18 May 2012

Addendum to Tutorial 16c

As I've been reviewing what I've done so far, I started thinking about some way to test my claims in the tutorial discussing the need for accurate clocks in UART.  I recently acquired a logic analyzer, which is fast proving to be an extremely useful tool for me! I'll probably use it quite a bit in the coming months and years trying to understand and debug some of the designs I'm working through.

In any case, I thought it might be interesting to use it to show what happens when clocks are off slightly.  The four channels shown here are all measuring the same signal, with the Red channel clocking at the correct rate (9600 baud), Yellow at 3% Error (effectively 9888 baud), Green at 6% Error (the theoretical error from using two +/- 3% clocks, effectively 10,176 baud), and Blue at 10% Error (effectively 10,560 baud).



The second image zooms in to the first characters so you can see the frame errors more clearly.  The dots placed on each plot show where each channel is sampling the data stream.  At 6% error, the software is smart enough to decode the characters, but the stop bit on each is missed, making communication unreliable.  In practice, you need better than 5% combined error to have reliable communication in UART.  (Using identical systems, each needs a clock that is accurate to better than 2.5%.)

Note that this isn't really true in all cases; I'm using 8N1 encoding here.  If I were to use larger frames than the 10 bits used for 8N1, the smaller clock errors may eventually cause a frame error as well.  If you use a protocol that sends more than 10 bits, you'll need even more accuracy in your clocks.

Just an interesting little test I put together to try out my fancy logic analyzer.