i2c.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef I2C_H
  2. #define I2C_H
  3. #include "common.h"
  4. #include "atomic.h"
  5. #include "io.h"
  6. static inline uint32_t i2c_wait(void)
  7. {
  8. waitfor(I2C_IRQ);
  9. }
  10. static inline void i2c_send_byte(uint8_t byte, uint8_t ctl)
  11. {
  12. i2c_wait();
  13. I2C_WDATA = (byte << 8) | I2C_NAK | ctl;
  14. }
  15. static inline uint32_t i2c_data_status(void)
  16. {
  17. i2c_wait();
  18. return I2C_RDATA;
  19. }
  20. static inline bool i2c_acked(void)
  21. {
  22. return !(i2c_data_status() & I2C_NAK);
  23. }
  24. static inline uint8_t i2c_recv_byte(uint8_t ctl)
  25. {
  26. uint32_t rdata;
  27. i2c_wait();
  28. I2C_WDATA = (~0xff) | ctl;
  29. return i2c_data_status() >> 8;
  30. }
  31. static inline void i2c_set_speed(unsigned int khz)
  32. {
  33. I2C_DIVISOR = ((CPU_HZ/4000)-1)/khz;
  34. }
  35. extern volatile bool _i2c_locked;
  36. static bool i2c_lock(void)
  37. {
  38. return !atomic_xchg(_i2c_locked, true);
  39. }
  40. static void i2c_unlock(void)
  41. {
  42. _i2c_locked = false;
  43. }
  44. #define I2C_ERR_BUSY (-1)
  45. #define I2C_ERR_CONFLICT (-2)
  46. #define I2C_ERR_NAK (-3)
  47. #define I2C_ERR_IO (-4)
  48. #define I2C_ERR_STUCK (-5)
  49. #define I2C_ERR_NODEV (-6)
  50. extern int i2c_send(uint8_t addr, const void *data, size_t len);
  51. extern int i2c_recv(uint8_t addr, void *data, size_t len);
  52. extern int i2c_send_recv(uint8_t addr, const void *odata, size_t olen,
  53. void *idata, size_t ilen);
  54. #endif /* I2C_H */