luat_i2c_air101.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "luat_base.h"
  2. #include "luat_i2c.h"
  3. #include "wm_include.h"
  4. #include "wm_i2c.h"
  5. #include <string.h>
  6. #include "wm_gpio_afsel.h"
  7. #define LUAT_LOG_TAG "luat.i2c"
  8. #include "luat_log.h"
  9. int luat_i2c_exist(int id) {
  10. return id == 0;
  11. }
  12. int luat_i2c_setup(int id, int speed, int slaveaddr) {
  13. //if (luat_i2c_exist(id) != 0) return -1;
  14. if (speed == 0)
  15. speed = 100 * 1000; // SLOW
  16. else if (speed == 1)
  17. speed = 400 * 1000; // FAST
  18. else if (speed == 2)
  19. speed = 800 * 1000; // SuperFast
  20. wm_i2c_scl_config(WM_IO_PA_01);
  21. wm_i2c_sda_config(WM_IO_PA_04);
  22. tls_i2c_init(speed);
  23. return 0;
  24. }
  25. int luat_ic2_close(int id) {
  26. // tls_i2c_stop();
  27. return 0;
  28. }
  29. int luat_i2c_send(int id, int addr, void* buff, size_t len) {
  30. tls_i2c_write_byte(addr << 1, 1);
  31. if(WM_FAILED == tls_i2c_wait_ack())
  32. return -1;
  33. for (size_t i = 0; i < len; i++)
  34. {
  35. tls_i2c_write_byte(((u8*)buff)[i], 0);
  36. if(WM_FAILED == tls_i2c_wait_ack())
  37. return -1;
  38. }
  39. tls_i2c_stop();
  40. return 0;
  41. }
  42. int luat_i2c_recv(int id, int addr, void* buff, size_t len) {
  43. tls_i2c_write_byte((addr << 1) + 1, 1);
  44. if(WM_FAILED == tls_i2c_wait_ack())
  45. return -1;
  46. if (len < 1)
  47. return -1;
  48. else if (len == 1){
  49. ((u8*)buff)[0] = tls_i2c_read_byte(0, 1);
  50. }else {
  51. for (size_t i = 0; i < len; i++){
  52. if (i == 0)
  53. ((u8*)buff)[i] = tls_i2c_read_byte(1, 0);
  54. else if (i == len - 1)
  55. ((u8*)buff)[i] = tls_i2c_read_byte(0, 1);
  56. else
  57. ((u8*)buff)[i] = tls_i2c_read_byte(1, 0);
  58. if(WM_FAILED == tls_i2c_wait_ack())
  59. break;
  60. }
  61. }
  62. return 0;
  63. }