i2c_msg_sample.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "rtconfig.h"
  2. #if defined BSP_USING_I2C_MSG
  3. #include "drv_log.h"
  4. #include "drv_i2c.h"
  5. #define TEST_DEVICE_ADDR 0x53
  6. static struct rt_i2c_bus_device *i2c_test_bus = RT_NULL;
  7. int i2c_msg_sample(int argc, char *argv[])
  8. {
  9. rt_uint8_t write_content[] = {"Phytium Rt-thread I2C Msg Driver Test Successfully !!"};
  10. rt_uint8_t write_addr[2] = {0x0, 0x0};
  11. rt_uint8_t write_buf[2 + sizeof(write_content)];
  12. rt_memcpy(write_buf, write_addr, 2);
  13. rt_memcpy(write_buf + 2, write_content, sizeof(write_content));
  14. rt_uint8_t read_buf[2 + sizeof(write_content)];
  15. rt_memcpy(read_buf, write_addr, 2);
  16. char name[RT_NAME_MAX];
  17. rt_strncpy(name, "I2C3_MSG", RT_NAME_MAX);
  18. i2c_test_bus = (struct rt_i2c_bus_device *)rt_device_find(name);
  19. if (i2c_test_bus == RT_NULL)
  20. {
  21. rt_kprintf("can't find %s device!\n", name);
  22. }
  23. else
  24. {
  25. rt_kprintf("find %s device!!!!\n", name);
  26. }
  27. struct rt_i2c_msg write_msgs;
  28. write_msgs.addr = TEST_DEVICE_ADDR;
  29. write_msgs.flags = RT_I2C_WR;
  30. write_msgs.buf = write_buf;
  31. write_msgs.len = sizeof(write_buf);
  32. rt_i2c_transfer(i2c_test_bus, &write_msgs, 1);
  33. struct rt_i2c_msg read_msgs;
  34. read_msgs.addr = TEST_DEVICE_ADDR;
  35. read_msgs.flags = RT_I2C_RD;
  36. read_msgs.buf = read_buf;
  37. read_msgs.len = sizeof(read_buf);
  38. rt_i2c_transfer(i2c_test_bus, &read_msgs, 1);
  39. for (rt_uint8_t i = 0; i < sizeof(write_content); i++)
  40. {
  41. if (read_buf[i] != write_content[i])
  42. {
  43. return -RT_ERROR;
  44. }
  45. }
  46. printf("%s\n", read_buf);
  47. return RT_EOK;
  48. }
  49. MSH_CMD_EXPORT(i2c_msg_sample, i2c msg device sample);
  50. #endif