This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Problems reading I2C sensor - Migrating code from MBED to NRF5 SDK

Dear devzone community,

I am currently in the process of migrating my MBED code to NRF5 SDK. My MBED code is functional and it works fine, you can find the code below:

#include "mbed.h"
 
I2C i2c(p2, p3);        // sda, scl
RawSerial pc(p6, p5); // tx, rx
 
uint8_t addr = 0x19; // define the correct I2C Address
uint8_t acc_addr;    
uint8_t acc_id;
uint8_t acc_ready;
uint8_t fs_factor;
char dt[2]; 
#define LIS3DH_CTRL_REG1        0x20
#define data_rate               1 
#define LIS3DH_CTRL_REG4        0x23
#define fullscale               2
#define LIS3DH_SENSITIVITY_8G   4
#define LIS3DH_WHO_AM_I         0x0f
#define I_AM_LIS3DH             0x33
#define LIS3DH_OUT_X_L          0x28 
#define GRAVITY                (9.80665F / 1000)
#define LIS3DH_V_CHIP_ADDR  (0x19 << 1)
int main() 
{
    pc.baud(115200);
    //I2C i2c(p2, p3);        // sda, scl
    i2c.frequency(400000);
    
    // Initialize Check acc is available of not
    acc_addr = addr;
    dt[0] = LIS3DH_WHO_AM_I;
    i2c.write(LIS3DH_V_CHIP_ADDR, dt, 1, true);
    i2c.read(LIS3DH_V_CHIP_ADDR, dt, 1, false);
    pc.printf("%d\n", dt[0]);
    if (dt[0] == I_AM_LIS3DH) {
        acc_ready = 1;
        pc.printf("Ready");
    } else {
        acc_ready = 0;
        pc.printf("Not Ready");
    }
    
    //  Reg.1
    dt[0] = LIS3DH_CTRL_REG1;
    dt[1] = 0x07;
    dt[1] |= data_rate << 4;
    i2c.write(LIS3DH_V_CHIP_ADDR, dt, 2, false);
    //  Reg.4
    dt[0] = LIS3DH_CTRL_REG4;
    dt[1] = 0x08;  // High resolution
    dt[1] |= fullscale << 4;
    i2c.write(LIS3DH_V_CHIP_ADDR, dt, 2, false);
    fs_factor = LIS3DH_SENSITIVITY_8G;

    //ReadID
    dt[0] = LIS3DH_WHO_AM_I;
    i2c.write(LIS3DH_V_CHIP_ADDR, dt, 1, true);
    i2c.read(LIS3DH_V_CHIP_ADDR, dt, 1, false);
    acc_id = (uint8_t)dt[0];
    if(acc_id == I_AM_LIS3DH)
    {
        while (1) 
        {            
            float dt_usr[3];
            char data[6];
            if (acc_ready == 0) 
            {
                dt_usr[0] = 0;
                dt_usr[1] = 0;
                dt_usr[2] = 0;
            }
            dt[0] = LIS3DH_OUT_X_L | 0x80;
            i2c.write(LIS3DH_V_CHIP_ADDR, dt, 1, true);
            i2c.read(LIS3DH_V_CHIP_ADDR, data, 6, false);
            dt_usr[0] = float(short((data[1] << 8) | data[0]) >> 4) * fs_factor * GRAVITY;
            dt_usr[1] = float(short((data[3] << 8) | data[2]) >> 4) * fs_factor * GRAVITY;
            dt_usr[2] = float(short((data[5] << 8) | data[4]) >> 4) * fs_factor * GRAVITY;
            
            
            pc.printf("%f, %f, %f\n",dt_usr[0],dt_usr[1],dt_usr[2]);
            wait(0.5);
        }
    }
}

However I am having problems making the code work in NRF5 SDK. This is what I have so far:

/**
 * Copyright (c) 2015 - 2019, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
/** @file
 * @defgroup tw_sensor_example main.c
 * @{
 * @ingroup nrf_twi_example
 * @brief TWI Sensor Example main file.
 *
 * This file contains the source code for a sample application using TWI.
 *
 */

#include <stdio.h>
#include "boards.h"
#include "app_util_platform.h"
#include "app_error.h"
#include "nrf_drv_twi.h"
#include "nrf_delay.h"

#include "nrf_twi_mngr.h"

#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"

//Includes for UART
//#include "app_uart.h"
//#include "nrf.h"
//#include "bsp.h"
//#include "nrf_uart.h"
///////////////////


/* TWI instance ID. */
#define TWI_INSTANCE_ID     0

/* Common addresses definition for temperature sensor. */
#define LM75B_ADDR          (0x90U >> 1)

#define LM75B_REG_TEMP      0x00U
#define LM75B_REG_CONF      0x01U
#define LM75B_REG_THYST     0x02U
#define LM75B_REG_TOS       0x03U

/* Mode for LM75B. */
#define NORMAL_MODE 0U

/* Indicates if operation on TWI has ended. */
static volatile bool m_xfer_done = false;

/* TWI instance. */
static const nrf_drv_twi_t m_twi = NRF_DRV_TWI_INSTANCE(TWI_INSTANCE_ID);

/* Buffer for samples read from temperature sensor. */
static uint8_t m_sample;

/**
 * @brief Function for setting active mode on MMA7660 accelerometer.
 */
void LM75B_set_mode(void)
{
    ret_code_t err_code;

    /* Writing to LM75B_REG_CONF "0" set temperature sensor in NORMAL mode. */
    uint8_t reg[2] = {LM75B_REG_CONF, NORMAL_MODE};
    err_code = nrf_drv_twi_tx(&m_twi, LM75B_ADDR, reg, sizeof(reg), false);
    APP_ERROR_CHECK(err_code);
    while (m_xfer_done == false);

    /* Writing to pointer byte. */
    reg[0] = LM75B_REG_TEMP;
    m_xfer_done = false;
    err_code = nrf_drv_twi_tx(&m_twi, LM75B_ADDR, reg, 1, false);
    APP_ERROR_CHECK(err_code);
    while (m_xfer_done == false);
}

/**
 * @brief Function for handling data from temperature sensor.
 *
 * @param[in] temp          Temperature in Celsius degrees read from sensor.
 */
__STATIC_INLINE void data_handler(uint8_t temp)
{
    NRF_LOG_INFO("Temperature: %d Celsius degrees.", temp);
}

/**
 * @brief TWI events handler.
 */
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;
    }
}

/**
 * @brief UART initialization.
 */
void twi_init (void)
{

    ret_code_t err_code;
    const nrf_drv_twi_config_t twi_lm75b_config = {
       .scl                = ARDUINO_SCL_PIN,
       .sda                = ARDUINO_SDA_PIN,
       .frequency          = NRF_DRV_TWI_FREQ_400K,
       .interrupt_priority = APP_IRQ_PRIORITY_HIGH,
       .clear_bus_init     = false
    };
  
    err_code = nrf_drv_twi_init(&m_twi, &twi_lm75b_config, twi_handler, NULL);
    APP_ERROR_CHECK(err_code);

    nrf_drv_twi_enable(&m_twi);
}

/**
 * @brief Function for reading data from temperature sensor.
 */
static void read_sensor_data()
{
    m_xfer_done = false;

    /* Read 1 byte from the specified address - skip 3 bits dedicated for fractional part of temperature. */
    ret_code_t err_code = nrf_drv_twi_rx(&m_twi, LM75B_ADDR, &m_sample, sizeof(m_sample));
    APP_ERROR_CHECK(err_code);
}

/**
 * @brief Function for main application entry.
 */

///////////////////////////////
uint8_t addr = 0x19; // define the correct I2C Address
uint8_t acc_addr;    
uint8_t acc_id;
uint8_t acc_ready;
uint8_t fs_factor;
char dt[2]; 
#define LIS3DH_CTRL_REG1        0x20U
#define data_rate               1U 
#define LIS3DH_CTRL_REG4        0x23U
#define fullscale               2U
#define LIS3DH_SENSITIVITY_8G   4U
#define LIS3DH_WHO_AM_I         0x0fU
#define I_AM_LIS3DH             0x33U
#define LIS3DH_OUT_X_L          0x28U 
#define GRAVITY                (9.80665F / 1000)
#define LIS3DH_V_CHIP_ADDR      0x19U
/////////////////////////////

//////////////////////////
int main(void)
{
    APP_ERROR_CHECK(NRF_LOG_INIT(NULL));
    NRF_LOG_DEFAULT_BACKENDS_INIT();

    NRF_LOG_FLUSH();
    NRF_LOG_INFO("\r\nStart");
    NRF_LOG_FLUSH();
    twi_init();
    //NRF_LOG_FLUSH();
    //NRF_LOG_INFO("\r\nTest");
    //NRF_LOG_FLUSH();
    //LM75B_set_mode();

    ret_code_t err_code;
    
    /* Writing to LM75B_REG_CONF "0" set temperature sensor in NORMAL mode. */
    //uint8_t reg[2] = {LM75B_REG_CONF, NORMAL_MODE};
    //nrf_drv_twi_tx(&m_twi, LIS3DH_V_CHIP_ADDR, LIS3DH_WHO_AM_I, 1, false);
    //APP_ERROR_CHECK(err_code);
    //while (m_xfer_done == false);
    //nrf_drv_twi_rx(&m_twi, LIS3DH_V_CHIP_ADDR, &m_sample, sizeof(m_sample));
    //APP_ERROR_CHECK(err_code);
    //while (m_xfer_done == false);

    /* Writing to pointer byte. */
    //reg[0] = LM75B_REG_TEMP;
    //m_xfer_done = false;
    //err_code = nrf_drv_twi_tx(&m_twi, LM75B_ADDR, reg, 1, false);
    ////APP_ERROR_CHECK(err_code);
    //while (m_xfer_done == false);
 

    while (true)
    {
        nrf_delay_ms(500);
        err_code = nrf_drv_twi_tx(&m_twi, LIS3DH_V_CHIP_ADDR, LIS3DH_WHO_AM_I, sizeof(LIS3DH_WHO_AM_I), false);
        //NRF_LOG_INFO(err_code);
        APP_ERROR_CHECK(err_code);
        while (m_xfer_done == false);
        err_code = nrf_drv_twi_rx(&m_twi, LIS3DH_V_CHIP_ADDR, &m_sample, sizeof(m_sample));
        /APP_ERROR_CHECK(err_code);
        if(m_sample == I_AM_LIS3DH)
        {
            NRF_LOG_INFO("\r\nSuccess!");
        }
        else
        {
            NRF_LOG_INFO("Fail");
        }

        //do
        //{
        //    __WFE();
        //}while (m_xfer_done == false);

        //read_sensor_data();
        NRF_LOG_FLUSH();
        NRF_LOG_INFO("\r\nTWI sensor example started.");
        NRF_LOG_FLUSH();
    }
}

/** @} */

Can anybody point out what I am doing wrong here, functionally I want the code to function like in MBED, but I'm not sure about the I2C communication part in NRF5 SDK. It would be super helpful if anybody can give an example in what order I should send and listen to the I2C bus.

kind regards,

Parents
  • Would be easier to narrow down the problem if you can post your working transaction (with MBed code) and not working one (nRF5 SDK based) oscilloscope of logic analyzer output so that we can see what differences there are on the pin output level.

  • In the picture below I am running Lines 29 - 33 of the MBED code, the MCU is sending an I2C message and the sensor is talking back to the MCU.

    In the picture below I am running this code which is supposed to do the same thing as the part I mention above for the MBED code

    uint8_t readRegister(uint8_t regNumber)
    {
        uint8_t resultsWhoAmI;
        uint8_t whoAmIPointer = regNumber;
        nrf_drv_twi_tx(&m_twi, ACCELEROMETER_ADDRESS, &whoAmIPointer, 1, true);
        nrf_drv_twi_rx(&m_twi, ACCELEROMETER_ADDRESS, &resultsWhoAmI, 1);
        return resultsWhoAmI;
    }
    
      while(true){
        test = readRegister(LIS3DH_WHO_AM_I);
        if(test == I_AM_LIS3DH)
        {
          NRF_LOG_FLUSH();
          NRF_LOG_INFO("%d", test);
          NRF_LOG_FLUSH();
        }else
        {
          NRF_LOG_FLUSH();
          NRF_LOG_INFO("%d", test);
          NRF_LOG_FLUSH();
        }

    See the logic analyzer below: It looks like the MCU is successfully communicating with the sensor, but the sensor is not talking back.

    So somewhere in the read command it goes wrong I think

  • it  looks like the device is not reading the RX fast enough what is the priority with which you initialized the nrf_drv_twi? Can you try to increase it to see if that could be the cause?

Reply Children
No Data
Related