I2C Communication with the TI Tiva TM4C123GXL

Created by Shaun Gruenig, last modified on Jul 21, 2014

Purpose

This page contains example code that shows how to use the TI Tiva TM4C123GXL LaunchPad Eval Board for I2C communications. It includes some example code for generic sending and receiving that should work with most devices that support the I2C protocol. To demonstrate the sending functions, it includes some example code for how to use the generic send and receive functions to communicate with a Matrix Orbital GLK12232-25-SM LCD display. To demonstrate the receiving functions, it includes some example code that reads data from a Freescale MMA7455L 3-axis accelerometer.

Introduction

TI’s peripheral driver library for its Tiva series of evaluation boards include functions for using the on-chip I2C peripherals. My example code uses their functions to send and receive data over an I2C bus. My code uses bus 0, but can easily be modified to allow a different bus to be used, or a bus to be specified when calling the function if multiple buses are necessary (by making the bus a variable instead of hard-coding). My example code does lack error-checking at this point; in my experience working with the TM4C123GXL, error-checking was not needed for my uses. However, if the device is going to be used in critical applications, error checking should be added to ensure proper communication between the MCU and the slave device(s). Error-checking likely becomes more important as more and more slave devices share the same I2C bus (which is a major benefit of using the I2C protocol). Some error-checking that should be implemented includes ensuring that the slave device(s) properly acknowledge the master device’s communications, and ensuring that responses from the slave device(s) are within expected values/boundaries.

Example of Generic I2C Communications

These are the necessary libraries to include in order for the example code to function properly.

Included Libraries

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include "inc/hw_i2c.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_gpio.h"
#include "driverlib/i2c.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/pin_map.h"

This code initializes I2C peripheral 0.

Initialize I2C0 function

//initialize I2C module 0
//Slightly modified version of TI's example code
void InitI2C0(void)
{
    //enable I2C module 0
    SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0);
 
    //reset module
    SysCtlPeripheralReset(SYSCTL_PERIPH_I2C0);
     
    //enable GPIO peripheral that contains I2C 0
    SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
 
    // Configure the pin muxing for I2C0 functions on port B2 and B3.
    GPIOPinConfigure(GPIO_PB2_I2C0SCL);
    GPIOPinConfigure(GPIO_PB3_I2C0SDA);
     
    // Select the I2C function for these pins.
    GPIOPinTypeI2CSCL(GPIO_PORTB_BASE, GPIO_PIN_2);
    GPIOPinTypeI2C(GPIO_PORTB_BASE, GPIO_PIN_3);
 
    // Enable and initialize the I2C0 master module.  Use the system clock for
    // the I2C0 module.  The last parameter sets the I2C data transfer rate.
    // If false the data rate is set to 100kbps and if true the data rate will
    // be set to 400kbps.
    I2CMasterInitExpClk(I2C0_BASE, SysCtlClockGet(), false);
     
    //clear I2C FIFOs
    HWREG(I2C0_BASE + I2C_O_FIFOCTL) = 80008000;
}

This is the code for sending a series of bytes passed into the function as arguments.

I2C Send Function

//sends an I2C command to the specified slave
void I2CSend(uint8_t slave_addr, uint8_t num_of_args, ...)
{
    // Tell the master module what address it will place on the bus when
    // communicating with the slave.
    I2CMasterSlaveAddrSet(I2C0_BASE, slave_addr, false);
     
    //stores list of variable number of arguments
    va_list vargs;
     
    //specifies the va_list to "open" and the last fixed argument
    //so vargs knows where to start looking
    va_start(vargs, num_of_args);
     
    //put data to be sent into FIFO
    I2CMasterDataPut(I2C0_BASE, va_arg(vargs, uint32_t));
     
    //if there is only one argument, we only need to use the
    //single send I2C function
    if(num_of_args == 1)
    {
        //Initiate send of data from the MCU
        I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_SINGLE_SEND);
         
        // Wait until MCU is done transferring.
        while(I2CMasterBusy(I2C0_BASE));
         
        //"close" variable argument list
        va_end(vargs);
    }
     
    //otherwise, we start transmission of multiple bytes on the
    //I2C bus
    else
    {
        //Initiate send of data from the MCU
        I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_START);
         
        // Wait until MCU is done transferring.
        while(I2CMasterBusy(I2C0_BASE));
         
        //send num_of_args-2 pieces of data, using the
        //BURST_SEND_CONT command of the I2C module
        for(uint8_t i = 1; i < (num_of_args - 1); i++)
        {
            //put next piece of data into I2C FIFO
            I2CMasterDataPut(I2C0_BASE, va_arg(vargs, uint32_t));
            //send next data that was just placed into FIFO
            I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_CONT);
     
            // Wait until MCU is done transferring.
            while(I2CMasterBusy(I2C0_BASE));
        }
     
        //put last piece of data into I2C FIFO
        I2CMasterDataPut(I2C0_BASE, va_arg(vargs, uint32_t));
        //send next data that was just placed into FIFO
        I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_FINISH);
        // Wait until MCU is done transferring.
        while(I2CMasterBusy(I2C0_BASE));
         
        //"close" variable args list
        va_end(vargs);
    }
}

This is another send command. This command, instead of using a list of argument (of variable length), sends a C-style string. This is useful if the data you want to send is a string, or already packed into an array of bytes. Be aware that the function expects a C-style string (in other words, it expects the array of bytes to end with a NULL terminator).

I2C Send String Function

//sends an array of data via I2C to the specified slave
void I2CSendString(uint32_t slave_addr, char array[])
{
    // Tell the master module what address it will place on the bus when
    // communicating with the slave.
    I2CMasterSlaveAddrSet(I2C0_BASE, slave_addr, false);
     
    //put data to be sent into FIFO
    I2CMasterDataPut(I2C0_BASE, array[0]);
     
    //if there is only one argument, we only need to use the
    //single send I2C function
    if(array[1] == '\0')
    {
        //Initiate send of data from the MCU
        I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_SINGLE_SEND);
         
        // Wait until MCU is done transferring.
        while(I2CMasterBusy(I2C0_BASE));
    }
     
    //otherwise, we start transmission of multiple bytes on the
    //I2C bus
    else
    {
        //Initiate send of data from the MCU
        I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_START);
         
        // Wait until MCU is done transferring.
        while(I2CMasterBusy(I2C0_BASE));
         
        //initialize index into array
        uint8_t i = 1;
 
        //send num_of_args-2 pieces of data, using the
        //BURST_SEND_CONT command of the I2C module
        while(array[i + 1] != '\0')
        {
            //put next piece of data into I2C FIFO
            I2CMasterDataPut(I2C0_BASE, array[i++]);
 
            //send next data that was just placed into FIFO
            I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_CONT);
     
            // Wait until MCU is done transferring.
            while(I2CMasterBusy(I2C0_BASE));
        }
     
        //put last piece of data into I2C FIFO
        I2CMasterDataPut(I2C0_BASE, array[i]);
 
        //send next data that was just placed into FIFO
        I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_FINISH);
 
        // Wait until MCU is done transferring.
        while(I2CMasterBusy(I2C0_BASE));
    }
}

This function receives (or reads) data on the I2C bus. In its current state, it can only read a single register on the slave device, as not all I2C devices support reading multiple registers in a single transaction. Similar to the send commands above, the I2C_MASTER_CMD_BURST_RECEIVE_START/CONT/FINISH can be used to modify the function to read multiple registers on the slave device (if it supports doing so).

I2C Receive Function

//read specified register on slave device
uint32_t I2CReceive(uint32_t slave_addr, uint8_t reg)
{
    //specify that we are writing (a register address) to the
    //slave device
    I2CMasterSlaveAddrSet(I2C0_BASE, slave_addr, false);
 
    //specify register to be read
    I2CMasterDataPut(I2C0_BASE, reg);
 
    //send control byte and register address byte to slave device
    I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_BURST_SEND_START);
     
    //wait for MCU to finish transaction
    while(I2CMasterBusy(I2C0_BASE));
     
    //specify that we are going to read from slave device
    I2CMasterSlaveAddrSet(I2C0_BASE, slave_addr, true);
     
    //send control byte and read from the register we
    //specified
    I2CMasterControl(I2C0_BASE, I2C_MASTER_CMD_SINGLE_RECEIVE);
     
    //wait for MCU to finish transaction
    while(I2CMasterBusy(I2C0_BASE));
     
    //return data pulled from the specified register
    return I2CMasterDataGet(I2C0_BASE);
}

Example of Writing Data to a Matrix Orbital GLK12232-25-SM LCD display

Here are some examples of using the above code to communicate with a Matrix Orbital GLK12232-25-SM LCD display. These examples include both sending commands to the devices to adjust parameters like brightness and contrast, as well as sending characters and strings to be printed on the display. For this particular display, no command is necessary to write characters to the display, so simply sending a character will cause it to be printed. On the other hand, command bytes (which are specific to this device and, for this device, always begin with the byte 0xFE) are sent to instruct the device to perform a specific task.

Functions

#define LCD_SLAVE_ADDR 0x28
#define LCD_CMD 0xFE //used to send commands to the LCD
  
//clear LCD
void ClearScreen()
{
    I2CSend(LCD_SLAVE_ADDR, 2, LCD_CMD, 0x58);
}
 
//set brightness of LCD
void SetBrightness(uint8_t brightness)
{
    I2CSend(LCD_SLAVE_ADDR, 3, LCD_CMD, 0x99, brightness);
}
  
//set contrast of LCD
void SetContrast(uint8_t contrast)
{
    I2CSend(LCD_SLAVE_ADDR, 3, LCD_CMD, 0x50, contrast);
}
 
//write single char to LCD
void WriteChar(uint8_t character)
{
    I2CSend(LCD_SLAVE_ADDR, 1, character);
}
  
//write string to LCD
void WriteString(char string[255])
{
    I2CSendString(LCD_SLAVE_ADDR, string);
}
 
//draw a line with start point (x1, y1) and endpoint (x2, y2)
void DrawLine(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2)
{
    I2CSend(LCD_SLAVE_ADDR, 6, LCD_CMD, 0x6C, x1, y1, x2, y2);
}
  
//set coordinates (in exact pixels) of the cursor
void SetCursorCoord(uint8_t x, uint8_t y)
{
    I2CSend(LCD_SLAVE_ADDR, 4, LCD_CMD, 0x79, x, y);   
}
 
//set position of the text cursor
void SetCursorPos(uint8_t col, uint8_t row)
{
    I2CSend(LCD_SLAVE_ADDR, 4, LCD_CMD, 0x47, col, row);   
}

Main Function

void main(void)
{
    // Set the clocking to run directly from the external crystal/oscillator.
    SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_PLL | SYSCTL_OSC_INT | SYSCTL_XTAL_16MHZ);
  
    //initialize I2C module 0
    InitI2C0();
  
    //initialize display
    SetBrightness(0);
    SetContrast(150);
    ClearScreen();
  
    SetCursorPos(0, 1);
    WriteString("Hello,");
    SetCursorPos(0, 2);
    WriteString("World!");
  
    while(1){};
}

Example of Reading data from a Freescale MMA7455L 3-axis Accelerometer

Here is some very basic example code for reading the 8-bit x,y, and z registers on the Freescale MMA7455L.

Example Code

#define ACCEL_SLAVE_ADDR 0x1D
#define XOUT8 0x06
#define YOUT8 0x07
#define ZOUT8 0x08
  
uint8_t ReadAccel(uint8_t reg)
{
    uint8_t accelData =  I2CReceive(ACCEL_SLAVE_ADDR, reg);
 
    return accelData;
}
  
void main(void)
{
    // Set the clocking to run directly from the external crystal/oscillator.
    SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_PLL | SYSCTL_OSC_INT | SYSCTL_XTAL_16MHZ);
 
    //initialize I2C module 0
    InitI2C0();
  
    uint8_t Ax, Ay, Az;
  
    Ax = ReadAccel(XOUT8);
    Ay = ReadAccel(YOUT8);
    Az = ReadAccel(ZOUT8);
  
    while(1){};
}

Questions/Comments

Any questions or comments please go to Digi-Key’s TechForum