Two-Wire Interface (TWI) driver — Configuration and implementation details of TWI (I²C®) driver


The SAM9 processor HAL contains a driver for the Two-Wire Interface (TWI) controller on the SAM9. This type of bus is also known as I²C®. The API for this may be found within the CYGPKG_IO_I2C package.

I²C/TWI driver configuration

The I²C® driver uses the SAM9's internal Two-Wire Interface (TWI) support. This is controlled within the SAM9 processor HAL (CYGPKG_HAL_SAM9). The CYGPKG_HAL_SAM9_TWI CDL component controls whether the TWI driver is enabled. Within that component, there are two sub-options:

  • CYGNUM_HAL_SAM9_TWI_CLOCK sets the speed of the TWI bus clock in Hz. This is usually 100kHz, but can be set up to 400kHz if the devices on the bus support this speed, also known as fast mode. However other values below 400kHz can also be chosen, subject to the accuracy of the clock waveform generation parameters.
  • The second option within the CYGPKG_HAL_SAM9_TWI component is CYGNUM_HAL_SAM9_TWI_CKDIV. This is the clock divider used when configuring the TWI_CWGR register. Consult the SAM9 datasheet description of the TWI_CWGR register for the formula used to determine the clock frequency. Increasing the divider will decrease the accuracy in practice of the generated I²C bus clock compared to CYGNUM_HAL_SAM9_TWI_CLOCK. But the divider must also be sufficiently low that the relevant factors do not overflow valid values for CHDIV/CLDIV in TWI_CWGR. Note that when the SAM9 is using a 60MHz MCK, then for 100kHz operation, a value for this option of 1 is most appropriate. For 400kHz, a value for this option of 0 is most appropriate. The default value of this CDL is an appropriate value for CKDIV assuming a 60MHz MCK and a TWI clock between 29kHz and 400kHz.

    To be specific, the CLDIV/CHDIV fields of the TWI_CWGR are considered equal. The value of, for example, CLDIV, can be expressed as:

To use the I²C/TWI driver, the generic I²C driver package CYGPKG_IO_I2C must be used. Documentation for its API may be found elsewhere.

Usage notes

Due to the characteristics of the SAM9's operation, it is not possible to provide support for repeated starts with the I²C package API. Similarly indicating a NACK when performing a receive is equivalent to also sending a STOP.

A test application for use with the AT24C512 serial EEPROM fitted to the AT91SAM9260EK board is provided within the tests subdirectory of the CYGPKG_HAL_SAM9 package. This test communicates with the I²C EEPROM on the board to perform read and write operations using I²C. This test is not built by default. It may be built by enabling the configuration option CYGBLD_HAL_ARM_ARM9_SAM9_TEST_TWI_AT24C512 within the SAM9 processor HAL.