i2c_tools.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. printf("[ ");
  37. for(uint8_t i = 0; i < len; i++){
  38. printf("0x%02X", buffer[i]);
  39. if(i != (len-1)){
  40. printf(", ");
  41. }
  42. }
  43. printf(" ]\n");
  44. }
  45. luat_heap_free(buffer);
  46. }else if(memcmp("scan",command,4) == 0){
  47. int i2c_id = atoi(strtok(NULL, " "));
  48. i2c_init(i2c_id);
  49. i2c_scan();
  50. }else{
  51. i2c_help();
  52. }
  53. luat_heap_free(i2c_tools_data);
  54. }