i2c_sample.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "rtconfig.h"
  2. #if defined BSP_USING_I2C
  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. rt_err_t i2c_sample()
  8. {
  9. rt_uint8_t write_content[] = {"Phytium Rt-thread I2C 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. #if defined(FIREFLY_DEMO_BOARD)
  18. rt_strncpy(name, "MIO1", RT_NAME_MAX);
  19. #endif
  20. #if defined(E2000D_DEMO_BOARD)||defined(E2000Q_DEMO_BOARD)
  21. rt_strncpy(name, "MIO15", RT_NAME_MAX);
  22. #endif
  23. #if defined(TARGET_PD2408)
  24. rt_strncpy(name, "I2C3", RT_NAME_MAX);
  25. #endif
  26. i2c_test_bus = (struct rt_i2c_bus_device *)rt_device_find(name);
  27. if (i2c_test_bus == RT_NULL)
  28. {
  29. rt_kprintf("can't find %s device!\n", name);
  30. }
  31. else
  32. {
  33. rt_kprintf("find %s device!!!!\n", name);
  34. }
  35. struct rt_i2c_msg write_msgs;
  36. write_msgs.addr = TEST_DEVICE_ADDR;
  37. write_msgs.flags = RT_I2C_WR;
  38. write_msgs.buf = write_buf;
  39. write_msgs.len = sizeof(write_buf);
  40. rt_i2c_transfer(i2c_test_bus, &write_msgs, 1);
  41. struct rt_i2c_msg read_msgs;
  42. read_msgs.addr = TEST_DEVICE_ADDR;
  43. read_msgs.flags = RT_I2C_RD;
  44. read_msgs.buf = read_buf;
  45. read_msgs.len = sizeof(read_buf);
  46. rt_i2c_transfer(i2c_test_bus, &read_msgs, 1);
  47. for (rt_uint8_t i = 0; i < sizeof(write_content); i++)
  48. {
  49. if (read_buf[i] != write_content[i])
  50. {
  51. return -RT_ERROR;
  52. }
  53. }
  54. rt_kprintf("%s\n", read_buf);
  55. return RT_EOK;
  56. }
  57. MSH_CMD_EXPORT(i2c_sample, i2c device sample);
  58. #endif