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 
11 #include <rtthread.h>
12 #include <rtdevice.h>
13 
14 #ifdef BSP_USING_SPI
15 
16 #define BUS_NAME     "spi0"
17 #define SPI_NAME     "spi00"
18 
19 static struct rt_spi_device *spi_dev = RT_NULL;
20 
21 /* attach spi5 device */
rt_spi_device_init(void)22 static int rt_spi_device_init(void)
23 {
24     struct rt_spi_configuration cfg;
25 
26     rt_hw_spi_device_attach(BUS_NAME, SPI_NAME, RT_NULL);
27 
28     cfg.data_width = 8;
29     cfg.mode   = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB | RT_SPI_NO_CS;
30     cfg.max_hz = 10 *1000 *1000;
31 
32     spi_dev = (struct rt_spi_device *)rt_device_find(SPI_NAME);
33 
34     if (RT_NULL == spi_dev)
35     {
36         rt_kprintf("spi sample run failed! can't find %s device!\n", SPI_NAME);
37         return -RT_ERROR;
38     }
39 
40     rt_spi_configure(spi_dev, &cfg);
41 
42     return RT_EOK;
43 }
44 INIT_APP_EXPORT(rt_spi_device_init);
45 
46 /* spi loopback mode test case */
spi_sample(int argc,char ** argv)47 static int spi_sample(int argc, char **argv)
48 {
49     rt_uint8_t t_buf[8], r_buf[8];
50     int i = 0;
51     static struct rt_spi_message msg1;
52 
53     if (argc != 9)
54     {
55         rt_kprintf("Please Usage:\n");
56         rt_kprintf("spi_sample 1 2 3 4 5 6 7 8\n");
57         return -RT_ERROR;
58     }
59 
60     for (i = 0; i < 8; i++)
61     {
62         t_buf[i] = atoi(argv[i+1]);
63     }
64 
65     msg1.send_buf   = &t_buf;
66     msg1.recv_buf   = &r_buf;
67     msg1.length     = sizeof(t_buf);
68     msg1.cs_take    = 1;
69     msg1.cs_release = 0;
70     msg1.next       = RT_NULL;
71 
72     rt_spi_transfer_message(spi_dev, &msg1);
73 
74     rt_kprintf("spi rbuf : ");
75     for (i = 0; i < sizeof(t_buf); i++)
76     {
77         rt_kprintf("%x ", r_buf[i]);
78     }
79 
80     rt_kprintf("\nspi loopback mode test over!\n");
81 
82     return RT_EOK;
83 }
84 MSH_CMD_EXPORT(spi_sample, spi loopback test);
85 
86 #endif /* BSP_USING_SPI */
87