i2c_test.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #include <rtthread.h>
  2. #include <rtdevice.h>
  3. #include <stdio.h>
  4. #include <stdint.h>
  5. #include <stdlib.h>
  6. #ifdef RT_USING_I2C
  7. static int i2cmemrd(int argc, char **argv)
  8. {
  9. uint8_t rbuf[64];
  10. uint8_t wbuf[1];
  11. struct rt_i2c_msg msg[2];
  12. struct rt_i2c_bus_device *bus;
  13. uint16_t slave;
  14. uint16_t size;
  15. if (argc != 5)
  16. {
  17. printf("Usage: i2cmemrd BUSNAME SLAVE POS SIZE\n");
  18. return -1;
  19. }
  20. bus = rt_i2c_bus_device_find(argv[1]);
  21. if (!bus)
  22. {
  23. printf("i2cbus: %s not found\n", argv[1]);
  24. return -1;
  25. }
  26. slave = (uint16_t)atoi(argv[2]);
  27. wbuf[0] = (uint8_t)atoi(argv[3]);
  28. size = (uint16_t)atoi(argv[4]);
  29. if (size > sizeof(rbuf) || size == 0)
  30. {
  31. printf("SIZE 1~64\n");
  32. return -1;
  33. }
  34. msg[0].flags = RT_I2C_WR;
  35. msg[0].addr = slave;
  36. msg[0].buf = wbuf;
  37. msg[0].len = 1;
  38. msg[1].flags = RT_I2C_RD;
  39. msg[1].addr = slave;
  40. msg[1].buf = rbuf;
  41. msg[1].len = size;
  42. if (rt_i2c_transfer(bus, msg, 2) == 2)
  43. {
  44. int i;
  45. for (i = 0; i < size; i++)
  46. {
  47. if (i % 16 == 0)
  48. printf("\n");
  49. printf("%02X ", rbuf[i]);
  50. }
  51. printf("\n");
  52. }
  53. else
  54. {
  55. printf("read fail\n");
  56. }
  57. return 0;
  58. }
  59. MSH_CMD_EXPORT(i2cmemrd, i2cmemrd BUSNAME SLAVE POS SIZE);
  60. static int i2cmemwr(int argc, char **argv)
  61. {
  62. uint8_t buf[64];
  63. uint8_t pos[1];
  64. struct rt_i2c_msg msg[2];
  65. struct rt_i2c_bus_device *bus;
  66. uint16_t slave;
  67. if (argc != 5)
  68. {
  69. printf("Usage: i2cmemwr BUSNAME SLAVE POS VALUE\n");
  70. return -1;
  71. }
  72. bus = rt_i2c_bus_device_find(argv[1]);
  73. if (!bus)
  74. {
  75. printf("i2cbus: %s not found\n", argv[1]);
  76. return -1;
  77. }
  78. slave = (uint16_t)atoi(argv[2]);
  79. pos[0] = (uint8_t)atoi(argv[3]);
  80. buf[0] = (uint8_t)atoi(argv[4]);
  81. msg[0].flags = RT_I2C_WR;
  82. msg[0].addr = slave;
  83. msg[0].buf = pos;
  84. msg[0].len = 1;
  85. msg[1].flags = RT_I2C_WR;
  86. msg[1].addr = slave;
  87. msg[1].buf = buf;
  88. msg[1].len = 1;
  89. if (rt_i2c_transfer(bus, msg, 2) != 2)
  90. {
  91. printf("write fail\n");
  92. }
  93. return 0;
  94. }
  95. MSH_CMD_EXPORT(i2cmemwr, i2cmemwr BUSNAME SLAVE POS VALUE);
  96. #endif