nRF52832's TWI (two wire interface, also known as hardware i2c):
1. i2c communication knowledge reserve
1.i2c communication requires two lines, sda and scl. I2C communication roles are divided into: master and slave
2. When the communication bus is idle, scl and sda are in a high state
3. During the i2c communication process, there are two sets of control signals:
1) start:
sda when scl is high From high level to low level
2) stop: When
scl is high level, sda changes from low level to high level
Second, programming analysis
SDK version: nRF5_SDK_15.2.0_9412b96
//1.twi初始化配置
//头文件:nrf_drv_twi.h
//sdk_config.h中开启twi功能
#define ARDUINO_SCL_PIN 7
#define ARDUINO_SDA_PIN 8
#define TWI_IMU_INSTANCE_ID 1 //使用TWI1
#define IMU_ADDR (0x78>>1) //IMU地址
static const nrf_drv_twi_t m_twi = NRF_DRV_TWI_INSTANCE(TWI_IMU_INSTANCE_ID) //twi实例
static volatile bool m_xfer_done = false; //指示twi的操作是否结束
//twi回调函数,主要是用来上报twi操作完成功能
static 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_TX)
{
NRF_LOG_INFO("twi tx donw!");
}
else if(p_event->xfer_desc.type == NRF_DRV_TWI_XFER_RX)
{
NRF_LOG_INFO("twi rx donw!");
}
m_xfer_done = true;
break;
case NRF_DRV_TWI_EVT_ADDRESS_NACK:
NRF_LOG_INFO("Error event: NACK received after sending the address.");
break;
case NRF_DRV_TWI_EVT_DATA_NACK:
NRF_LOG_INFO(" Error event: NACK received after sending a data byte.");
break;
default:
break;
}
}
static void twi_config(void)
{
uint32_t err_code;
nrf_drv_twi_config_t const config = {
.scl = ARDUINO_SCL_PIN, //时钟gpio引脚
.sda = ARDUINO_SDA_PIN, //数据gpio引脚
.frequency = NRF_TWI_FREQ_100K, //twi时钟频率
.interrupt_priority = APP_IRQ_PRIORITY_LOWEST, //中断优先级
.clear_bus_init = false //初始化期间清除总线
}
//初始化twi
err_code = nrf_drv_twi_init(&m_twi,&config,twi_handler,NULL);
APP_ERROR_CHECK(err_code);
//使能twi
nrf_drv_twi_enable(&m_twi);
}
// 2. Read and write slave device
1) Write
ret_code_t nrf_drv_twi_tx (nrf_drv_twi_t const * p_instance, uint8_t address, uint8_t const * p_data, uint8_t length, bool no_stop);
p_instance: pointer to the twi instance
address: slave address
p: address data Buffer
length: number of data bytes to be sent
no_stop: no stop bit is set
2) read
ret_code_t nrf_drv_twi_rx (const * p_instance nrf_drv_twi_t, uint8_t address, uint8_t const * P_DATA, uint8_t length);
p_instance: twi instance pointer points to
address : Slave device address
p_data: read data storage buffer
length: read data byte length