Recently I was doing some transplant code stuff from stm32 to Nrf52833 for the motion sensor-LIS2DH12
Generally, the way is just to implement the C source code, and change the stm32's HAL function to NRF's HAL function.
First step: Validate the source code (example code)
Setup the stm32 and try to read the data from LIS2DH12
It works good, the terminal shows the data from the motion sensor
It's time to transplant the code to nrf
- The address is 0x33(Read 0011001"1", Write 0011001"0" )
- It's the HAL function of the stm32 iic below
So we noticed that here's the nrf twi_tx(iic_write), so naturally, I just set the address as 0x33.
RUN the code
if the nrf_drv_twi_tx(........................) succeeds to send stuff and get the ACK from the slave, then the return value will be "1".
Result: err_code == 2 (Doesn't send successfully)
Check by the logic analyzer
- After decoding, the address request is 0x33, Does it looks good?
- But it still doesn't received the ACK signall.
Check the source code and the datasheet
Everything looks fine, but why it doesn't get the reply?
After carefully checking that one line by line, still don't feel anything weird!!! :(
So let's probe the stm32's iic signal and compare it to the current one.
!!! The address is 0x19!
Finally, we found that if we compare the binary one by one, then we will discover that 0x19 is just 00110011"1" without "1"(Read)
why it's that so confusing?
Two HAL has different operations, nrf_Version uses the function name to clarify the LSB
nrf_drv_twi_tx(&m_twi, address, tx_buf, sizeof(0x33+0x55),false);
nrf_drv_twi_rx(&m_twi, address, &sample_data, sizeof(sample_data));
the _rx and _tx are being used to define the LSB("0"Write/"1"Read)
We need to do the >> calculation manually
Device ID : 0x33 >>1 == 0x19(without LSB)
Address = 0x19
Anyway, we got this fix then.
Conclusion:
Actually, the root cause is the unusual IIC HAL format edited by Nordic SDK. (It sucks). The good way of coding for IIC is like the way Stm32's source code does.
- It's should refer to the datasheet format(ADD+R.W as one byte)
- Do the bit shift calculation inside the function