Atxmega TWI/I2C shush dont tell phillips

Phillips invented the I2C standard a long time ago and owns all the rights to it still so we will be using the TWI standard which just happens to be compatiable with I2C devices.

Atmel also generously provided us with the main driver files so instead of re-hashing them, I am just going to cover how to use their functions. You can either download the drivers from their website or from my github account.

The following examples are for using the device as a master, slave use is straightforward once you get the hang of the drivers.

  • Setup

    \\create an instance of the TWI Master struct TWI_Master_t twiMaster;
    //master struct pointer, twi port, interrrupt level, baudrate setting //baudrate setting = (sys freq/(2*twi freq))-5 //75 = (16MHz/(2*100kHz))-5 TWI_MasterInit(&twiMaster, &TWIE, TWI_MASTER_INTLVL_LO_gc, 75);
    \\enable low level interrupts PMIC.CTRL |= PMIC_LOLVLEN_bm;

  • Write/Read (Write 3 bytes to twi device 6 and read back 5 from it)

    char data[3] = {6,2,1}; //master struct, address, char * write data, num bytes to write, num bytes to read TWI_MasterWriteRead(&twiMaster,6,data,3,5);

  • Transaction finished interrupt

    ISR(TWIE_TWIM_vect){ twiMaster.status = TWIM_STATUS_READY; twiMaster.address = twiMaster.address>>1;
    \\add your code here! }