i2c.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "i2c.h"
  2. #include "system.h"
  3. void I2C_Init(I2C_TypeDef *i2c, uint32_t frequency)
  4. {
  5. uint16_t prescaler = SYS_GetPclkFreq() / frequency / 5 - 1;
  6. I2C_SetPrescaler(i2c, prescaler);
  7. }
  8. void I2C_StartSend(I2C_TypeDef *i2c, uint8_t addr)
  9. {
  10. I2C_WaitForTransfer(i2c); // Make sure no transfer is in progress
  11. I2C_SetTxData(i2c, I2C_WR_ADDR(addr));
  12. I2C_SetCmd(i2c, I2C_CR_WR | I2C_CR_STA);
  13. }
  14. void I2C_SendData(I2C_TypeDef *i2c, uint8_t data)
  15. {
  16. I2C_WaitForTransfer(i2c);
  17. I2C_SetTxData(i2c, data);
  18. I2C_SetCmd(i2c, I2C_CR_WR);
  19. }
  20. void I2C_StopSend(I2C_TypeDef *i2c, uint8_t data)
  21. {
  22. I2C_WaitForTransfer(i2c);
  23. I2C_SetTxData(i2c, data);
  24. I2C_SetCmd(i2c, I2C_CR_WR | I2C_CR_STO);
  25. }
  26. void I2C_StartReceive(I2C_TypeDef *i2c, uint8_t addr)
  27. {
  28. I2C_WaitForTransfer(i2c);
  29. I2C_SetTxData(i2c, I2C_RD_ADDR(addr));
  30. I2C_SetCmd(i2c, I2C_CR_WR | I2C_CR_STA);
  31. }
  32. // Send the receive commands. Data can be read from RXR after TIP bit is cleared
  33. void I2C_ReceiveData(I2C_TypeDef *i2c)
  34. {
  35. I2C_WaitForTransfer(i2c);
  36. I2C_SetCmd(i2c, I2C_CR_RD);
  37. }
  38. void I2C_StopReceive(I2C_TypeDef *i2c)
  39. {
  40. I2C_WaitForTransfer(i2c);
  41. I2C_SetCmd(i2c, I2C_CR_RD | I2C_CR_STO | I2C_CR_NACK);
  42. }