I2C.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* --------------------------- (C) COPYRIGHT 2021 Fortiortech ShenZhen -----------------------------
  2. File Name : I2C.c
  3. Author : Fortiortech Appliction Team
  4. Version : V1.0
  5. Date : 2021-04-11
  6. Description : This file contains .C file function used for Motor Control.
  7. ----------------------------------------------------------------------------------------------------
  8. All Rights Reserved
  9. ------------------------------------------------------------------------------------------------- */
  10. #include <MyProject.h>
  11. /*
  12. void I2C_Init_Master(void)
  13. {
  14. SetBit(P0_PU , P00);
  15. SetBit(P0_PU , P01);
  16. // I2C initial
  17. SetBit(I2C_CR , I2CMS); //主从模式选择 0-->Slave Mode 1-->Host Mode
  18. ClrBit(I2C_CR , I2CSPD1); //00-->100kHz 01-->400kHz
  19. SetBit(I2C_CR , I2CSPD0); //10-->1MHz 11-->RSV
  20. ClrBit(I2C_CR , I2CIE); //中断使能 0-->Disable 1-->Enable
  21. I2C_ID = 0xD0;
  22. SetBit(I2C_ID , GC); //广播呼叫使能 0-->Disable 1-->Enable
  23. SetBit(I2C_CR , I2CEN); //I2C使能 0-->Disable 1-->Enable
  24. }
  25. void I2C_ID_Start(bool rw)
  26. {
  27. if(rw)
  28. SetBit(I2C_SR , DMOD);
  29. else
  30. ClrBit(I2C_SR , DMOD);
  31. SetBit(I2C_SR , I2CSTA); //1-->发送START或RESTART和地址字节
  32. while(!ReadBit(I2C_SR , STR));
  33. ClrBit(I2C_SR , STR);
  34. }
  35. void I2C_Addr_Write(unsigned char addr,unsigned char wdata)
  36. {
  37. I2C_ID_Start(0); // ID write
  38. I2C_DR = addr; // Slave reg addr.
  39. while(!ReadBit(I2C_SR , STR));
  40. ClrBit(I2C_SR , STR);
  41. I2C_DR = wdata; // Slave reg data.
  42. while(!ReadBit(I2C_SR , STR));
  43. ClrBit(I2C_SR , STR);
  44. SetBit(I2C_SR , I2CSTP); //1-->发送STOP
  45. }
  46. unsigned char I2C_Addr_Read(char addr)
  47. {
  48. unsigned char rd_data;
  49. //write process
  50. I2C_ID_Start(0); // write+ID
  51. I2C_DR = addr; // write reg. addr
  52. while(!ReadBit(I2C_SR , STR));
  53. ClrBit(I2C_SR , STR);
  54. // SetBit(I2C_SR , I2CSTP); //1-->发送STOP
  55. //read process
  56. I2C_ID_Start(1); // read+ID
  57. while(!ReadBit(I2C_SR , STR));
  58. ClrBit(I2C_SR , STR);
  59. rd_data = (unsigned char)(I2C_DR); // read data
  60. SetBit(I2C_SR , NACK); //第9位发送NACK
  61. SetBit(I2C_SR , I2CSTP); //1-->发送STOP
  62. return(rd_data);
  63. }*/