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

Interfacing a Sensor Hub with TWI drivers?

Hi,

I am trying to adapt the read register function that use the TwoWire lib of Arduino in order to read a Sensor Hub Response Byte of a defined Host Command :

uint8_t readByte(uint8_t _familyByte, uint8_t _indexByte,\
                                           uint8_t _writeByte)
{

    uint8_t returnByte;
    uint8_t statusByte;

    _i2cPort->beginTransmission(_address);
    _i2cPort->write(_familyByte);
    _i2cPort->write(_indexByte);
    _i2cPort->write(_writeByte);
    _i2cPort->endTransmission();
    delay(CMD_DELAY);

    _i2cPort->requestFrom(_address, sizeof(returnByte) + sizeof(statusByte));
    statusByte = _i2cPort->read();
    if (statusByte)// SUCCESS (0x00)
        return statusByte; // Return the error, see: READ_STATUS_BYTE_VALUE 

    returnByte = _i2cPort->read();
    return returnByte; // If good then return the actual byte. 

}

to have a function that uses the nrf_dr_twi, like this: 

uint32_t nrf_drv_read_registers(uint8_t reg, uint8_t* p_data, uint32_t length)
{
    uint32_t err_code;
    uint32_t timeout = OXI_TWI_TIMEOUT;

    err_code = nrf_drv_twi_tx(&m_twi_instance, OXI_ADDRESS, &reg, 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_instance, OXI_ADDRESS, p_data, length);
    if (err_code != NRF_SUCCESS) return err_code;

    timeout = OXI_TWI_TIMEOUT;
    while ((!twi_rx_done) && --timeout) ;
    if (!timeout) return NRF_ERROR_TIMEOUT;
    twi_rx_done = false;

    return err_code;
}

Have you some ideas on how i can use the family and index byte of the Sensor Hub in order to retrieve the correct byte? 

Thank you very much in advance,

Kind regards

Parents
  • Hello Polimarte,

    Have you some ideas on how i can use the family and index byte of the Sensor Hub in order to retrieve the correct byte? 

    It is as @awneil says - we do not support Arduino, unfortunately.
    However, as awneil mentions, I would recommend reading the Sensor Hubs documentation, to figure out how to implement the interface.
    It will be easier for you to see what the Sensor Hub is expecting to receive from its datasheet, rather than reading it and translating it directly from an Arduino implementation.

    Best regards,
    Karl

  • Hi i'am sorry to have given a very vague question. I have understood a bit more, now i can describe well my problem, maybe.

    The read and write action on my sensor hub are described as:

    and i want to use the nrf_drv_tx and rx in order to implement these actions.

    If i have the function 

    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 
    )

    where

    [in] p_instance Pointer to the driver instance structure.
    [in] address Address of a specific slave device (only 7 LSB).
    [in] p_data Pointer to a transmit buffer.
    [in] length Number of bytes to send.
    [in] no_stop If set, the stop condition is not generated on the bus after the transfer has completed successfully (allowing for a repeated start in the next transfer).

    If i need to transmit a series if byte as for example only the Family and Index Byte in order to write,  would i need a buffer (p_data) as an array of dimension 2, able to store these two bytes? 

    and so for the reception if i want to retrieve the Status and the Response byte would i need another buffer with same dimension?

    Hope to hear you again and thanks for help me!

    polimarte

  • Hello Polimarte,

    Sorry for my late reply.

    polimarte said:
    i'am sorry to have given a very vague question.

    Do not worry, asking the right questions is an art in and of itself. :) 

    polimarte said:
    I have understood a bit more, now i can describe well my problem, maybe.

    Great! Let us see if we can't get to the bottom of this issue then.

    polimarte said:
    If i need to transmit a series if byte as for example only the Family and Index Byte in order to write,  would i need a buffer (p_data) as an array of dimension 2, able to store these two bytes? 

    With the information you have provided above, it seems to me that your device requires the start of a typical write to contain ADDR - FAMILY - INDEX - content.
    Based on this  I would recommend that you implement this as an array of commands in an array, which you then queue for transfer. You can do this by providing the NRFX_TWIM_XFER_DESC_TX macro with this array of commands, and then passing this this to the nrfx_twim_xfer function.

    Alternatively, if if you do not intend to use the nrfx_twim driver, you could take a look at how some other TWI master drivers for specific components have been implemented. You could see some examples of this in the SDK/components/driver_ext folder of the SDK.
    For example, you could see the external driver for the lis2dh12, located in SDK/components/drivers_ext/lis2dh12
    Especially, note how all the registers are defined in the internal file - this makes writing the driver a lot easier - and how there are functions for specific tasks. Implementing these config and control functions makes using your driver much easier.
    Even if you are planning to use the nrfx_twim driver, you could use the same general structure / approach from this driver, in your driver. 

    Lastly, I also recommend that you do a search on github for the specific component you are working with, if the internal registers file is not provided by the component manufacturer - chances are that someone already have transcribed all the register addresses for your particular component, which greatly reduce the time you have to sit and 'transcribe' these addressees from the datasheet directly.

    Best regards,
    Karl

  • Hi Karl, thanks for answering to my question.

    I ll use definitely the NRFX_TWIM drivers, but Why i cannot use the normal TWI drivers and define by myself the primary and secondary buffer (and merge them) each time? Is there some problem with communication?

    I have implemented the read and write function using nrf_drv_twi with rx and tx buffer, whose lengths depens on how many bytes i need each time. Here an Example of Write byte function, Does it make any sense to you?

    uint8_t writeByte( uint8_t _familyByte, uint8_t _indexByte, uint8_t _writeByte)
    {
    
            uint32_t err_code;
            
            uint32_t timeout = TWI_TIMEOUT;
            uint8_t StatusByte=0;     
           
            uint8_t lenght = sizeof(_familyByte) + sizeof(_indexByte) + sizeof(_writeByte);
    
            uint8_t rx_buffer;
    
            uint8_t tx_buffer[] = {_familyByte, _indexByte, _writeByte};   //cazzo devo fare qua 
    
            err_code = nrf_drv_twi_tx(&m_twi_instance, address, tx_buffer, lenght, true);
            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_instance, address, &rx_buffer, sizeof(rx_buffer));
            if (err_code != NRF_SUCCESS) return err_code;
    
            timeout = OXI_TWI_TIMEOUT;
            while ((!twi_rx_done) && --timeout) ;
            if (!timeout) return NRF_ERROR_TIMEOUT;
            twi_rx_done = false;
    
            StatusByte = rx_buffer;
    
            return StatusByte;
          
        }

    Sorry this can be a stupid question but i have just started to study the TWI config and to use nordic components.

    Thanks a lot,

    polimarte

  • Hello Polimarte,

    polimarte said:
    thanks for answering to my question.

    No problem at all, I am happy to help!

    polimarte said:
    Sorry this can be a stupid question but i have just started to study the TWI config and to use nordic components.

    No need to apologize - we were all new to these things at one point or another. It is great that you are familiarizing with the TWI protocol and the drivers and libraries supplied with the SDK on your own! The forum is here whenever you should encounter any issues or questions with any of these, there is no harm in asking! :)

    polimarte said:
    I ll use definitely the NRFX_TWIM drivers, but Why i cannot use the normal TWI drivers and define by myself the primary and secondary buffer (and merge them) each time? Is there some problem with communication?

    I am not sure I understand what you mean when you ask why you can not use the "normal TWI drivers" - are you here referring to the legacy nrf_drv_twi_* driver?
    As you can see in the NRFX_TWIM_XFER_DESC_TX documentation, you may very well set up more than 1 byte for TX with this description. As you can see from the nrfx_twim_xfer function documentation you may use the different flag option to initiate different types of transfers - such as the NRFX_TWIM_FLAG_TX_NO_STOP flag, to signal that the TX transfer is not done yet.

    If you are going to do a TXRX ( or another of the transfer options ) sending ( which might require the secondary buffer that you mention ), you should instead use the NRFX_TWIM_XFER_DESC_TXRX. 

    polimarte said:
    I have implemented the read and write function using nrf_drv_twi with rx and tx buffer, whose lengths depens on how many bytes i need each time. Here an Example of Write byte function, Does it make any sense to you?

    You have only shared your writeByte implementation, so I can not say anything about your function for reading.
    Regarding the writeByte function code you shared above, I have the following comments:

    - The return type of your function is incorrect since you sometimes intend to return error codes, such as those possibly returned by nrf_drv_twi_tx with is an ret_code_t which is uint32_t type.

    - You are also mixing what you might be returning, you should not do this as it will make it very hard to use the functions return value ( you will not know if the function returns an error or the status byte). Instead, you should provide the function with a buffer, in which it may place the statusbyte, or whatever else it outputs.

    - Your usage of the timeout might not be as intended, since it will run down the while using CPU cycles, not ms or us or anything "human readable". So, the timeout feature might not work quite as you have intended, but this is just a guess from my side, since I neither know the value nor calculation used to disern TWI_TIMEOUT.

    - Your rx_buffer is used as an array, but is not declared and instantiated as such.

    - You are returning if the result of nrf_drv_twi_tx is != NRF_SUCCESS, this is good. But, since you also might be returning the status register, I am not sure that you are passing the returned value of writeByte through an APP_ERROR_CHECK. Do you do this?

    - I am guessing that the twi_rx_done and twi_tx_done variables are set to true in the twi event handler, is this correct?

    - You are not declaring "StatusByte" at the end, and you are setting it equal to what I am guessing should have been a pointer to an uint8_t array ( which it is not ).

    - Broadly speaking, it also seems that you are not following a particular convention with your variable and function naming, and I highly recommend doing so. For example, you sometimes use Pascal, sometimes camel, and you also use underscores in front of your function parameters - you should be consistent here, and you should not use underscores as a prefix for variable names.

    - Your call to nrf_drv_twi_tx looks all right, if your "address" parameter is as intended. I am guessing that you forgot to replace it with the _writeByte parameter.

    - Your call to nrf_drv_twi_rx also looks ok, but here you are again passing the variable "address" which I think might be incorrect ( but I do not know what address actually points to, so I might be wrong about this ).

    I do not mean to sound crass, I am just trying to help.
    Please take a look at the above comments, and let me know if you should have any questions.
    If you review your code with these comments in mind, feel free to share the updated version here, and I will take a look at it again! :) 


    Best regards,
    Karl

  • Thanks a lot Karl!!

    I understand that there are several errors and i expected that so thanks to help me!! 

    My goal is to adapt code originally made for arduino in c++, using keil uvision, that's probably the reason why there is such confusion about the conventions. 

    Unfortunately i am a total beginner to embedded systems and i have to admit that i am lacking of some important basics here.I am sure that i ll understand a bit more now with your hints.

    I ll ask help again, hope to present a more reasonable code in the future. 

    polimarte

  • polimarte said:
    Thanks a lot Karl!!

    No problem at all, Polimarte!

    polimarte said:
    I understand that there are several errors and i expected that so thanks to help me!! 

    I am glad to hear that you took it this way, and that my comments was well received! :)  

    polimarte said:
    My goal is to adapt code originally made for arduino in c++, using keil uvision, that's probably the reason why there is such confusion about the conventions. 

    This is a clear, and achievable goal, great! For starters, I would recommend adopting a similar coding style as demonstrated in the SDK examples, if possible.
    Since the particular variable and function names wont matter following compilation, there is no reason not to write out descriptive names for each variable and function. This will also make it much easier for you to 'get back into the code' if you should take a break at any time, or come back to the code after having worked on another project for a while.

    polimarte said:
    Unfortunately i am a total beginner to embedded systems and i have to admit that i am lacking of some important basics here.I am sure that i ll understand a bit more now with your hints.

    No worries, we all were new to this at some point, and the best way to get better is to keep trying! I will say this though, Nordic SoC's might not be the easiest starting place to learn embedded programming. Mainly, this is because our SoC's are pretty high-end, with a lot of customizable functionality, configurations, and optimizations.
    This makes the learning curve for developing with out SoC's pretty steep - but because of this, once you get the hang of it you will have plenty of tools and functionality at your disposal!

    It is great that you are starting out with the TWI drivers, and are working on how to interface with a sensor. This is a good way to start.
    Especially the BLE parts of the nRF5 SDK examples' code might seem daunting when you first come across it, but once you get familiar with it it will be just as straight forward as the TWI drivers!
    Please do not hesitate to ask, if you should get stuck anywhere in your project.

    polimarte said:
    I ll ask help again, hope to present a more reasonable code in the future. 

    Great! That sounds like a good plan, I look forward to hearing how you progress with your project.

    Good luck with your development!

    Best regards,
    Karl

Reply
  • polimarte said:
    Thanks a lot Karl!!

    No problem at all, Polimarte!

    polimarte said:
    I understand that there are several errors and i expected that so thanks to help me!! 

    I am glad to hear that you took it this way, and that my comments was well received! :)  

    polimarte said:
    My goal is to adapt code originally made for arduino in c++, using keil uvision, that's probably the reason why there is such confusion about the conventions. 

    This is a clear, and achievable goal, great! For starters, I would recommend adopting a similar coding style as demonstrated in the SDK examples, if possible.
    Since the particular variable and function names wont matter following compilation, there is no reason not to write out descriptive names for each variable and function. This will also make it much easier for you to 'get back into the code' if you should take a break at any time, or come back to the code after having worked on another project for a while.

    polimarte said:
    Unfortunately i am a total beginner to embedded systems and i have to admit that i am lacking of some important basics here.I am sure that i ll understand a bit more now with your hints.

    No worries, we all were new to this at some point, and the best way to get better is to keep trying! I will say this though, Nordic SoC's might not be the easiest starting place to learn embedded programming. Mainly, this is because our SoC's are pretty high-end, with a lot of customizable functionality, configurations, and optimizations.
    This makes the learning curve for developing with out SoC's pretty steep - but because of this, once you get the hang of it you will have plenty of tools and functionality at your disposal!

    It is great that you are starting out with the TWI drivers, and are working on how to interface with a sensor. This is a good way to start.
    Especially the BLE parts of the nRF5 SDK examples' code might seem daunting when you first come across it, but once you get familiar with it it will be just as straight forward as the TWI drivers!
    Please do not hesitate to ask, if you should get stuck anywhere in your project.

    polimarte said:
    I ll ask help again, hope to present a more reasonable code in the future. 

    Great! That sounds like a good plan, I look forward to hearing how you progress with your project.

    Good luck with your development!

    Best regards,
    Karl

Children
  • Nordic SoC's might not be the easiest starting place to learn embedded programming. Mainly, this is because our SoC's are pretty high-end, with a lot of customizable functionality

    Absolutely! The fact that the nRF52 is not just a microcontroller but also integrates a complete radio systems adds a whole lot of complication.

    (not picking on Nordic here - the same would apply to any comparable SoC)

    I would strongly suggest that you spend some time on a simpler, "conventional" microcontroller to learn the basics of embedded development.

    eg, as noted above, I2C comms and  your Sensor Hub are not at all related to BLE - that's just an unnecessary extra complication at the learning stage.

    Here are some general beginner "getting started" tips for microcontrollers:

    https://www.avrfreaks.net/comment/2079906#comment-2079906

  • Hi awneil thanks for the hint!

    Unfortunately I will have to use ANT modules in a following part of my project, but i have some source code that can be very helpful to me when i ll arrive at that point. I have little experience with ATMega and STmicrocontoller but you are right this SoC's are not easy at all. Thanks to the excellent Nordic costumer service I am sure i ll made it. 

    polimarte

  • Hi Karl!

    I followed your hints and i modified my code, hope to present a better solution now. What i wanted to do is to modify the read and write function for Arduino, that use the library Wire.h to implement the transactions TXRX. The read function of the Arduino code is in my original question. The write function is implemented in this way: 

    uint8_t SparkFun_Bio_Sensor_Hub::writeByte(uint8_t _familyByte,uint8_t _indexByte,uint8_t _writeByte)
    {
    
      _i2cPort->beginTransmission(_address);     
      _i2cPort->write(_familyByte);    
      _i2cPort->write(_indexByte);    
      _i2cPort->write(_writeByte); 
      _i2cPort->endTransmission(); 
      delay(CMD_DELAY); 
    
      // Status Byte, success or no? 0x00 is a successful transmit
      _i2cPort->requestFrom(_address, static_cast<uint8_t>(1)); 
      uint8_t statusByte = _i2cPort->read(); 
      return statusByte; 
    
    }

    and i have used the NRFX_TWIM_XFER_DESC_TXRX in this way for Read:

    uint8_t readByte_WB(uint8_t familyByte, uint8_t indexByte, uint8_t writeByte)
    {
    
    		nrfx_err_t err_code
    		uint8_t StatusByte;    
            uint8_t ReturnByte;
       
            uint8_t rx_buffer[2];
    		size_t rx_lenght =2;
    
    		uint8_t tx_buffer[] = {familyByte, indexByte, writeByte};    
    		size_t tx_lenght = sizeof(familyByte) + sizeof(indexByte) + sizeof(writeByte);
    
    		nrfx_twim_xfer_desc_t transferType = NRFX_TWIM_XFER_DESC_TXRX(address, tx_buffer, tx_lenght, rx_buffer,rx_lenght);
    		err_code = nrfx_twim_xfer(&twim_instance, &transferType, 0);
    		NRF_LOG_INFO("Xfer error code: %s \n", errorcode_printer(err_code));
    
        
    		StatusByte = int(rx_buffer[0]);
            NRF_LOG_INFO("Status Byte: %lu \n",StatusByte); //0x00 for SUCCESS
        
    		ReturnByte = rx_buffer[1];  
    		return ReturnByte;
    }

    and for write: 

    uint8_t writeByte( uint8_t familyByte, uint8_t indexByte, uint8_t writeByte)
    {
    
    		nrfx_err_t err_code
    		
    		uint8_t StatusByte;    
        
    		uint8_t rx_buffer[1];
    		size_t rx_lenght =1;
    
    		uint8_t tx_buffer[] = {familyByte, indexByte, writeByte};    
    		size_t tx_lenght = sizeof(familyByte) + sizeof(indexByte) + sizeof(writeByte);
    
    		nrfx_twim_xfer_desc_t transferType = NRFX_TWIM_XFER_DESC_TXRX(address, tx_buffer, tx_lenght, rx_buffer,rx_lenght);
    		err_code = nrfx_twim_xfer(&twim_instance, &transferType, 0);
    		NRF_LOG_INFO("Xfer error code: %s \n", errorcode_printer(err_code));
    
    		StatusByte = rx_buffer[0];
            
            return StatusByte;
    
    }

    I understand that formally it would be more correct use pointers in order to retrieve the bytes with buffers but i need a non void return function for my adaptation to the original code. I use the StatusByte only to check the SUCCESS the TXRX and eventually i return the unsigned integer whose Byte length is predetermined (the bytes that follow the StatusByte). This Write function only write Family, Index and Write Byte, checking the StatusByte. The Read function in this case is used only to retrieve the first byte after the StatusByte which value luckly will be 0x00 (SUCCESS Transmission). I made other similar functions (following the method of the Arduino Code) in case of the need to retrieve different byte lengths (uint16_t,uint32_t..) or to fill arrays passed as input.

    It is the right way for the implementation or i am missing something?

    Thanks to help me again!

    polimarte

  • Hello Polimarte,

    Sorry for my late reply, I was out of office for some days.

    polimarte said:
    Thanks to the excellent Nordic costumer service I am sure i ll made it.

    I am happy to hear you say that, thank you!

    polimarte said:
    I followed your hints and i modified my code, hope to present a better solution now. What i wanted to do is to modify the read and write function for Arduino, that use the library Wire.h to implement the transactions TXRX. The read function of the Arduino code is in my original question. The write function is implemented in this way:

    I am glad to see the changes you have made to your functions, they are huge improvements!

    I will include some comments below:

    You are absolutely on the right track here, this looks a lot better!

    polimarte said:
    I understand that formally it would be more correct use pointers in order to retrieve the bytes with buffers but i need a non void return function for my adaptation to the original code.

    I understand, and I see that you function still returns the StatusByte instead of the err_code. I assume this is done for compatibility with other ported functions from the Arduino Library.
    However, I would suggest that you include an APP_ERROR_CHECK on the err_code returned from nrfx_twim_xfer, to catch any errors being generated.

    I also notice your use of magic numbers for the size/length of rx_buffer - I would advise against doing this for any piece of code. Preferably, if you have a static array length that your twim transactions always will return, then it is preferable that you create a define for this, for increased readability.

    Other than that, this use of the nrfx_twim driver seems fine!

    However, I am not sure that this will behave as expected, since when you are using the TXRX transfer description there is no STOP condition generated in between the TX and RX - this is not as shown in the illustration you posted earlier. From the illustration, it seems very much like you will need a stop condition before doing the next operation.
    So, you might have to do this in separate transfers after all ( first completing a TX of length three, then completing a RX of length two )  - Sorry that I did not catch this when I recommended you the TXRX description, my mistake.

    polimarte said:
    It is the right way for the implementation or i am missing something?

    Your usage of the nrfx_twim driver seems to be implemented correctly now.
    What are you seeing when you run this code - are you getting any errors, or unexpected behavior?

    polimarte said:
    I made other similar functions (following the method of the Arduino Code) in case of the need to retrieve different byte lengths (uint16_t,uint32_t..) or to fill arrays passed as input.

    Make sure to give these functions clear and descriptive names, to differentiate them from each other.

    Best regards,
    Karl

  • Hi my dear Karl! 

    Thanks for helping me again!

    However, I am not sure that this will behave as expected, since when you are using the TXRX transfer description there is no STOP condition generated in between the TX and RX - this is not as shown in the illustration you posted earlier.

    I used the TX and RX transfers separately in this way:

    uint8_t readByte_WB(uint8_t familyByte, uint8_t indexByte, uint8_t writeByte)
    {
    
    		nrfx_err_t err_code;
    		uint8_t StatusByte;    
            uint8_t ReturnByte;
       
            uint8_t rx_buffer[2];
    		size_t rx_lenght =2;
    
    		uint8_t tx_buffer[] = {familyByte, indexByte, writeByte};    
    		size_t tx_lenght = sizeof(familyByte) + sizeof(indexByte) + sizeof(writeByte);
    
    		nrfx_twim_xfer_desc_t tx_xfer = NRFX_TWIM_XFER_DESC_TX(address, tx_buffer, tx_lenght);
    		err_code = nrfx_twim_xfer(&twim_instance, &tx_xfer, 0);
    		APP_ERROR_CHECK(err_code);
    		
    		nrfx_twim_xfer_desc_t rx_xfer = NRFX_TWIM_XFER_DESC_RX(address, rx_buffer, rx_lenght);
    		err_code = nrfx_twim_xfer(&twim_instance, &rx_xfer, 0);
    		APP_ERROR_CHECK(err_code);
        
    		StatusByte = rx_buffer[0];
            NRF_LOG_INFO("Status Byte: %lu \n",StatusByte); //0x00 for SUCCESS
        
    		ReturnByte = rx_buffer[1];  
    		return ReturnByte;
    }

    Can be a good solution for the read function? the write one it ll be very similar following this logic.

    Unfortunately i am stack with other ( many) errors in a previous part of my code and i cannot verify the correctness of these functions, but i ll do that very soon and i ll let you know if there are some problems!

    I just want to know if the logic behind this is correct, than i ll debug this part of the code properly.

    if you have a static array length that your twim transactions always will return, then it is preferable that you create a define for this, for increased readability.

    I will do that, thanks for the advice!

    thanks, 

    polimarte

Related