硬件: nRF52832
SDK: Ver 15.2.0
目标: TWI (I2C) 总线应用 (TWI MASTER 模式)
样例: <InstallFolder>\examples\peripheral\twi_sensor
TWI driver 包括两层: HAL 硬件层和 DRV 驱动层;
TWI MASTER 于 sdk_config.h 中配置
注意:配置中下图红框中 TWI0_ENABLED 使能! 以及选中 TWI0_USE_EASY_DMA!
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);
}
基本用法, 阻塞模式 (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 定义了传输类型
Starting a transfer from PPI (暂略)
Repeated transfers (暂略)
Events (暂略)
在项目文件结构中,添加 nrf_dev_twi.c, nrfx_twi.c,nrfx_twim.c