In the last article I talked about How I2C and TWI protocol works and we saw that they are mostly the same so this library works for both I2C and TWI serial interfaces. You don't have to know every detail about how the I2C protocol works but I strongly recommend reading the article to have a general idea about it, and that way it will be easier to use this library.
Using the I2C, TWI library with an AVR microcontroller
Setting the library file
As always, first include the library file:
#include "twi.h"
Most AVR microcontrollers have two TWI modules TWI0 and TWI1 so to choose between the two there is the following line of code:
#define TWI_MODULE_NUMBER 0 // TWI module 0 or 1
The default module is TWI0.
Functions
void TWI_Init(uint32_t frequency)
Used to initialize the TWI module. This will set the TWI bit rate and enable global interrupts. 400kHz is the maximum TWI speed that regular AVR microcontrollers supports although I have managed to talk to a DAC at 577kHz.
frequency: can be one of the following constants or any value between 100-400kHz.
#define TWI_400KHZ 400000 // Hz #define TWI_100KHZ 100000 // Hz