在上篇介绍了OLED的II以写操作为主,没有进行读取操作。所以在现再补充读取的操作。
我在此以LIS2DH为例子
uint8_t temp; lis2dh_read_registers(LIS2DH_WHO_AM_I,&temp,1);
我们现在操作的寄存器为who_am_i时序如下
好了现在贴上主要代码
#define MEMS_LIS2DH_ADDR (0x30U>>1) #define LIS2DH_WHO_AM_I 0x0F #define MEMS_TWI_TIMEOUT 5000 static const nrf_drv_twi_t m_twi_mems_lis2ds12 = NRF_DRV_TWI_INSTANCE(1);//需要在nrf_drv_config.h文件中 #define TWI1_ENABLED 1 volatile static bool twi_tx_done = false; volatile static bool twi_rx_done = false;
void mems_lis2dh12_twi_handler(nrf_drv_twi_evt_t const * p_event, void * p_context)
{
ret_code_t err_code;
switch(p_event->type)
{
case NRF_DRV_TWI_RX_DONE:
twi_rx_done = true;
break;
case NRF_DRV_TWI_TX_DONE:
twi_tx_done = true;
break;
default:
break;
}
}
void bsp_lis2dh12_init(void)
{
ret_code_t err_code;
const nrf_drv_twi_config_t twi_mems_lis2dh12_config =
{
.scl = MEMS_LIS2DH12_I2C_SCL_PIN,
.sda = MEMS_LIS2DH12_I2C_SDA_PIN,
.frequency = NRF_TWI_FREQ_100K,
.interrupt_priority = APP_IRQ_PRIORITY_LOW
};
err_code = nrf_drv_twi_init(&m_twi_mems_lis2dh12, &twi_mems_lis2dh12_config, mems_lis2dh12_twi_handler, NULL);
APP_ERROR_CHECK(err_code);
nrf_drv_twi_enable(&m_twi_mems_lis2dh12);
nrf_gpio_pin_clear(MEMS_LIS2DH12_SD0_PIN);
nrf_gpio_cfg_output(MEMS_LIS2DH12_SD0_PIN);
nrf_gpio_pin_set(MEMS_LIS2DH12_CS_PIN);
nrf_gpio_cfg_output(MEMS_LIS2DH12_CS_PIN);
}
uint32_t lis2dh12_write_register(uint8_t reg_param, uint8_t data_param)
{
uint32_t err_code;
uint32_t timeout = MEMS_TWI_TIMEOUT;
uint8_t packet[2] = {reg_param, data_param};
err_code = nrf_drv_twi_tx(&m_twi_mems_lis2dh12, MEMS_LIS2DH12_ADDR, packet, 2, false);
if(err_code != NRF_SUCCESS)
{
return err_code;
}
while((!twi_tx_done) && --timeout);
if(!timeout)
{
return NRF_ERROR_TIMEOUT;
}
twi_tx_done = false;
return err_code;
}
uint32_t lis2dh12_read_registers(uint8_t reg_param, uint8_t * p_data, uint32_t length)
{
uint32_t err_code;
uint32_t timeout = MEMS_TWI_TIMEOUT;
err_code = nrf_drv_twi_tx(&m_twi_mems_lis2dh12, MEMS_LIS2DH12_ADDR, ®_param, 1, false);
if(err_code != NRF_SUCCESS)
{
return err_code;
}
while((!twi_tx_done) && --timeout);
if(!timeout)
{
return NRF_ERROR_TIMEOUT;
}
twi_tx_done = false;
err_code = nrf_drv_twi_rx(&m_twi_mems_lis2dh12, MEMS_LIS2DH12_ADDR, p_data, length, false);
if(err_code != NRF_SUCCESS)
{
return err_code;
}
timeout = MEMS_TWI_TIMEOUT;
while((!twi_rx_done) && --timeout);
if(!timeout)
{
return NRF_ERROR_TIMEOUT;
}
twi_rx_done = false;
return err_code;
}