spi_w25q_sample.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-08-15 misonyo first implementation.
  9. */
  10. /*
  11. * 程序清单:这是一个 SPI 设备使用例程
  12. * 例程导出了 spi_w25q_sample 命令到控制终端
  13. * 命令调用格式:spi_w25q_sample spi10
  14. * 命令解释:命令第二个参数是要使用的SPI设备名称,为空则使用默认的SPI设备
  15. * 程序功能:通过SPI设备读取 w25q 的 ID 数据
  16. */
  17. #include <rtthread.h>
  18. #include <rtdevice.h>
  19. #define W25Q_SPI_DEVICE_NAME "qspi10"
  20. static void spi_w25q_sample(int argc, char *argv[])
  21. {
  22. struct rt_spi_device *spi_dev_w25q;
  23. char name[RT_NAME_MAX];
  24. rt_uint8_t w25x_read_id = 0x90;
  25. rt_uint8_t id[5] = {0};
  26. if (argc == 2)
  27. {
  28. rt_strncpy(name, argv[1], RT_NAME_MAX);
  29. }
  30. else
  31. {
  32. rt_strncpy(name, W25Q_SPI_DEVICE_NAME, RT_NAME_MAX);
  33. }
  34. /* 查找 spi 设备获取设备句柄 */
  35. spi_dev_w25q = (struct rt_spi_device *)rt_device_find(name);
  36. if (!spi_dev_w25q)
  37. {
  38. rt_kprintf("spi sample run failed! can't find %s device!\n", name);
  39. }
  40. else
  41. {
  42. /* 方式1:使用 rt_spi_send_then_recv()发送命令读取ID */
  43. rt_spi_send_then_recv(spi_dev_w25q, &w25x_read_id, 1, id, 5);
  44. rt_kprintf("use rt_spi_send_then_recv() read w25q ID is:%x%x\n", id[3], id[4]);
  45. /* 方式2:使用 rt_spi_transfer_message()发送命令读取ID */
  46. struct rt_spi_message msg1, msg2;
  47. msg1.send_buf = &w25x_read_id;
  48. msg1.recv_buf = RT_NULL;
  49. msg1.length = 1;
  50. msg1.cs_take = 1;
  51. msg1.cs_release = 0;
  52. msg1.next = &msg2;
  53. msg2.send_buf = RT_NULL;
  54. msg2.recv_buf = id;
  55. msg2.length = 5;
  56. msg2.cs_take = 0;
  57. msg2.cs_release = 1;
  58. msg2.next = RT_NULL;
  59. rt_spi_transfer_message(spi_dev_w25q, &msg1);
  60. rt_kprintf("use rt_spi_transfer_message() read w25q ID is:%x%x\n", id[3], id[4]);
  61. }
  62. }
  63. /* 导出到 msh 命令列表中 */
  64. MSH_CMD_EXPORT(spi_w25q_sample, spi w25q sample);