Thursday, May 21, 2015

BLE application development : Custom Hardware

This is the third post of a series on how to develop an application with Bluetooth Low Energy (BLE). If you haven't already, go back to the first post in the series for information on how to get started. I'm working on a light bulb where the intensity and color temperature can be set via BLE. The application does a ton of stuff, and I'm grafting BLE support into the rest of the application. For projects like this, the Anaren module approach is great.

A Hardware Abstraction Layer is a programming pattern whereby you encapsulate all the functions that talk to the bare hardware into one file. This makes it easier to port the application to different hardware platforms.

To complete this step, you'll need:
a) have completed the previous two steps
b) finished most of your schema with FirstApp, and made stubs for the callbacks
c) the schematic
d) hopefully a reference design close to your application. I'm using Tiva.

Because this is my first project using the Anaren BLE module, I routed all my module connections to the same signals as those used on the Anaren example that uses the TI TM4C123GXL LaunchPad and BoosterPack. This makes porting a little easier.

I recommend getting your schema and callback functions written while in the Em-Builder environment. Changing the schema after you move stuff over is a pain.

I like to start with the Hardware Abstraction Layer because that's the lowest level, and once it is done the rest should be fairly straightforward. Start by creating a new directory called Hal. In it create two blank files, Hal.h and Hal.c. First, copy and paste over the contents of the FirstApp Hal.h file. Save it and compile. Be sure that you don't have errors. My general approach is to go step by step, copying over stuff and compiling as we go. That way we can solve problems early instead of getting to the end and discovering a huge pile of problems to wade through.

Porting Hal.c

I have Hal.c open in Em-Builder, and an empty file in my IDE named Hal.c. I've already copied over Hal.h. Now, to port Hal.c we're going to go step by step: start from the top of the file, copying over a little, modifying it as appropriate, and compiling.

#includes

First, copy over all the includes. The original Hal.c had two files:
#include "lm4f120h5qr_pin_map.h"
#include "inc/lm4f120h5qr.h"
... that can be replaced with the simpler driverlib one:
#include "driverlib/pin_map.h"
Now it should work better.

#defines

There are a couple of #defines that are rather perplexing. To clarify:
EAP_RX_ACK_PIN - this is an input to the module, and an output from the MCU
EAP_TX_ACK_PIN - this is an output from the module, and an input to the MCU
Next you'll see the LED stuff. I ported over the LED_PIN and CONNECTED_LED stuff but I commented out the BLUE_LED stuff. I also left out the BUTTON_PIN and DEBUG1_PIN and DEBUG2_PIN stuff. One thing that isn't self-explanatory: the #define MSEC_CYCLES is the number of cycles in a MSEC, so if your clock frequency is 50MHz, this would be equal to 50000.

Functions

I did not port over the debug functions Hal_debugOn, Hal_debugOff, Hal_debugPulse.

The Hal_Init() function is a big chunk of code, and should be done very carefully. Since I already have a hal_init function for the rest of the application, I renamed this BLE_Hal_init() so that it's clearer. I commented out a lot of the initialization stuff, but be sure to leave in the code that initializes the EAP TX & RX pins:
   SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1);
   /* These are the module's special flow-control functions */

   GPIOPinTypeGPIOOutput(EAP_RX_ACK_PORT, EAP_RX_ACK_PIN);
   GPIOPinTypeGPIOInput(EAP_TX_ACK_PORT, EAP_TX_ACK_PIN);
    IntEnable(INT_GPIOA);
    GPIOIntEnable(EAP_TX_ACK_PORT, EAP_TX_ACK_PIN);

Also include the UART1 initialization, or whatever UART initialization you need. Be sure that it's configured properly.

The last line of their Hal_init function won't allow us to compile. Temporarily comment it out; we'll come back to that later.
//FIXME: update this once the rest is working
//handlerTab[DISPATCH_HANDLER_ID] = Em_Message_dispatch;
The FIXME tag will get automatically added to our list of tasks. This can be seen by adding the Tasks view. To do so navigate to: View : Other : General : Tasks and it should appear next to your problems tab.

With that you should be able to compile the entire Hal.c file.

Event Handling

We're handling event handling a little differently. The Hal.c file has a function:
void Hal_idleLoop(void)
But we're doing it differently, so temporarily we skip over this.

LED Functions

Port the Hal_ledOn, off, read, toggle functions next. If you set up your #defines then you should just be able to copy/paste these functions.

Timer Function

The next function is a little funky:
void Hal_tickStart(uint16_t msecs, void (*handler)(void))
The two parameters are:
  • msecs - the number of milliseconds before the timer expires
  • handler - the function that will be called when the timer expires.
This works in conjunction with Hal_timerIsr(void) which is called by the timer when it expires. The first line in the function:
handlerTab[TICK_HANDLER_ID] = handler;
adds an entry to the event handler table that should be called when the timer expiry event is processed. For now I'm commenting it out so that I can complete the port of the rest of the file.

SRT-HAL Interface

I think the "SRT" refers to the module. I had to do a little bit of googling to find that it means "Schema Runtime" which is as self-explanatory as "SRT". Or not. At any rate, these functions are the ones that handle the serial communication. Here you can see the funky communications protocol that the module uses. When I copied these functions over, the compiler didn't like that the Em_Hal_reset function used Em_Hal_unlock before it was declared, so I moved Em_Hal_unlock above the Em_Hal_reset function. Then Em_Hal_startSend didn't like how Em_Message_startTx was used because I haven't yet included the other Emmoco files.

Interrupt Service Routines

The ISRs are short and to the point which is nice. I did not copy over the Hal_buttonIsr function since I have my own. The rest of these functions form the real meat and potatoes of the module interface. This includes the serial receive ISR as well as the ISR for the handshake from the module, Hal_txAckIsr. When I added these, it became clear that I needed to import the Emmoco files now.

Adding the Emmoco Files

Now that we have a compiling Hal file, lets import the Emmoco files. I simply copied over the Em directory from my FirstApp to my project directory. The first thing that I did was add in the line at the top of my Hal.c file:
#include "Em_Message.h"
and tried to compile. Unfortunately it didn't work; the error
cannot open source file "Em_Message.h"
was displayed. Temporarily I fixed this by changing that line to:
#include "../Em/Em_Message.h"
But this is a hack.

Fixing the Interrupt Service Routines

When I ported the ISRs, there were a number of errors; some from the event handling, and one from an old Stellaris function that was used:
GPIOPinIntClear(EAP_TX_ACK_PORT, EAP_TX_ACK_PIN);
This has been replaced with:
GPIOIntClear(EAP_TX_ACK_PORT, EAP_TX_ACK_PIN);

Should be able to compile now

Following the steps outlined above (and commenting out the few pieces of code) you should be able to compile now.

Copy over the Application Logic

Now, in your main.c file (or whatever file holds your application), add the folowing line:
#include "Em/FirstApp.h"
And compile again. You shouldn't have any errors.

Over in Em-Browser, open your FirstApp-Prog.c file. We will be copying over some variables and functions from here. First, copy over the variables that are used:
static FirstApp_psuTemperatureC_t psuTempC = 10;
static FirstApp_pcbTemperatureC_t pcbTempC = 10;
static FirstApp_level_t intensity = 10;
static FirstApp_colorTemperature_t colorTemperature = 5600;
static FirstApp_command_t powerState = FirstApp_TURN_OFF;

Also, be sure to copy over the connectHandler and disconnectHandler functions; it turns out that the schema requires them.

Fix the Issues from Before

 Previously we commented out some code. Now, go back in and uncomment each part, and be sure it compiles. Add the start() method - the last three lines of your main application should be something like below:
/* The Hal_init() function for BLE stuff */
    BLE_Hal_init();
/* Initialize the BLE module */
    FirstApp_start();

/* The event handler that never exits */
    eventHandler();

Add Interrupt Vectors

The Tiva line of microcontrollers uses a very cool interrupt vector table to tell the processor which function to call for a given interrupt. Open the startup code file that you're using (mine is startup_ccs.c) and add the following interrupt functions, replacing IntDefaultHandler with the name of the function.
    Hal_txAckIsr,                           // GPIO Port A
    Hal_rxIsr,                              // UART1 Rx and Tx
    Hal_timerIsr,                           // Timer 0 subtimer A

Troubleshooting

After I was able to compile the code it didn't work. So, to troubleshooting we go. First, double check your schematic connections, as far as what is an input and what is an output. Next hook up a logic analyzer and observe, and compare to the reference traces:
http://wiki.em-hub.com/display/ED/Sample+Logic+Analyzer+Trace
When I started, I wasn't seeing the RX_ACK pulses after each byte received from the module. Doing a bit of troubleshooting, I found that the uart receive interrupt was not properly configured.





Wednesday, March 4, 2015

Fiducials in Altium

In Printed Circuit Board design, Fiducial marks are used to align the pick and place machine with the PCB. A fiducial requires a circular area free of silkscreen and solderpaste, and in the middle of that area is a smaller circle exposing the top metal of the PCB.

Creating these in Altium with keepouts can be problematic because it will create a keepout on both layers when typically you only want the keepout on the same layer as the fiducial.

I recently saw a great solution for this: do it with a clearance rule. Create a Clearance design rule named "FiducialClearance" (or whatever you want to name it) that specifies the 26mil clearance needed and is limited to just your fiducials. Create a new rule with the following:
HasFootprint('Fiducial-40mil')
Obviously, replace 'Fiducial-40mil' with the name of your fiducial footprint.


Finally change the priority of the "FiducialClearance" rule so that Priority=1.



Thursday, October 16, 2014

The Difference Between an Amateur Engineer and a Professional Engineer

An amateur grabs any old part from the parts bin and puts it into the board. A professional only uses parts that he has a valid part number for, since it will need to go into documentation somewhere.
An amateur assembles boards themselves. A professional only hand-builds if it will save money.
An amateur stores board revisions in zip files. A professional uses version control (like SVN).
An amateur doesn't pay attention to ESD when reworking boards. A professional uses proper grounding & wrist strap.
An amateur tries to solve all the problems himself. A professional coerces the manufacturer to help. :)
An amateur tests whether a design works. A professional tests how well the design works.
An amateur cares about the cost of the software tool. A professional cares about the productivity of the tool.
An amateur asks a question on a forum without RTFM. A professional asks a question on a forum after RTFM, usually when the documentation contradicts itself. :)
An amateur doesn't care about software licensing. A professional can tell you when you can use GPL code vs. LGPL vs. BSD license.

Friday, September 26, 2014

Demystifying Decoupling Capacitor Placement

Digital ICs require decoupling capacitors, to absorb the small current spikes from the switching behavior of the IC. Most of what we know about decoupling capacitor layout is "conventional wisdom", such as:

1. Need a variety of capacitance values to decouple a wide frequency range
2. Many capacitors of one value is better than many values
3. Place caps close to ICs
4. Location doesn't matter
5. Spread caps across the entire board

Most of our conventional wisdom is based on guidelines instead of empirical data.

I found an excellent presentation which explains proper decoupling capacitor placement:
https://ewh.ieee.org/r3/enc/emcs/archive/2012-10-10b_DecouplingMyths.pdf

Friday, August 1, 2014

Using Texas Instruments Tiva Microcontroller Temperature Sensor

The Tiva line of processors from Texas Instruments has an internal temperature sensor. Code to do this is below. To use this,
  1. Call halTemperatureSensorInit() to initialize the sensor and ADC. Only needs to be done once.
  2. Call halGetTemperature() to get the temperature in Celsius
  3. Optionally, call halConvertTemperatureFromCtoF to convert it to Fahrenheit
Example code is below.

/**
* Tiva Microcontroller Internal Temperature Utility Functions
*
* @section license License
* This work is PUBLIC DOMAIN
*
* YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE PROVIDED “AS IS”
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO
* EVENT SHALL  TESLA CONTROLS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE,
* STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR
* INDIRECT DAMAGES OR EXPENSE INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT,
* PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE
* GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY
* DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*/

/**
 * Initialize the ADC for use by the temperature sensor.
 * @see TivaWare/examples/peripherals/adc/temperature_sensor.c
 * @post temperature sensor can be read with halGetTemperature()
 */
static void halTemperatureSensorInit()
{
    /** Enable the ADC */
    SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0);

#define ADC_SEQUENCE    3
#define ADC_STEP        0

    /* Enable sample sequence 3 with a processor signal trigger.
     * Sequence 3 will do a single sample when the processor sends a signal to start the conversion. */
    ADCSequenceConfigure(ADC0_BASE, ADC_SEQUENCE, ADC_TRIGGER_PROCESSOR, 0);

    /* Configure step 0 on sequence 3:
     * - Sample the temperature sensor (ADC_CTL_TS) in single-ended mode (default)
     * - Configure the interrupt flag (ADC_CTL_IE) to be set when the sample is done
     * - Tell the ADC logic that this is the last conversion on sequence 3 (ADC_CTL_END). */
    ADCSequenceStepConfigure(ADC0_BASE, ADC_SEQUENCE, ADC_STEP, ADC_CTL_TS | ADC_CTL_IE | ADC_CTL_END);

    /* Enable the ADC Sequence we're using */
    ADCSequenceEnable(ADC0_BASE, ADC_SEQUENCE);

    /* Clear the interrupt status flag. This is done to make sure the interrupt flag is cleared before we sample. */
    ADCIntClear(ADC0_BASE, ADC_SEQUENCE);
}


/**
 * Read the processor's internal temperature sensor. Accuracy is +/-5C
 * @pre halTemperatureSensorInit() was called to initialize the ADC
 * @return temperature of processor in degrees Celsius
 * @note to convert: VTSENS = 2.7 - ((TEMP + 55) / 75)
 */
int32_t halGetTemperature()
{
    /* This array is used for storing the data read from the ADC FIFO. It must be as large as the
    FIFO for the sequencer in use.  This example uses sequence 3 which has a FIFO depth of 1. */
    uint32_t ulADC0_Value[1];

    /* Our output value */
    int32_t temperatureInDegreesC;

    /* Manually Trigger the ADC conversion */
    ADCProcessorTrigger(ADC0_BASE, 3);

    /* Wait for conversion to be completed */
    while(!ADCIntStatus(ADC0_BASE, 3, false))
    {
    }

    /* Clear the ADC interrupt flag. */
    ADCIntClear(ADC0_BASE, 3);

    /* Read ADC Value. */
    ADCSequenceDataGet(ADC0_BASE, 3, ulADC0_Value);

    //UARTprintf("ADC Value = %u\n", ulADC0_Value[0]);

    /* Reference voltage of 3.3V, in mV.  */
#define REFERENCE_VOLTAGE_MV                (3300l)

    /* ADC is 12 bit resolution */
#define NUMBER_OF_STEPS_12_BIT_RESOLUTION   (4096l)

    /* The voltage from the ADC, in millivolts */
    uint32_t adcMv = (uint32_t) ((ulADC0_Value[0] * REFERENCE_VOLTAGE_MV) / NUMBER_OF_STEPS_12_BIT_RESOLUTION);

    /* Use non-calibrated conversion provided in the data sheet. Divide last to avoid dropout. */
    temperatureInDegreesC = (147500l - 75l * adcMv) / 1000;

    return temperatureInDegreesC;
}


/**
 * Utility function to convert a celsius temperature to fahrenheit.
 * @param temperatureInDegreesC the temp in C
 * @return the temp in F
 */
int32_t halConvertTemperatureFromCtoF(int32_t temperatureInDegreesC)
{
    return ((temperatureInDegreesC * 9) + 160) / 5;
}

Thursday, May 8, 2014

The Main Event - A Simple Event Handler for Microcontrollers

Every application has some type of event handler. Typically, an interrupt will occur, and the interrupt service routine (ISR) will then set a flag, and then the ISR will exit to return to the normal application. This approach is used to minimize the time spent in the ISR. Next, in the main application, the event flags are read, and if any were set then the application processes each event.

I've been looking through the Anaren Bluetooth Low Energy software lately, and I saw this rather cool event handler. It uses a table of function pointers that are the functions to be called when the event occurs.

The Event Handler Functions

We will create a typedef for our function pointer. All functions in our Event Handler Table need to be this type.
/* Typedef for the event handler functions that will go into our table */
typedef void (*Hal_Handler)(void);

Next, for convenience we also create a type for the event flag bitmask. For speed, make this the same as the processor's data size.
/* The type of integer that we will use for our event bitflag. uint32 = 32 possible events */
typedef uint32_t EventFlags;

We also create the global variable that will be the bitflag of any events that get set.
/* Bitflag of the events that need to be processed */
static volatile EventFlags handlerEvents = 0;

To complete the initialization, we define a few events, and create our event handler table.
#define NUM_HANDLERS 3
#define BUTTON_HANDLER_ID      0
#define TICK_HANDLER_ID        1
#define DISPATCH_HANDLER_ID    2

#define KNOB_INCREMENT_HANDLER_ID  3
#define KNOB_DECREMENT_HANDLER_ID  4

/* Table of handler function pointers */
static Event_Handler handlerTable[NUM_HANDLERS];

This table will contain function pointers for the function that gets called when the corresponding event gets called. For example, when the knob gets rotated clockwise, its ISR will set bit #3 in the handlerEvents function. Then the main loop will call the function that is located at handlerTable[3].

We initialize our list by adding event handlers to the event handler table using the method below:
 int addEventHandler(uint8_t index, Event_Handler handler)
 {
     if (index > NUM_HANDLERS)
     {
         return -1;
     }
     handlerTable[index] = handler;
     return 0;
 }

We then call this in our main() function, which we'll explain in a bit.

Set a flag when an event occurs

When an event happens, in the ISR we need to set the bitflag that corresponds to that event. This is done in the postEvent() method as shown below. This bitflag will be read later in our main event handling loop. For safety, we disable interrupts while we are modifying the handlerEvents variable.
/** Set the corresponding bitflag for the eventId */
void postEvent(uint8_t handlerId)
{
    //Note: you should check that handlerId < NUM_HANDLERS here
    IntMasterDisable();
    handlerEvents |= 1 << handlerId;
    IntMasterEnable();
}

In the ISRs, you will need to add a call to postEvent. For example, in a button ISR, add:
postEvent(BUTTON_HANDLER_ID);

Configuring The Actions

When the bitflag for an event gets set, we want the event handler to do something. It does so by calling a function pointer that points to the function that we want to get called when that event happens. For example, when a button is pressed we just want to tell the user. Same for knob, as shown below:
void buttonHandler(void)
{
    printf("Button Pressed!\r\n");
}
void knobIncrementHandler(void)
{
    printf("Knob Up!\r\n");
}
void knobDecrementHandler(void)
{
    printf("Knob Down!\r\n");
}

Now, we need these in the Event Table so in main() we add them with the function we created earlier:

    addEventHandler(BUTTON_HANDLER_ID, buttonHandler);
    addEventHandler(KNOB_INCREMENT_HANDLER_ID, knobIncrementHandler);
    addEventHandler(KNOB_DECREMENT_HANDLER_ID, knobDecrementHandler);

Now we've configured the event setting, and the event processing, so now we can implement the main event handler.

The Main Event (handler)

The Main Event Handler is fairly simple. It continually loops, and processes any events that were set by postEvent(). If a bitflag was set, then it calls the corresponding function pointer.
void eventHandler(void)
{
    IntMasterEnable();
    for (;;)
    {
        /* First, disable interrupts so we don't get messed up while we are reading events */
        IntMasterDisable();

        /* While interrupts are disabled, copy the current list of events that need to be processed */
        EventFlags events = handlerEvents;

        /* ... and clear the master bitflag of events */
        handlerEvents = 0;

        /* Now, process any events that need to be processed */
        if (events)
        {   // dispatch all current events
            IntMasterEnable();     // Enable interrupts - note that we do this before calling each handler function
            /* mask will be the bitflag that we use to check the events bitflag. Starts at 0x1, then 0x2, 0x4, 0x8 etc. */
            uint16_t mask;
            /* The numeric index of the event - 0 through 31 */
            uint8_t id;
            /** Iterate through all possible events */
            for (id = 0, mask = 0x1; id < NUM_HANDLERS; id++, mask <<= 1)
            {
                if ((events & mask) && handlerTable[id]) // If we need to process the event
                {                                      // AND there is an event handler for it
                    handlerTable[id]();                  // ... Then process the event
                }
            }
        } else {          // No events to handle, so wait for more
            /* If using a battery powered device, you could go back to sleep here. Just be sure to enable interrupts! */
            IntMasterEnable();        // Enable Interrupts
        }
    }
}





Friday, May 2, 2014

Using Bluetooth Low Energy to Do Something


In the previous post we looked at how to get up and running with Bluetooth Low Energy. Now we're going to do something useful. This section assumes that you have completed the previous tutorial successfully.

Load on-line Help

First, we want to load the on-line help for the FirstApp example. Open Em-Builder and select Help > Em-Builder > Primer Contents and you'll see a number of lessons available:
 Select "Lesson 01 - Your First App" and the workspace will change to load the on-line help:

Run Unmodified FirstApp

Just like you did for Blinker, now right-click on the FirstApp project in the left hand column and select "Run Em-Builder Example". If you had an error, be sure that your development board is attached, and try the Em-blinker example too. Now open Em-Browser on your iPhone and connect to your development board. You should be able to read and write a variable with the unoriginal name of "data". Fun.

Customizing FirstApp

The first thing that we're going to do to get our feet wet with the Emmoco software is to do something very simple: change the name of the "data" variable to "pcbTemperature". This will give us a good exposure to what Emmoco uses to communicate. Make the change in the schema, FirstApp.ems.


 If you try to build it, then you will get an error, complaining of an unknown type name.

Now in the schema (FirstApp.ems) change the name of the variable "data". This will cause the build to fail, because we need to change all the other variables. If you go to FirstApp.h then you can see declarations of the new typedef and functions.
Now, make these changes to FirstApp.c
Now that we've renamed the variables, we should be able to build successfully. Run the example (Right-click on project and select "Run Em-Builder Example") and it will be loaded on the development board. Using Em-Browser you should be able to read and write a resource named pcbTemperature.

Do Something When We Receive a New Value

Ok, now we're rolling.

Now, just for fun, we modify the function pcbTemperatureC_store() as shown below to blink LED twice whenever we get a new value.
Now, in Em-Browser, write a value to pcbTemperature and you'll see the LED blink twice. Cool! Too bad we don't have printf() here though; it would be nice to be able to see it.

Adding Another Variable

Now we want to add another variable. I looked through the schema examples and saw that there's a 'num' type where you can set the range and interval. This is useful so that the phone application will only send us valid values. We want to control a light, so we add a variable, called 'level'. This can vary between 0% (totally off) and 100% (totally on), in steps of 1 percent each.
Now right click on the project and select"Build Project". It will report a few errors but more importantly it will automatically generate the typedefs and function declarations that we need. This will make our lives easier.
Here we can see that the Emmoco framework created a bunch of new stuff for us, including the following.
The min, max, step, and scale values are there because in the schema we defined our variable as a number with range of 0 to 100 and in steps of 1. We can copy/paste the function declarations into our application to make life easier. Now we need to add these to our application.

In FirstApp-Prog.c, add a variable:
static FirstApp_level_t intensity = 10;
Also add two new functions:
/* Send resource TO phone */
void FirstApp_level_fetch(FirstApp_level_t* output)
{
    *output = intensity;
}

/* Receive new value FROM phone */
void FirstApp_level_store(FirstApp_level_t* input)
{
    intensity = *input;
}

Run the Example

Now, try building again - 'Run Em-Builder Example'. You shouldn't have any errors.
Now open Em-Browser on the iPhone. You can now see that we have a new resource, called Level, and we can write to it and read it.
Clicking on 'level' shows us more information about it. Note that if you try to write a level above 100 then it will be limited to 100.


Conclusion

In this tutorial we demonstrated how to modify one of their examples to do something useful and how to add another variable.








Get Started with Bluetooth Low Energy

This tutorial will show you how to develop an application with Bluetooth Low Energy and do something useful. Going through all the steps in this post will take between 30-60 minutes, depending on if you run into any issues. Bluetooth Low Energy (aka BLE) is all the rage right now, and rightfully so, as it is an easy to use low power RF communications protocol. All the new iPhones and some Android phones incorporate a BLE radio, so you can now easily design RF peripherals to communicate with the iPhone.

I like to use a module for BLE because it is easier and less expensive for quantities less than 10k. For this post I'm trying out the Anaren BLE Module which is available on a Development kit from Digikey for $60. You will also need a Texas Instruments Launchpad. I'm using the TI Tiva Launchpad which available from Digikey for about $14. These are so cheap that I recommend buying two. Below is a picture of the Anaren Board mounted on the Tiva Development Board.
 For this tutorial, you will need:
  • Anaren BLE Development Kit
  • Mini-USB cable for above (comes with the kit)
  • Texas Instruments Tiva Launchpad
  • Micro-USB cable for above (comes with the kit)
  • iPhone, 4S or later to run phone examples
  • iPhone apps "Em-Blinker" & "Em-Browser", available for free from the App Store
  • Basic knowledge of C

Hardware Connections

First, mate the two boards as shown above. Next, connect the Tiva's "Debug" USB port to your computer. Be sure that the slider switch is in the "DEBUG" position. Finally connect the "Admin UART" USB port on the Anaren Board to your computer.

Get the Software

The Anaren module uses a framework from Emmoco to make development easier. Go to www.em-hub.com. You will need to create an account to be able to download the software. Click on the "Sign-Up" link. The access code that it wants is printed on a sticker on the Anaren board. It is on the black connector, on the far left of the above image. Enter that code and your other information. Next, click on the "Downloads" link and select v13, and then "Em-Builder IDE Container" for your operating system.

Install the Software

After it downloads, install the software. It will also install some drivers too. When you first start the application it will look rather empty, like below.
Now we'll follow along the instructions in the left pane. Select Help > Em-Builder > Em-Hub Credentials and enter the same username and password you used to create your account.

Update Development Board Firmware

Next, you'll connect to the board and update the firmware. The hardest part on this step is figuring out which serial port is used for the "UART-ADMIN" port. I tried each of them but figured out finally that it was COM75 on mine. If the application is showing an error, then one thing to try is to press the "MCU Reset SOC" button on the Anaren Board; that allowed the two devices to connect. This took me awhile to figure out.

Once you have updated the firmware, it will be happy:
If you want, you can also change the name of the device here. Call it "SHAMU" or whatever you would like as long as it's all upper case. Now we're done updating the module firmware. If you want, you can remove the USB cable from the "ADMIN UART" port now.

Get the Example Projects

Now we need to import some examples so that we can start playing with them. GO to File > Import > Em-Builder > Example Projects, and select EK-TM4C123GXL as shown below.



Now, the application should have a few example projects:

Running an Example Application

Now we are ready to do something useful. Be sure that the USB cable to the Tiva board is connected to your computer. Right-click on the "Blinker-EK-TM4C123GXL" example and select "Run Em-Builder Example". It should compile and build, as shown below.
Now, open the "Em-Blinker" application on your phone. It should look something like below:
It doesn't do anything yet, you need to tell it to connect to your board. Press the button in the upper right corner to select the board. Previously we named our board "SHAMU" so we select that one. On the Tiva board, the Red LED should illuminate to indicate that it is connected to a phone.
Now, press "Start" or "On" depending on your version of Em-Blinker, and you should now see the blue LED on the Tiva board blink.

Conclusion

In this tutorial we started from zero and ended with a phone connected to our embedded device. Next time we'll look at making our own application.

Wednesday, April 30, 2014

The Easy Way to Use Thermistors


 A Thermistor is a resistor that varies its values with temperature. These are fairly inexpensive and easy to use with a microcontroller that has an analog to digital converter (ADC). However, figuring out how to compute the exact temperature is not simple. Here I go through the process that I use. I call it "The Easy Way" because I use Excel and Word to do the heavy lifting for me.

There are two types of thermistors, Negative Temperature Coefficient (NTC) and Positive Temperature Coefficient (PTC). Simply, for NTC thermistors, the resistance goes DOWN when the temperature goes UP.

In a circuit, thermistors are typically half of a voltage divider. In our example, the top half of the voltage divider is a 10k Ohm, 1% fixed resistor, powered by Vref, 2.5V. The bottom half of the voltage divider is a 10k Ohm 3% NTC thermistor.

Step 1: Get the temperature to resistance table

The math to convert from temperature to resistance is quite complex, so the manufacturers publish a table containing the resistance to temperature values. For example, see this link.

Step 2: Get them into Excel

For the table in the previous link the values were in a PDF sheet. But we need them in Excel. If you have a lot of time on your hands then you can manually retype them all. But I'm lazy, so I did some creative cut/paste from the PDF file into a Notepad file. You need a table consisting of many rows, each row containing the Temperature (in C) and also the Resistance (in Ohms). In Excel I also added another column containing the temperature in degrees Fahrenheit. This is just for convenience and not used in any calculations. The equation to convert from C to F in excel is the following, assuming the value in C is in cell A24:
=CONVERT(A24, "C", "F")
Below we see what our table looks like after we have all our values. We only computed for the temperature range of 0C to 85C because that was our product requirements.

Step 3: Get your ADC working

Use an oscilloscope to measure the output voltage of the voltage divider, while also measuring with the ADC. This will help you calibrate your calculations. Be sure that you know the resolution of your ADC to get the corresponding maximum counts. For example, a 12 bit ADC has 4096 possible values. Obviously to be able to measure temperature you will need to measure the voltage output from the thermistor voltage divider.

Step 4: Math Time

First, a few definitions:
  • R1 = our "top" resistor, in our case the fixed 10kOhm value
  • Rt = the varying thermistor resistance
  • Vref = the voltage supply to the top of the voltage divider, in our case 2.5V
  • Vt = the output voltage of this voltage divider
The equation for the thermistor being on the BOTTOM leg of the voltage divider is:
Rt                    Vt
-------       =   ---------
(R1 +Rt)          Vref

This can be rearranged to:
Rt = R1 / ( ( Vref/Vt) - 1)
Now, test this with your circuit, and verify that you are seeing reasonable values.
Next, we need to convert this to ADC measurements. But first a couple more definitions:
  • ADC= the value we measure from the ADC, in "counts"
  • Resolution = The resolution of the ADC. In our case, this is 4096 because we have a 12-bit ADC.
The ADC equation is:
Vt = (ADC / Resolution) * Vref
We can substitute this into the previous equation to get our magic equation:
ADC = (4096) / ( (R1/Rt) + 1)

Step 5: Make a Table

We can use this equation to create a table in Excel that contains the following tuplets:
  • Temperature (in C)
  • Resistance (in Ohms)
  • ADC Measurement
Using the Microsoft Excel Equation shown below. This assumes that our other resistor is 10k ohms, and our ADC has 4096 counts of resolution. In this case the raw resistance value is in cell C22. We
=((4096)/((10000/C22)+1))
However, this will give us decimal values. We want to round this off, so we use the following:
=ROUND(((4096)/((10000/C22)+1)), 0)

Below shows the table with the ADC values added:

Step 5: Convert this into a C Array

Here's where our laziness comes into play. We're going to use Microsoft Word to convert the list of values into a C array. First, select only the ADC column, starting at the value for 0C. Paste this as plain text into a new Microsoft Word file. Be sure to paste as plain text.
Now we have a wonderful list of values. Next, use Word's find/replace option to replace the carriage return with a comma and a space, as shown below. Note the find string is "^p" without the quotes, and the replace string is ", " without the quotes.
This performs a bit of magic, turning our long list into something that's starting to look like an array:
Now, just wrap this with the variable definition and a comment explaining what it is, and we're done.

/** ADC values which correspond to temperature starting at 0C up to 85C*/
const uint16_t adcToTemperature[] = {3008, 2973, 2937, 2900, 2864, 2827, 2789, 2752,
2714, 2675, 2636, 2598, 2558, 2519, 2480, 2440, 2401, 2362, 2322, 2283, 2243, 2204,
2165, 2126, 2086, 2048, 2010, 1971, 1934, 1896, 1859, 1822, 1785, 1749, 1713, 1678,
1643, 1609, 1575, 1541, 1508, 1476, 1443, 1412, 1381, 1350, 1320, 1290, 1261, 1232,
1204, 1177, 1150, 1123, 1097, 1072, 1047, 1022, 998, 975, 952, 929, 907, 886, 865,
844, 824, 804, 785, 766, 748, 730, 712, 695, 679, 662, 646, 631, 616, 601, 587,
573, 559, 545, 532, 519};

Step 6: Get the Temperature for ADC Reading

We now have our array of values. To get the temperature we just iterate through this table, looking for the closest match. We're not doing any interpolation or anything fancy, just a straight look-up. If you need more accuracy then do something different.
/** Gets the temperature in degrees C for the specified ADC reading.
 * @param adc the reading from the ADC
 * @return the temperature in C, or ERROR_TEMPERATURE_NOT_FOUND if the value was not found.
 */
uint8_t getTemperatureForAdc(uint16_t adc)
{
#define ADC_RESOLUTION                        (4096)

    if (adc > ADC_RESOLUTION)
    {
        return ERROR_TEMPERATURE_NOT_FOUND;  //error - this should not happen
    }

    /* Now iterate through the table, looking for the nearest match */
    uint32_t iterator = 0;
    while (adc < adcToTemperature[iterator])
    {
        iterator++;
    }
    if (iterator == ADC_TO_TEMP_LOOKUP_TABLE_ROWS)
    {
        // We've gone through the entire table but haven't found a match
        return ERROR_TEMPERATURE_NOT_FOUND;  //error - this should not happen
    }
    return (iterator);   // The temperature, in degrees C
}

Conclusion

We now have an easy and fast way to get the temperature from the thermistor.


Thursday, September 12, 2013

Syntax Highlighting for Custom Keywords in IAR

Syntax highlighting makes code much easier to read by parsing the various elements (function names, parameters, constants, etc.) and displaying each differently. Unfortunately IAR doesn't recognize the C99 Fixed-Width Integer Types so it doesn't display them. For example see below. IAR doesn't display uint8_t any differently from the rest of the text.

To make IAR aware of these, you'll need to first create a custom keyword file, and then tell IAR to use it.

Creating a custom keyword file

To create a custom keyword file, open up your favorite text editor and insert the text below. Save it somewhere convenient. 



int8_t int16_t int32_t int64_t
int_fast8_t int_fast16_t int_fast32_t int_fast64_t
int_least8_t int_least16_t int_least32_t int_least64_t
uint8_t uint16_t uint32_t uint64_t
uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t
uint_least8_t uint_least16_t uint_least32_t uint_least64_t
intmax_t intptr_t uintmax_t uintptr_t 




Tell IAR to use the custom keyword file

Go to Tools : Options
Check the "Use Custom Keyword File" checkbox
Click on the Browse button labeled "..." and select the file you created above


Tell IAR to use the custom keyword file

Now, we'll change the color. 
Go to Editor : Colors and Fonts
In the Syntax Coloring box, click on "User keyword"
Change the color and font to whatever you want. I chose green to make them stand out a little from everything else that is blue.

Final Result

Same as before, but now with color.


Monday, September 2, 2013

API Design Technique for Web Application - Part 1

We are in the process of releasing our new web application, COIL, and are working on how to allow users to get their data. COIL is a complete sensor to server development system that enables developers to display data from Zigbee devices in a web page. Users can create an account for free and customize the display of the data. On the back end, COIL receives the data from Gateways and communicates with the devices. We sell COIL as both a single tenant application (one server = one organization) and also as a multi-tenant application (one server supports thousands of users, each with their own data and configuration).

COIL System Architecture

We use a MySQL database instance on Amazon RDS to hold our data. It's very cool. This is in a Virtual Private Cloud along with the application servers hosted on Amazon EC2. So everything is behind one big firewall, with very limited access in/out. For a single tenant system everything is dedicated to that client; one cloud instance only has that one company's data. For multi-tenant systems everything is shared to support thousands of users.

API Goals

One of the goals of COIL is to allow users to access their data via an Application Programming Interface (API). There are a few ways to implement this, all with their own challenges. The goals of our API are:
  • Easy to use - easy to pull into an application.
  • Multitenancy support - support different users
  • Secure - one user should not see a different user's data
  • Implementation independent - allow us to change schema etc. without breaking API
  • Isolated - prevent a user from bogging down the database server.
  • Cross-platform - not tied to Windows, Mac, Linux, etc.
  • Scalable - handle millions of rows

API Design Techniques

So we are evaluating different API approaches, and these have been mentioned:
* Database Access - open up a port into our database
* SOAP - Remote procedure calls
* REST - the most popular approach right now
* Flat Files - like a good old fashioned CSV file

Each of these has pros and cons, which we'll get into more in Part 2.

Saturday, October 13, 2012

Using a Wiki for Technical Documentation

If you still produce technical documentation as PDF files then let me introduce a very cool tool to you. It's called MediaWiki. It's the engine behind a little site you might have heard of, WikiPedia. It's pretty easy to get up and running, and is totally free.

Most people think of wikis as user generated content, but these are also handy for documentation projects where there are few authors but many readers. Most good documentation has two types of content: specifications and examples. The specifications explain how the thing works and are "locked down" as changes are restricted. The examples section is more free-flowing and it is desirable for users to add their own examples. The nice thing is that MediaWiki can be used for both. For specifications you can protect pages so that only a select group of users can make changes to them while at the same time leaving the example pages untouched.

Using a Wiki to Reduce Support Costs

In any product, a support call or email is typically "how do I do X?" and the user may or may not have actually tried to research the problem first. When receiving a request like that the knee-jerk reaction is to explain to the user in a response how to solve the problem. But that only works that one time, and the next time that someone has the same question you'll have to answer the question again. Now many companies turn to user forums, hoping in vain that users will search through the forums for the answer before asking again. But few do, as forums are often full of questions and rarely full of answers.

The better way to answer a support question is to answer the question by creating a Wiki page. This has several benefits. First, the next time that someone asks the same question you can answer the inquiry by sending the user a link to the article (whilst also kindly reminding him to RTFM first). Second, it's a little easier to find a Wiki article due to the organization and searchability of a Wiki site. Finally, it encourages others to add on to the page, increasing the quality of the answer.

Wiki Advantages

There are a few key advantages of using a Wiki to document a product rather than plain PDF files.

Hyperlinks

While you can add links in a PDF document, the Wiki format naturally lends itself to creating links, not just within the document but also to external links too. This can make it much easier for users. For a Zigbee Product Wiki, anytime I used a Zigbee term I made it a link to one page that explains what that term means. Hyperlinking can also reduce redundancy in documents.

Categorization

Another benefit of the wiki format is that you can assign one or more categories to a page. This makes it easy for users to find related content. It's quite easy to do, and allows users to navigate the site easier.

Easier to Maintain

One of the challenges of maintaining traditional documentation is often "who has the most recent word file" for the document. There is also a huge barrier to making any changes, as then the file has to be re-generated and uploaded somewhere. With a Wiki you always have the most recent version of the document on hand. You can create protected pages where users cannot modify the content, which is great for interface specifications.

User Generated Content

How often have you read through a datasheet and thought "why didn't they include more examples?" What would be better is for users to create examples and add it to the page. The best example of this is the MySQL documentation where the user section is as valuable (if not more so) than the official section.

Media

With PDF documentation of course you can include images, but with a Wiki you can include almost any type of media, including videos or other file formats. In the Zigbee Wiki I mentioned previously I wanted to explain to the reader how two ICs communicate. I included an image of a logic analyzer screenshot, but then I also included the logic analyzer capture file. Users can download this and then get in-depth information about how the ICs communicate.

Wrapping Up

So, the next time you need to create documentation for your project, consider using a Wiki. It will take a bit of thought to get up and running but will be much easier to maintain, in addition to the other benefits I mentioned above.


Wednesday, September 19, 2012

Testing Battery Pulse Characteristics

Low power wireless devices typically sleep most of the time and then wake up to send a message and then go back to sleep again. In a previous post I discussed battery selection for low power wireless devices. One issue with using coin cells is that they have poor pulse characteristics, and this performance varies across manufacturers.

To figure out which battery will work for you (and get a feel for battery life) you will need to run a test. This test will involve pulsing the battery, waiting, and then pulsing it again; continuing until the battery voltage under load will no longer be sufficient for your product.

Pulse Waveform
First, you need to get the waveform of what a typical pulse looks like. The easiest way is to supply your circuit through a one-ohm resistor and capture a typical pulse on an oscilloscope. Below is an example.

To test battery life you will need to be able to reproduce this current draw. So, measure the current pulse. You don't need to get that fancy; just measure the width and height of the main pulse. For example, it may be 30mA for 5mSec. To reproduce the pulse you will need a suitable circuit. A simple MOSFET and load resistor will work. For 30mA at 3V use a 100 ohm resistor (V=IR).

Pulse Generation
To generate the pulses you can use an arbitrary waveform generator, or if it's just simple on/off, you could even just write code to do it on a microcontroller development board if that's easier. For the most accurate estimate of battery life as measured by number of pulses you will want to allow as much "recovery time" as possible for the battery between pulses. Obviously you can't wait too long though; if you pulse every 6 seconds and your battery lasts for 45,000 pulses then this will take 3 days to measure. Typically we will run a "slow" test and "fast" test simultaneously to see if wait time has any affect.

Capture
Remember that you need to measure the voltage of each pulse too to ensure that it it above your threshold voltage. This can be done in a few ways:
  • Analog DAQ, like those from National Instruments, although often these are not fast enough
  • Multimeter with output, like an Agilent 34410A DMM. This is what we used with good results. Some custom processing of the output may be required though.
  • Custom code on a microcontroller. Come to think, it might just be the easiest way, especially if you are using the microcontroller to generate the pulses too.
Whatever option you select, record how many pulses it took before failing. It might also be good to record a typical voltage measurement (like voltage readings every millisecond of the pulse) so you can see how it fades.

Test Strategy
For good measurement accuracy, perform the test on a sample of identical batteries, not just one. Five or so is sufficient. If you see lots of variability then you know to definitely not use that vendor. Test batteries from a few different vendors and use this information to determine which battery is best for you.

You also now have a good indication of real battery life and which vendor's battery is best for you. When calculating total battery life be sure to include sleep current consumption as well as the current consumed by receiving any data too.

Monday, September 17, 2012

Battery Selection for Zigbee and Low Power Wireless

Low Power Wireless Standards include Zigbee, Bluetooth Low Energy, Dash7, you name it. Often times the newest wireless standard makes a claim like "lasts 4 years on a coin cell battery!" This is usually in the earliest days of the standard before anyone has actually tried it.

Battery selection for low power wireless standards is very important. These systems typically need to run for a long time (months, if not years) and have many demands. Our ideal battery for these systems:
* Lots of capacity (measured in amp-hours)
* Small size
* Excellent peak current capability (a wireless node can pulse up to 100mA)
* Fairly flat voltage curve
* Very low self-discharge
* Dimensional stability (doesn't swell)
* Low cost
The challenge is that we're asking quite a lot from a battery. We want it to discharge very little while the device is sleeping but then also to discharge in large pulses when we transmit. Usually batteries that have excellent peak current capability have a higher self-discharge rate, and vice-versa.

When starting a new project, people will often leap into creating a fancy battery lifetime spreadsheet, showing how based on estimated current consumption the battery will last something like 13.7 years or so. If only it were so! Unfortunately reality is quite a bit different. Battery lifetime is usually quite a bit shorter and often people don't quite know why.

One of the biggest reasons why is internal resistance. This causes the battery's output voltage to drop under load, limiting the effective amount of current that can be delivered. In general, the larger the battery, the smaller the internal resistance. This is one reason why coin cells don't work well in low power wireless devices - they have too high of internal resistance and therefore cannot supply enough peak current. They'll work fine for data-logging or applications where the peak current is low (below 10mA) but for wireless devices that pulse at 30-100mA they will start to fade. Most coin cells are not specified at all for pulse current, let alone that much. Even worse, the pulse current capability will be different for different vendors' batteries. That means that Energizer may be able to handle a 15mA pulse but Maxell might be able to do 20mA pulses. It all depends on the coin cell size, geometry, etc.

My favorite battery for low power wireless devices is the Energizer L91 (AA size) or L92 (AAA size). These lithium batteries have low self-discharge, nice voltage curve, good peak capability, and you can buy them in most grocery stores.

Next I'll talk about how to test different batteries...

Friday, September 14, 2012

The Joy of Bit-Banging, part 2: RX

I previously discussed how to implement the Tx side of a bit-bang serial port, in The Joy of Bit-Banging, part 1: TX. This time I'll describe how to implement the receive side. This implementation uses blocking waits, as a result it should not be used unless you can tolerate delays.

In this implementation the receive pin is P2.5

Required definitions, etc:
#include "msp430x24x.h"
#define BIT_BANG_RX_PORT P2IN
#define BIT_BANG_RX_BIT BIT5
#define DISABLE_BIT_BANG_RX_INTERRUPT() (P2IE &= ~BIT5)
#define ENABLE_BIT_BANG_RX_INTERRUPT() (P2IE |= BIT5)
//Timings calculated using DCO_8_MHZ - modify if different oscillator speed or different hardware
#define BIT_LENGTH_9600 160
#define HALF_BIT_LENGTH_9600 76
#define BIT_LENGTH_19200 75
#define HALF_BIT_LENGTH_19200 27

/** Simple delay for bit width. Used in transmit and receive. */
void delayFullBit() {for (unsigned int i = 0; i < BIT_LENGTH_19200; i++) ; } //104uSec delay

/** Simple delay for 1/2 of bit width. Used in receive. */
void delayHalfBit() {for (unsigned int i = 0; i < HALF_BIT_LENGTH_19200; i++) ; } //104uSec delay

#define NUMBER_OF_DATA_BITS 8 
#define TOGGLE_DEBUG_PIN() (P4OUT ^= BIT5)  //debugging only

Output function:
/**
* Blocking UART receiver. Called by BIT_BANG_RX_PORT Interrupt Service Routine upon detection of start bit (high to low transition).
* BIT_BANG_RX_BIT should be configured as high-low edge triggered interrupt.
* Receives a byte and then processes it.
* @note BIT_BANG_RX_PORT, BIT_BANG_RX_BIT, DISABLE_BIT_BANG_RX_INTERRUPT(), and ENABLE_BIT_BANG_RX_INTERRUPT() must be #defined. Modify accordingly for other hardware.
* @pre Oscillator configured for 8MHz
* @pre A high-to-low transition has occurred on BIT_BANG_RX_BIT
* @return the byte received
*/
char bitBangInput()
{
    unsigned char receivedBitIndex = 0;
    unsigned char receivedByte = 0;
   
    DISABLE_BIT_BANG_RX_INTERRUPT();
    delayHalfBit();     //Since this method was called on detection of an edge, need to wait until we're in the middle of the bit width.
   
    TOGGLE_DEBUG_PIN();
    //Read this start bit - should be zero
    if (BIT_BANG_RX_PORT & BIT_BANG_RX_BIT)
    {
        //error - re-enable interrupt and return  
    }

    for (int i =0; i    {
        delayFullBit();
        TOGGLE_DEBUG_PIN();
        receivedByte |= (BIT_BANG_RX_PORT & BIT_BANG_RX_BIT) ? (1 << receivedBitIndex) : 0;     //Sample the bit, and if '1' then increase receivedByte accordingly
        receivedBitIndex++;
    }
        delayFullBit();   
        TOGGLE_DEBUG_PIN();
    //THIS IS STOP BIT (line should be back high)
    if (!(BIT_BANG_RX_PORT & BIT_BANG_RX_BIT))
    {
     //error - line is low; should be high because this is stop bit  
    }
    //all bits have been received!
    ENABLE_BIT_BANG_RX_INTERRUPT();
    return receivedByte;
}



Thursday, September 13, 2012

Implementing I2C

Lately I've been doing a lot of I2C development. In just about every way you can do it. Over the course of a month I've had to write code to communicate with an EEPROM and two sensors via:
  • MSP430 using USCI
  • MSP430 using bit-bang
  • Stellaris using StellarisWare
  • Stellaris using bit-bang
Over the course of that experience I've gotten to know the I2C protocol very well. I won't go into the details of the protocol; there are plenty of sources for that.

When you're first getting started, the best way to verify the i2c interface is configured correctly is to not connect the peripheral, but just watch the i2c signals to see that they are being toggled correctly. By definition I2C is not a push-pull interface but uses open drain I/O. It's really quite elegant, as it prevents a bus conflict if one IC outputs a '1' and another outputs a '0'. As a result if you want to see anything you will need external pull-up resistors. I like to first develop code first without the peripheral ICs, just the pull-up resistors. This way you can connect a logic analyzer to the two signals and verify that your code is working correctly. This is especially important if you are implementing a bit-bang solution and need to check that the GPIOs are configured correctly.

If you are using a hardware based solution then it is fairly straightforward; configure the baud rate, etc. and the hardware does all the signaling. The hard part is determining how to use the various hardware registers to get the desired output. This is much easier if you're using StellarisWare, as it handles all the register settings for you.

If you're implementing a bit-bang solution, there are two ways of doing this. The first is with simple delays; the second is using a timer interrupt. I've done both. There both take about the same amount of time to implement. The first way is simpler but requires hand-tuning the amount of delay between bits to ensure the correct baud rate and a 50% duty cycle. Using a timer is a bit more elegant as you're not waiting the processor but requires a state machine to iterate through the various steps. If you're using a StellarisWare it includes a nifty little softI2c implementation that can be used decently easily.

The first test you should do is to just do a simple write of 4 bytes or so, and observe it on the logic analyzer. Of course the ACK bit will not be pulled down since there's no peripheral IC but you'll at least be able to observe proper timing and framing behavior. After you get that working also verify that reads work too.

After you get basic interfacing working, the next step is to write a simple address tester. This just writes to an address and checks to see if the write is acknowledged. This function is handy for verifying that the I2C peripheral is attached properly. This function can also be used for acknowledgment polling if you're implementing an EEPROM or FLASH interface. These types of memories take a few milliseconds to write and you must check that they are no longer in their write cycle before trying to access them again.

Once basic functionality is working you can implement the basic read/write routines. Write is easier since it's a single step operation. Reading typically requires two steps: First writing an address (e.g. register or memory address), then doing a repeat start, and then doing a read.

Since I2C has a fairly low bit rate (100kHz or 400 kHz under normal conditions) it can take awhile to write or read a lot of bytes (6mSec to read a full 64B page from an EEPROM at 100kHz). If you're using the I2C interface in a simple sensor it's fine to wait while communicating since you're not doing anything else until you receive the result. However, that would waste quite a few clock cycles; 160k if using a 25MHz clock. If you're using an RTOS or would otherwise like to minimize wait states then you'll want to implement it differently. In this case you should use DMA or at least an interrupt driven approach.

A few miscellaneous I2C hints:

Logic Analyzer
I2C is much, much easier to troubleshoot with a Logic Analyzer since it will parse the serial data stream and show you the I2C start, stops, and data. I really like one from Saleae, they're USB based and great for microcontroller use.

Mission Critical
I've had occasions whereby one of the peripheral ICs would get into a funky state and cause the I2C bus to lock up. If you're dealing with mission critical application or you just have an extra GPIO pin then I recommend controlling the power of each peripheral IC from the GPIO. That way you can "reboot" a peripheral IC if there is an issue.

Repeat Start
Several peripherals require you to implement a repeat start condition. This isn't well documented in the processor's documentation and you may need to do a bit of research to find out how to do it.