1.35.17 Two-wire Interface - TWI

The TWI PLIB can be configured in TWI master mode.

TWI master mode The TWI peripheral library supports the following transfers:

Master Write: The master writes a block of data to the slave Master Read: The master reads a block of data from the slave Master Write/Read: The master writes and then reads back a block of data from slave.

The block of data is transferred in a non-blocking manner using a peripheral interrupt. Application can either use a callback or IsBusy API to check for completion of data transfer.

// Following code demonstrates TWI write operation using polling method

#define APP_SLAVE_ADDR 0x0057
#define NUM_BYTES      10

uint8_t myWriteData [NUM_BYTES] = {'1', '0', ' ', 'B', 'Y', 'T', 'E', 'S', '!', '!',};

int main(void)
{
	/* Initialize all modules */
    SYS_Initialize ( NULL );
	
    /* Write data to the TWI Slave */
    TWI1_Write(APP_SLAVE_ADDR, &myWriteData[0], NUM_BYTES);

    /* Poll and wait for the transfer to complete */
    while(TWI1_IsBusy());

    /* Check if any error occurred */
    if(TWI1_ErrorGet() == TWI_ERROR_NONE)
    {
        //Transfer is completed successfully
    }
    else
    {
        //Error occurred during transfer.
    }
	...
}
// Following code demonstrates TWI write operation using callback method

#define APP_SLAVE_ADDR 0x0057
#define NUM_BYTES      10

uint8_t myWriteData [NUM_BYTES] = {'1', '0', ' ', 'B', 'Y', 'T', 'E', 'S', '!', '!',};

void TWI1_Callback(uintptr_t context)
{
    if(TWI1_ErrorGet() == TWI_ERROR_NONE)
    {
        //Transfer is completed successfully
    }
    else
    {
        //Error occurred during transfer.
    }
}

int main(void)
{
	/* Initialize all modules */
    SYS_Initialize ( NULL );
	
    /* Register Callback function */
    TWI1_CallbackRegister(TWI1_Callback, (uintptr_t)NULL);

    /* Submit Write Request */
    TWI1_Write(APP_SLAVE_ADDR, &myWriteData[0], NUM_BYTES);
	
	...
}

Library Interface

TWI Mode

Functions

Name Description
TWIx_Initialize Initializes given instance of the TWI peripheral
TWIx_Read Reads data from the TWI slave
TWIx_Write Writes data to the TWI slave
TWIx_WriteRead Write and Read data from TWI Slave
TWIx_IsBusy Returns the TWI Peripheral busy status
TWIx_ErrorGet Returns the TWI error that occurred on the bus
TWIx_TransferSetup Dynamic setup of TWI Peripheral
TWIx_CallbackRegister Sets the pointer to the function (and it's context) to be called when the given TWI's transfer events occur

Data types and constants

Name Type Description
TWI_ERROR Enum Defines the possible errors that the I2C peripheral can generate in I2C master mode
TWI_TRANSFER_SETUP Struct I2C transfer setup data structure
TWI_CALLBACK Typedef Defines the data type and function signature for the TWI peripheral callback function in TWI master mode