2016年2月2日 星期二

nRF51x22 I2C Master Driver

1. 最近開始接觸nRF51x22系列的東西, 真的是有點小複雜, 因此就把最近弄好的一些東西先簡
    易備份在Blogger上, 以方便之後有需要的時候容易能馬上使用.

2. 使用I2C Master Driver之前, 必須要先include以下的c & h file, 才能正常使用, 檔名及路徑如
    下:

  • 測試的版本皆是在nRF51_SDK_9.0.0_2e23562.zip這個sdk版本下進行測試的.
  • twi_hw_master.c:
    \components\drivers_nrf\twi_master\incubated\
  • twi_master.h:
    \components\drivers_nrf\twi_master\incubated\
  • twi_master_config.h:
    \components\drivers_nrf\twi_master\incubated\config\
3. 接著就是使用底下的i2c.c & i2c.h 這兩個檔案就可以使用了.

i2c.c:
--------------------------------------------------------------------------------------------------------------------------
  1. #include "i2c.h"
  2.  
  3. void I2C_Master_Init(void)
  4. {
  5. twi_master_init();
  6. }
  7.  
  8. int I2C_Write(uint8_t DeviceAddr, uint8_t RegAddr, uint8_t* pBuffer, uint16_t NumByteToWrite)
  9. {
  10. #define i2c_write_data_len 6
  11. uint8_t w2_data[i2c_write_data_len+1], i;
  12.  
  13. w2_data[0] = RegAddr;
  14. for ( i = 0 ; i < NumByteToWrite ; i++ ) {
  15. w2_data[i +1] = pBuffer[i];
  16. }
  17.  
  18. if(twi_master_transfer(DeviceAddr,w2_data,NumByteToWrite+1,TWI_ISSUE_STOP) == false)
  19. return -1;
  20.  
  21. return 0;
  22. }
  23.  
  24. int I2C_Read(uint8_t DeviceAddr, uint8_t RegAddr, uint8_t* pBuffer, uint16_t NumByteToRead)
  25. {
  26. if(twi_master_transfer(DeviceAddr, &RegAddr, 1, TWI_DONT_ISSUE_STOP) == false)
  27. return -1;
  28.  
  29. if(twi_master_transfer(DeviceAddr|TWI_READ_BIT, pBuffer, NumByteToRead, TWI_ISSUE_STOP) == false)
  30. return -1;
  31. return 0;
  32. }
  33.  

i2c.h:
--------------------------------------------------------------------------------------------------------------------------
  1. #include "twi_master.h"
  2.  
  3. void I2C_Master_Init(void);
  4. int I2C_Write(uint8_t DeviceAddr, uint8_t RegAddr, uint8_t* pBuffer, uint16_t NumByteToWrite);
  5. int I2C_Read(uint8_t DeviceAddr, uint8_t RegAddr, uint8_t* pBuffer, uint16_t NumByteToRead);
  6.  
4. 調整i2c speed的地方在twi_master_init()裡面:

TWI_FREQUENCY_FREQUENCY_K400 = 400KHz
TWI_FREQUENCY_FREQUENCY_K250 = 250KHz
TWI_FREQUENCY_FREQUENCY_K100 = 100KHz



5. 調整i2c gpio pin的地方在twi_master_config.h:

    SCL = 1U = GPIO1.

    SDA = 3U = GPIO3.



沒有留言:

張貼留言