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 "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) {
  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. wm_i2c_scl_config(WM_IO_PA_01);
  19. wm_i2c_sda_config(WM_IO_PA_04);
  20. tls_i2c_init(speed);
  21. return 0;
  22. }
  23. int luat_i2c_close(int id) {
  24. return 0;
  25. }
  26. int luat_i2c_send(int id, int addr, void* buff, size_t len , uint8_t stop) {
  27. tls_i2c_write_byte(addr << 1, 1);
  28. if(WM_FAILED == tls_i2c_wait_ack())
  29. return -1;
  30. for (size_t i = 0; i < len; i++){
  31. tls_i2c_write_byte(((u8*)buff)[i], 0);
  32. if(WM_FAILED == tls_i2c_wait_ack())
  33. return -1;
  34. }
  35. if (stop){
  36. tls_i2c_stop();
  37. }
  38. return 0;
  39. }
  40. int luat_i2c_recv(int id, int addr, void* buff, size_t len) {
  41. tls_i2c_write_byte((addr << 1) + 1, 1);
  42. if(WM_FAILED == tls_i2c_wait_ack())
  43. return -1;
  44. if (len < 1)
  45. return -1;
  46. else if (len == 1){
  47. ((u8*)buff)[0] = tls_i2c_read_byte(0, 1);
  48. }else {
  49. for (size_t i = 0; i < len; i++){
  50. if (i == 0)
  51. ((u8*)buff)[i] = tls_i2c_read_byte(1, 0);
  52. else if (i == len - 1){
  53. ((u8*)buff)[i] = tls_i2c_read_byte(0, 1);
  54. break;
  55. }
  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. }