spi_sample.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2023-05-01 flyingcys first version
  9. */
  10. #include <rtthread.h>
  11. #include <rtdevice.h>
  12. #ifdef BSP_USING_SPI
  13. #define BUS_NAME "spi0"
  14. #define SPI_NAME "spi00"
  15. static struct rt_spi_device *spi_dev = RT_NULL;
  16. /* attach spi5 device */
  17. static int rt_spi_device_init(void)
  18. {
  19. struct rt_spi_configuration cfg;
  20. rt_hw_spi_device_attach(BUS_NAME, SPI_NAME, RT_NULL);
  21. cfg.data_width = 8;
  22. cfg.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB | RT_SPI_NO_CS;
  23. cfg.max_hz = 10 *1000 *1000;
  24. spi_dev = (struct rt_spi_device *)rt_device_find(SPI_NAME);
  25. if (RT_NULL == spi_dev)
  26. {
  27. rt_kprintf("spi sample run failed! can't find %s device!\n", SPI_NAME);
  28. return -RT_ERROR;
  29. }
  30. rt_spi_configure(spi_dev, &cfg);
  31. return RT_EOK;
  32. }
  33. INIT_APP_EXPORT(rt_spi_device_init);
  34. /* spi loopback mode test case */
  35. static int spi_sample(int argc, char **argv)
  36. {
  37. rt_uint8_t t_buf[8], r_buf[8];
  38. int i = 0;
  39. static struct rt_spi_message msg1;
  40. if (argc != 9)
  41. {
  42. rt_kprintf("Please Usage:\n");
  43. rt_kprintf("spi_sample 1 2 3 4 5 6 7 8\n");
  44. return -RT_ERROR;
  45. }
  46. for (i = 0; i < 8; i++)
  47. {
  48. t_buf[i] = atoi(argv[i+1]);
  49. }
  50. msg1.send_buf = &t_buf;
  51. msg1.recv_buf = &r_buf;
  52. msg1.length = sizeof(t_buf);
  53. msg1.cs_take = 1;
  54. msg1.cs_release = 0;
  55. msg1.next = RT_NULL;
  56. rt_spi_transfer_message(spi_dev, &msg1);
  57. rt_kprintf("spi rbuf : ");
  58. for (i = 0; i < sizeof(t_buf); i++)
  59. {
  60. rt_kprintf("%x ", r_buf[i]);
  61. }
  62. rt_kprintf("\nspi loopback mode test over!\n");
  63. return RT_EOK;
  64. }
  65. MSH_CMD_EXPORT(spi_sample, spi loopback test);
  66. #endif /* BSP_USING_SPI */