nRF51 SDK - S210 SoftDevice
 All Data Structures Functions Variables Typedefs Enumerations Enumerator Groups Pages
TWI

The two-wire interface (TWI) driver includes two layers: the hardware abstraction layer (HAL) and the driver layer (DRV).

The hardware abstraction layer provides basic APIs for accessing the registers of the TWI. See the API documentation for the TWI HAL for details.

The driver layer provides APIs on a higher level than the HAL. See the API documentation for the TWI driver for details.

Key features include:

  • Repeated start.
  • No multi-master.
  • Only 7-bit addressing.
  • Supports clock stretching.
  • Tries to handle slaves stuck in the middle of transfer.
  • Both blocking and non-blocking mode.

Blocking mode is enabled if no event handler is provided during initialization. If an event handler is provided, calls like nrf_drv_twi_tx or nrf_drv_twi_rx will return instantly with NRF_SUCCESS. Notifications of end of transmission or error will be passed to the application using the nrf_drv_twi_evt_t structure.

The following code shows a simple write sequence without pending transfer:

uint32_t err_code;
uint8_t tx_data[] = {'a', 'b', 'c', 'd', 'e'};
err_code = nrf_drv_twi_init(&twi, NULL, NULL);
APP_ERROR_CHECK(err_code);
err_code = nrf_drv_twi_tx(&twi, SLAVE_ADDRESS, tx_data, sizeof(tx_data), false);
APP_ERROR_CHECK(err_code);
twi_simple_tx.jpg
Write sequence without pending transfer

The following code shows a write sequence with pending transfer:

uint32_t err_code;
uint8_t tx_data[] = {'a', 'b', 'c', 'd', 'e'};
err_code = nrf_drv_twi_init(&twi, NULL, NULL);
APP_ERROR_CHECK(err_code);
err_code = nrf_drv_twi_tx(&twi, SLAVE_ADDRESS, tx_data, sizeof(tx_data), true);
APP_ERROR_CHECK(err_code);
twi_pend_tx.jpg
Write sequence with pending transfer

Errors (like time-out or NACK) will stop the transmission:

twi_error.jpg
Sequence on NACK error