luat_i2c_idf5.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "luat_base.h"
  2. #include "luat_i2c.h"
  3. #include "driver/i2c.h"
  4. #define LUAT_LOG_TAG "i2c"
  5. #include "luat_log.h"
  6. #define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/
  7. #define I2C_CHECK(i2cid) ((i2cid<0 || i2cid>=SOC_I2C_NUM) ? -1:0)
  8. int luat_i2c_exist(int id){
  9. return (I2C_CHECK(id)==0);
  10. }
  11. int luat_i2c_setup(int id, int speed, int slaveaddr){
  12. if (I2C_CHECK(id)){
  13. return -1;
  14. }
  15. i2c_config_t conf = {0};
  16. conf.mode = I2C_MODE_MASTER;
  17. conf.sda_io_num = 4;
  18. conf.scl_io_num = 5;
  19. conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
  20. conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
  21. if (speed == 0)
  22. conf.master.clk_speed = 100 * 1000;
  23. else if (speed == 1)
  24. conf.master.clk_speed = 400 * 1000;
  25. i2c_param_config(id, &conf);
  26. i2c_driver_install(id, conf.mode, 0, 0, 0);
  27. return 0;
  28. }
  29. int luat_i2c_close(int id){
  30. if (I2C_CHECK(id)){
  31. return -1;
  32. }
  33. i2c_driver_delete(id);
  34. return 0;
  35. }
  36. int luat_i2c_send(int id, int addr, void *buff, size_t len, uint8_t stop){
  37. if (I2C_CHECK(id)){
  38. return -1;
  39. }
  40. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  41. i2c_master_start(cmd);
  42. i2c_master_write_byte(cmd, addr << 1 | I2C_MASTER_WRITE, ACK_CHECK_EN);
  43. i2c_master_write(cmd, (const uint8_t *)buff, len, ACK_CHECK_EN);
  44. if (stop)
  45. i2c_master_stop(cmd);
  46. i2c_master_cmd_begin(id, cmd, 1000 / portTICK_PERIOD_MS);
  47. i2c_cmd_link_delete(cmd);
  48. return 0;
  49. }
  50. int luat_i2c_recv(int id, int addr, void *buff, size_t len){
  51. if (I2C_CHECK(id)){
  52. return -1;
  53. }
  54. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  55. i2c_master_start(cmd);
  56. i2c_master_write_byte(cmd, addr << 1 | I2C_MASTER_READ, ACK_CHECK_EN);
  57. i2c_master_read(cmd, (uint8_t *)buff, len, I2C_MASTER_LAST_NACK);
  58. i2c_master_stop(cmd);
  59. i2c_master_cmd_begin(id, cmd, 1000 / portTICK_PERIOD_MS);
  60. i2c_cmd_link_delete(cmd);
  61. return 0;
  62. }