I2C.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /********************************************************************************
  2. **** Copyright (C), 2019, Fortior Technology Co., Ltd. ****
  3. ********************************************************************************
  4. * File Name : I2C.c
  5. * Author : Bruce HW&RD
  6. * Date : 2019-03-27
  7. * Description : .C file function description
  8. * Version : 1.0
  9. * Function List :
  10. *
  11. * Record :
  12. * 1.Date : 2019-03-27
  13. * Author : Bruce HW&RD
  14. * Modification: Created file
  15. ********************************************************************************/
  16. #include "I2C.h"
  17. /*
  18. void I2C_Init_Master(void)
  19. {
  20. SetBit(P0_PU , P00);
  21. SetBit(P0_PU , P01);
  22. // I2C initial
  23. SetBit(I2C_CR , I2CMS); //主从模式选择 0-->Slave Mode 1-->Host Mode
  24. ClrBit(I2C_CR , I2CSPD1); //00-->100kHz 01-->400kHz
  25. SetBit(I2C_CR , I2CSPD0); //10-->1MHz 11-->RSV
  26. ClrBit(I2C_CR , I2CIE); //中断使能 0-->Disable 1-->Enable
  27. I2C_ID = 0xD0;
  28. SetBit(I2C_ID , GC); //广播呼叫使能 0-->Disable 1-->Enable
  29. SetBit(I2C_CR , I2CEN); //I2C使能 0-->Disable 1-->Enable
  30. }
  31. void I2C_ID_Start(bool rw)
  32. {
  33. if(rw)
  34. SetBit(I2C_SR , DMOD);
  35. else
  36. ClrBit(I2C_SR , DMOD);
  37. SetBit(I2C_SR , I2CSTA); //1-->发送START或RESTART和地址字节
  38. while(!ReadBit(I2C_SR , STR));
  39. ClrBit(I2C_SR , STR);
  40. }
  41. void I2C_Addr_Write(unsigned char addr,unsigned char wdata)
  42. {
  43. I2C_ID_Start(0); // ID write
  44. I2C_DR = addr; // Slave reg addr.
  45. while(!ReadBit(I2C_SR , STR));
  46. ClrBit(I2C_SR , STR);
  47. I2C_DR = wdata; // Slave reg data.
  48. while(!ReadBit(I2C_SR , STR));
  49. ClrBit(I2C_SR , STR);
  50. SetBit(I2C_SR , I2CSTP); //1-->发送STOP
  51. }
  52. unsigned char I2C_Addr_Read(char addr)
  53. {
  54. unsigned char rd_data;
  55. //write process
  56. I2C_ID_Start(0); // write+ID
  57. I2C_DR = addr; // write reg. addr
  58. while(!ReadBit(I2C_SR , STR));
  59. ClrBit(I2C_SR , STR);
  60. // SetBit(I2C_SR , I2CSTP); //1-->发送STOP
  61. //read process
  62. I2C_ID_Start(1); // read+ID
  63. while(!ReadBit(I2C_SR , STR));
  64. ClrBit(I2C_SR , STR);
  65. rd_data = (unsigned char)(I2C_DR); // read data
  66. SetBit(I2C_SR , NACK); //第9位发送NACK
  67. SetBit(I2C_SR , I2CSTP); //1-->发送STOP
  68. return(rd_data);
  69. }*/