i2c_tools.c 1.9 KB

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