i2c_tools.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "luat_base.h"
  2. #include "i2c_utils.h"
  3. #include "luat_mem.h"
  4. #define LUAT_LOG_TAG "i2c tools"
  5. #include "luat_log.h"
  6. void i2c_tools(const char * data,size_t len){
  7. char *i2c_tools_data = (char *)luat_heap_malloc(len-8);
  8. memset(i2c_tools_data, 0, len-8); // 确保填充为0
  9. memcpy(i2c_tools_data, data+9, len-9);
  10. char *command = strtok(i2c_tools_data, " ");
  11. if (memcmp("send", command, 4) == 0){
  12. int i2c_id = atoi(strtok(NULL, " "));
  13. i2c_init(i2c_id,0);
  14. uint8_t address = strtonum(strtok(NULL, " "));
  15. uint8_t send_buff[16];
  16. uint8_t len = 0;
  17. while (1){
  18. char* buff = strtok(NULL, " ");
  19. if (buff == NULL)
  20. break;
  21. send_buff[len] = strtonum(buff);
  22. len++;
  23. }
  24. if(i2c_write(address, send_buff, len)!=1){
  25. LLOGI("[i2c] write to 0x%02X failed", address);
  26. }
  27. }else if(memcmp("recv",command,4) == 0){
  28. int i2c_id = atoi(strtok(NULL, " "));
  29. i2c_init(i2c_id,0);
  30. uint8_t address = strtonum(strtok(NULL, " "));
  31. uint8_t reg = strtonum(strtok(NULL, " "));
  32. uint8_t len = atoi(strtok(NULL, " "));
  33. if (len == 0)len = 1;
  34. uint8_t *buffer = (uint8_t *)luat_heap_malloc(len);
  35. memset(buffer, 0, len); // 确保填充为0
  36. if( i2c_read(address, reg,buffer,len)!=1){
  37. char buff[64] = {0};
  38. sprintf_(buff, "[ ");
  39. for(uint8_t i = 0; i < len; i++){
  40. sprintf_(buff + 2 + i *4, "0x%02X", buffer[i]);
  41. if(i != (len-1)){
  42. printf(", ");
  43. }
  44. }
  45. sprintf_(buff + 2 + 4*len, " ]");
  46. LLOGD("%s", buff);
  47. }
  48. luat_heap_free(buffer);
  49. }else if(memcmp("scan",command,4) == 0){
  50. int i2c_id = atoi(strtok(NULL, " "));
  51. i2c_init(i2c_id,0);
  52. i2c_scan();
  53. }else{
  54. i2c_help();
  55. }
  56. luat_heap_free(i2c_tools_data);
  57. }