硬體: nRF52832
SDK: Ver 15.2.0
目标: TWI (I2C) 總線應用 (TWI MASTER 模式)
樣例: <InstallFolder>\examples\peripheral\twi_sensor
TWI driver 包括兩層: HAL 硬體層和 DRV 驅動層;
1. TWI MASTER 于 sdk_config.h 中配置
注意:配置中下圖紅框中 TWI0_ENABLED 使能! TWI0_USE_EASY_DMA 視應用要求選擇。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TP350MnpmT10kaNBDOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLzkDN4QTOxcTMzETMxgTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
2. 于工程中添加檔案 nrfx_drv_twi.c, nrf_twim.c
TWI 初始化
初始化和使能函數: nrf_drv_twi_init(), nrf_drv_twi_enable()
去除初始化和禁止函數: nrf_drv_twi_disable(), nrf_drv_twi_uninit()
void twi_handler(nrf_drv_twi_evt_t const * p_event, void * p_context)
{
switch (p_event->type)
{
case NRF_DRV_TWI_EVT_DONE:
if (p_event->xfer_desc.type == NRF_DRV_TWI_XFER_RX)
{
data_handler(m_sample);
}
m_xfer_done = true;
break;
default:
break;
}
}
void twi_init (void)
{
ret_code_t err_code;
const nrf_drv_twi_config_t twi_config = {
.scl = ARDUINO_SCL_PIN,
.sda = ARDUINO_SDA_PIN,
.frequency = NRF_DRV_TWI_FREQ_100K,
.interrupt_priority = APP_IRQ_PRIORITY_HIGH,
.clear_bus_init = false
};
err_code = nrf_drv_twi_init(&m_twi_0, &twi_config, twi_handler, NULL);
APP_ERROR_CHECK(err_code);
nrf_drv_twi_enable(&m_twi_0);
}
TWI 驅動執行個體初始化函數
ret_code_t nrf_drv_twi_init | ( | nrf_drv_twi_t const * | p_instance, |
nrf_drv_twi_config_t const * | p_config, | ||
nrf_drv_twi_evt_handler_t | event_handler, | ||
void * | p_context | ||
) |
參數 event_handler 如果設定為 NULL, 則 TWI 為阻塞工作模式 ( blocking mode).
基本用法, 阻塞模式 (blocking mode)
此模式下,不使用中斷,沒有上下文句柄;
功能函數 nrf_drv_twi_rx(), nrf_drv_twi_tx() 在請求傳輸完成後,或出錯就會傳回。
// 阻塞模式示例代碼
uint32_t err_code;
uint8_t tx_data[] = {'a', 'b', 'c', 'd', 'e'};
const nrf_drv_twi_t twi = NRF_DRV_TWI_INSTANCE(0);
err_code = nrf_drv_twi_init(&twi, NULL, NULL);
APP_ERROR_CHECK(err_code);
nrf_drv_twi_enable(&twi);
err_code = nrf_drv_twi_tx(&twi, SLAVE_ADDRESS, tx_data, sizeof(tx_data), false);
APP_ERROR_CHECK(err_code);
進階用法,非阻塞模式 (non-blocking mode)
TWI 中斷會調用對應的事件處理
功能函數 nrf_drv_twi_tx(), nrf_drv_twi_rx(), nrf_drv_twi_xfer() 執行後會立即傳回 NRF_SUCCESS,
或是當驅動忙時, 立即傳回 NRF_ERROR_BUSY
此模式下, 可用 nrf_drv_twi_xfer() 進行複雜參數傳輸,使用 nrf_drv_twi_xfer_desc_t 結構體;
注: TWI 僅支援 NRF_DRV_TWI_FLAG_TX_NO_STOP flag. 其它辨別需要 TWIM.
nrf_drv_twi_xfer_desc_t::type 定義了傳輸類型