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

Calling TWI driver from multiple files using nrf_drv_twi

Hi, I use nrf51822 with SDK8.1, S110 and gcc with Makefile. I want to use nrf_drv_twi in both my main “.c” file as well as a library “.c” file that is included in the build. So in my main file I have:

#include <nrf_drv_twi.h>
//create TWI hardware object (see ../../../config/nrf_drv_config.h)
const nrf_drv_twi_t twi = NRF_DRV_TWI_INSTANCE(0);

...

int main(void)
{
    // Initialize.

...	
	nrf_drv_twi_init(&twi,NULL,NULL);
	nrf_drv_twi_enable(&twi);	
...
}

Then my main calls my library function, and the library function tries to use the same &twi like:

disp_success = nrf_drv_twi_tx(&twi,HW_I2C_DISPLAY_ADDRESS, data_buffer, 2, false);

but at complile time there is an error that 'twi is undeclared' in the library function. I can make the error go away if I add the following code to my library file and change the twi variable to twi2 in the library file:

#include <nrf_drv_twi.h>
const nrf_drv_twi_t twi2 = NRF_DRV_TWI_INSTANCE(0); 
disp_success = nrf_drv_twi_tx(&twi2,HW_I2C_DISPLAY_ADDRESS, data_buffer, 2, false);

But I expect this is not the proper way to use a TWI instance that I set up and initialized in the main file. For instance, if I decided to change the TWI instance from 0 to 1 in main, I would need to remember to also change it in my library file. So I would appreciate it if someone can advise the proper way to call the TWI in my second ".c" file after I have declared and enabled it in my main ".c" file. Thanks!!

  • This is a basic C question. Either pass the twi instance to your library functions as a parameter, ie change the function from

    void some_function( char some_data ); 
    

    to

    void some_function( nrf_drv_twi_t *twi_ptr, char some_data );
    

    or declare it in a header file marked extern

    extern nrf_drv_twi_t twi;
    

    and define it in one of the C files

    nrf_drv_twi_t twi;
    

    it's now an external symbol you can use from anywhere

Related