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  * 2022-11-26     zhaohaisheng copy from sch and do some change
9  */
10 
11 #include <rtthread.h>
12 #include <rtdevice.h>
13 #include "board.h"
14 
15 #ifdef BSP_USING_SPI
16 
17 #include "drv_spi.h"
18 #include <string.h>
19 
20 #define DRV_DEBUG
21 #define LOG_TAG              "drv.spi"
22 #include <drv_log.h>
23 
24 enum
25 {
26 #ifdef BSP_USING_SPI1
27     SPI1_INDEX,
28 #endif
29 #ifdef BSP_USING_SPI2
30     SPI2_INDEX,
31 #endif
32 #ifdef BSP_USING_SPI3
33     SPI3_INDEX,
34 #endif
35 };
36 
37 static struct ch32_spi_config spi_config[] =
38 {
39 #ifdef BSP_USING_SPI1
40         {                                                       \
41             .Instance = SPI1,                                   \
42             .bus_name = "spi1",                                 \
43             .irq_type = SPI1_IRQn,                              \
44         },
45 #endif
46 
47 #ifdef BSP_USING_SPI2
48         {                                                       \
49             .Instance = SPI2,                                   \
50             .bus_name = "spi2",                                 \
51             .irq_type = SPI2_IRQn,                              \
52         },
53 #endif
54 
55 #ifdef BSP_USING_SPI3
56         {                                                       \
57             .Instance = SPI3,                                   \
58             .bus_name = "spi3",                                 \
59             .irq_type = SPI3_IRQn,                              \
60         }
61 #endif
62 };
63 
64 static struct ch32_spi spi_bus_obj[sizeof(spi_config) / sizeof(spi_config[0])] = {0};
65 
66 static rt_uint32_t ch32_spi_clock_get(SPI_TypeDef *spix);
67 static void ch32_spi_clock_and_io_init(SPI_TypeDef *spix);
68 static rt_uint8_t spix_readwritebyte(SPI_TypeDef *Instance, rt_uint8_t TxData);
69 static rt_err_t spi_transmitreceive(SPI_TypeDef *Instance, rt_uint8_t *send_buf, rt_uint8_t *recv_buf, rt_uint16_t send_length);
70 static rt_err_t spi_transmit(SPI_TypeDef *Instance, rt_uint8_t *send_buf, rt_uint16_t send_length);
71 static rt_err_t spi_receive(SPI_TypeDef *Instance, rt_uint8_t *recv_buf,rt_uint16_t send_length);
72 
ch32_spi_clock_and_io_init(SPI_TypeDef * spix)73 static void ch32_spi_clock_and_io_init(SPI_TypeDef *spix)
74 {
75 
76     GPIO_InitTypeDef GPIO_InitStructure;
77 
78     GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
79 
80     if (spix == SPI1)
81     {
82         RCC_APB2PeriphClockCmd( RCC_APB2Periph_SPI1|RCC_APB2Periph_GPIOA, ENABLE );
83         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
84         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
85         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
86         GPIO_Init( GPIOA, &GPIO_InitStructure );
87 
88         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
89         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
90         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
91         GPIO_Init( GPIOA, &GPIO_InitStructure );
92 
93         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
94         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
95         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
96         GPIO_Init( GPIOA, &GPIO_InitStructure );
97     }
98 
99     if (spix == SPI2)
100     {
101         RCC_APB1PeriphClockCmd( RCC_APB1Periph_SPI2, ENABLE );
102         RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE );
103 
104         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
105         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
106         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
107         GPIO_Init( GPIOB, &GPIO_InitStructure );
108 
109         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
110         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
111         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
112         GPIO_Init( GPIOB, &GPIO_InitStructure );
113 
114         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
115         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
116         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
117         GPIO_Init( GPIOB, &GPIO_InitStructure );
118     }
119 
120     if (spix == SPI3)
121     {
122         RCC_APB1PeriphClockCmd( RCC_APB1Periph_SPI3, ENABLE );
123         RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE );
124 
125         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
126         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
127         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
128         GPIO_Init( GPIOB, &GPIO_InitStructure );
129 
130         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
131         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
132         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
133         GPIO_Init( GPIOB, &GPIO_InitStructure );
134 
135         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
136         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
137         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
138         GPIO_Init( GPIOB, &GPIO_InitStructure );
139     }
140 }
141 
ch32_spi_clock_get(SPI_TypeDef * spix)142 static rt_uint32_t ch32_spi_clock_get(SPI_TypeDef *spix)
143 {
144     RCC_ClocksTypeDef RCC_Clocks;
145 
146     RCC_GetClocksFreq(&RCC_Clocks);
147 
148     if (spix == SPI1)
149     {
150         return RCC_Clocks.PCLK2_Frequency;
151     }
152 
153     if (spix == SPI2)
154     {
155         return RCC_Clocks.PCLK1_Frequency;
156     }
157 
158     if (spix == SPI3)
159     {
160         return RCC_Clocks.PCLK1_Frequency;
161     }
162 
163     return RCC_Clocks.PCLK2_Frequency;
164 }
165 
166 /*
167  *spix read write byte
168  * */
spix_readwritebyte(SPI_TypeDef * Instance,rt_uint8_t TxData)169 static rt_uint8_t spix_readwritebyte(SPI_TypeDef *Instance, rt_uint8_t TxData)
170 {
171     rt_uint8_t i=0;
172     while (SPI_I2S_GetFlagStatus(Instance, SPI_I2S_FLAG_TXE) == RESET)
173     {
174         i++;
175         if (i > 200) return 0;
176     }
177     SPI_I2S_SendData(Instance, TxData);
178 
179     i=0;
180     while (SPI_I2S_GetFlagStatus(Instance, SPI_I2S_FLAG_RXNE) == RESET)
181     {
182         i++;
183         if(i > 200) return 0;
184     }
185     return SPI_I2S_ReceiveData(Instance);
186 }
187 
188 /*
189  *spi transmit and receive
190  * */
spi_transmitreceive(SPI_TypeDef * Instance,rt_uint8_t * send_buf,rt_uint8_t * recv_buf,rt_uint16_t send_length)191 static rt_err_t spi_transmitreceive(SPI_TypeDef *Instance, rt_uint8_t *send_buf, rt_uint8_t *recv_buf, rt_uint16_t send_length)
192 {
193     rt_uint16_t i=0;
194     for(i = 0; i < send_length; i++)
195     {
196         recv_buf[i] = spix_readwritebyte(Instance, send_buf[i]);
197     }
198     return RT_EOK;
199 }
200 
201 /*
202  *spi transmit
203  * */
spi_transmit(SPI_TypeDef * Instance,rt_uint8_t * send_buf,rt_uint16_t send_length)204 static rt_err_t spi_transmit(SPI_TypeDef *Instance, rt_uint8_t *send_buf, rt_uint16_t send_length)
205 {
206     rt_uint16_t i=0;
207     for(i = 0; i < send_length; i++)
208     {
209         spix_readwritebyte(Instance, send_buf[i]);
210     }
211     return RT_EOK;
212 }
213 
214 /*
215  *spi  receive
216  * */
spi_receive(SPI_TypeDef * Instance,rt_uint8_t * recv_buf,rt_uint16_t send_length)217 static rt_err_t spi_receive(SPI_TypeDef *Instance, rt_uint8_t *recv_buf,rt_uint16_t send_length)
218 {
219     rt_uint16_t i=0;
220     for(i = 0; i < send_length; i++)
221     {
222         recv_buf[i] = spix_readwritebyte(Instance, 0xFF);  /*发送数据为0xff 此时显示为不发送*/
223     }
224     return RT_EOK;
225 }
226 
ch32_spi_init(struct ch32_spi * spi_drv,struct rt_spi_configuration * cfg)227 static rt_err_t ch32_spi_init(struct ch32_spi *spi_drv, struct rt_spi_configuration *cfg)
228 {
229     RT_ASSERT(spi_drv != RT_NULL);
230     RT_ASSERT(cfg != RT_NULL);
231 
232     SPI_HandleTypeDef *spi_handle = &spi_drv->handle;
233 
234 
235     if (cfg->mode & RT_SPI_SLAVE)
236     {
237         spi_handle->Init.SPI_Mode = SPI_Mode_Slave;
238     }
239     else
240     {
241         spi_handle->Init.SPI_Mode = SPI_Mode_Master;
242     }
243 
244     if (cfg->mode & RT_SPI_3WIRE)
245     {
246         spi_handle->Init.SPI_Direction = SPI_Direction_1Line_Rx;
247     }
248     else
249     {
250         spi_handle->Init.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
251     }
252 
253     if (cfg->data_width <= 8)
254     {
255         spi_handle->Init.SPI_DataSize = SPI_DataSize_8b;
256         spi_handle->TxXferSize = 8;
257         spi_handle->RxXferSize = 8;
258     }
259     else if (cfg->data_width <= 16)
260     {
261         spi_handle->Init.SPI_DataSize = SPI_DataSize_16b;
262     }
263     else
264     {
265         return -RT_EIO;
266     }
267 
268     if (cfg->mode & RT_SPI_CPHA)
269     {
270         spi_handle->Init.SPI_CPHA = SPI_CPHA_2Edge;
271     }
272     else
273     {
274         spi_handle->Init.SPI_CPHA = SPI_CPHA_1Edge;
275     }
276 
277     if (cfg->mode & RT_SPI_CPOL)
278     {
279        spi_handle->Init.SPI_CPOL = SPI_CPOL_High;
280     }
281     else
282     {
283         spi_handle->Init.SPI_CPOL = SPI_CPOL_Low;
284     }
285 
286     spi_handle->Init.SPI_NSS = SPI_NSS_Soft;
287     //device is not RT_NULL, so spi_bus not need check
288     rt_uint32_t SPI_APB_CLOCK;
289     ch32_spi_clock_and_io_init(spi_handle->Instance);
290     SPI_APB_CLOCK = ch32_spi_clock_get(spi_handle->Instance);
291 
292     if (cfg->max_hz >= SPI_APB_CLOCK / 2)
293     {
294         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
295     }
296     else if (cfg->max_hz >= SPI_APB_CLOCK / 4)
297     {
298         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
299     }
300     else if (cfg->max_hz >= SPI_APB_CLOCK / 8)
301     {
302         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
303     }
304     else if (cfg->max_hz >= SPI_APB_CLOCK / 16)
305     {
306         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
307     }
308     else if (cfg->max_hz >= SPI_APB_CLOCK / 32)
309     {
310         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_32;
311     }
312     else if (cfg->max_hz >= SPI_APB_CLOCK / 64)
313     {
314         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64;
315     }
316     else if (cfg->max_hz >= SPI_APB_CLOCK / 128)
317     {
318         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128;
319     }
320     else
321     {
322         /*  min prescaler 256 */
323         spi_handle->Init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
324     }
325     SystemCoreClockUpdate();
326     LOG_D("sys freq: %d, pclk2 freq: %d, SPI limiting freq: %d, BaudRatePrescaler: %d",
327         SystemCoreClock,
328         SPI_APB_CLOCK,
329         cfg->max_hz,
330         spi_handle->Init.SPI_BaudRatePrescaler);
331 
332     if (cfg->mode & RT_SPI_MSB)
333     {
334        spi_handle->Init.SPI_FirstBit = SPI_FirstBit_MSB;
335     }
336     else
337     {
338         spi_handle->Init.SPI_FirstBit = SPI_FirstBit_LSB;
339     }
340 
341     SPI_Init(spi_handle->Instance, &spi_handle->Init);
342     /* Enable SPI_MASTER */
343 
344     SPI_Cmd(spi_handle->Instance, ENABLE);
345 
346     LOG_D("%s init done", spi_drv->config->bus_name);
347 
348     return RT_EOK;
349 }
350 
spi_configure(struct rt_spi_device * device,struct rt_spi_configuration * configuration)351 static rt_err_t spi_configure(struct rt_spi_device *device,
352                               struct rt_spi_configuration *configuration)
353 {
354     RT_ASSERT(device != RT_NULL);
355     RT_ASSERT(configuration != RT_NULL);
356     struct ch32_spi *spi_drv =  rt_container_of(device->bus, struct ch32_spi, spi_bus);
357     spi_drv->cfg = configuration;
358 
359     return ch32_spi_init(spi_drv, configuration);
360 }
361 
spi_xfer(struct rt_spi_device * device,struct rt_spi_message * message)362 static rt_ssize_t spi_xfer(struct rt_spi_device *device, struct rt_spi_message *message)
363 {
364     rt_err_t state = RT_EOK;
365     rt_size_t message_length, already_send_length;
366     rt_uint16_t send_length;
367     rt_uint8_t *recv_buf;
368     const rt_uint8_t *send_buf;
369 
370     RT_ASSERT(device != NULL);
371     RT_ASSERT(device->bus != RT_NULL);
372     RT_ASSERT(device->bus->parent.user_data != RT_NULL);
373     RT_ASSERT(message != NULL);
374 
375     struct ch32_spi *spi_drv =  rt_container_of(device->bus, struct ch32_spi, spi_bus);
376     SPI_HandleTypeDef *spi_handle = &spi_drv->handle;
377 
378     struct ch32_hw_spi_cs *cs = device->parent.user_data;
379     /* take CS */
380     if (message->cs_take && !(device->config.mode & RT_SPI_NO_CS))
381     {
382         if (device->config.mode & RT_SPI_CS_HIGH)
383             GPIO_WriteBit(cs->GPIOx, cs->GPIO_Pin, Bit_SET);
384         else
385             GPIO_WriteBit(cs->GPIOx, cs->GPIO_Pin, Bit_RESET);
386     }
387 
388     LOG_D("%s transfer prepare and start", spi_drv->config->bus_name);
389     LOG_D("%s sendbuf: %X, recvbuf: %X, length: %d",
390             spi_drv->config->bus_name,
391             (rt_uint32_t)message->send_buf,
392             (rt_uint32_t)message->recv_buf, message->length);
393 
394     message_length = message->length;
395     recv_buf = message->recv_buf;
396     send_buf = message->send_buf;
397 
398     while (message_length)
399     {
400         /* the HAL library use uint16 to save the data length */
401         if (message_length > 65535)
402         {
403             send_length = 65535;
404             message_length = message_length - 65535;
405         }
406         else
407         {
408             send_length = message_length;
409             message_length = 0;
410         }
411 
412         /* calculate the start address */
413         already_send_length = message->length - send_length - message_length;
414         /* avoid null pointer problems */
415         if (message->send_buf)
416         {
417             send_buf = (rt_uint8_t *)message->send_buf + already_send_length;
418         }
419         if (message->recv_buf)
420         {
421             recv_buf = (rt_uint8_t *)message->recv_buf + already_send_length;
422         }
423 
424          /* start once data exchange */
425         if (message->send_buf && message->recv_buf)
426         {
427             state = spi_transmitreceive(spi_handle->Instance, (rt_uint8_t *)send_buf, (rt_uint8_t *)recv_buf, send_length);
428         }
429         else if (message->send_buf)
430         {
431 
432             state = spi_transmit(spi_handle->Instance, (rt_uint8_t *)send_buf, send_length);
433             if (message->cs_release && (device->config.mode & RT_SPI_3WIRE))
434             {
435                 /* release the CS by disable SPI when using 3 wires SPI */
436                 SPI_Cmd(spi_handle->Instance, DISABLE);
437             }
438         }
439         else
440         {
441             rt_memset((rt_uint8_t *)recv_buf, 0xff, send_length);
442             /* clear the old error flag */
443             SPI_I2S_ClearFlag(spi_handle->Instance, SPI_I2S_FLAG_OVR);
444             state = spi_receive(spi_handle->Instance, (rt_uint8_t *)recv_buf, send_length);
445         }
446 
447         if (state != RT_EOK)
448         {
449             LOG_I("spi transfer error : %d", state);
450             message->length = 0;
451         }
452         else
453         {
454             LOG_D("%s transfer done", spi_drv->config->bus_name);
455         }
456 
457     }
458     /* release CS */
459     if (message->cs_release && !(device->config.mode & RT_SPI_NO_CS))
460     {
461         if (device->config.mode & RT_SPI_CS_HIGH)
462             GPIO_WriteBit(cs->GPIOx, cs->GPIO_Pin, Bit_RESET);
463         else
464             GPIO_WriteBit(cs->GPIOx, cs->GPIO_Pin, Bit_SET);
465     }
466 
467     if(state != RT_EOK)
468     {
469         return -RT_ERROR;
470     }
471 
472     return message->length;
473 }
474 
475 static const struct rt_spi_ops ch32_spi_ops =
476 {
477     .configure = spi_configure,
478     .xfer = spi_xfer,
479 };
480 
rt_hw_spi_bus_init(void)481 static int rt_hw_spi_bus_init(void)
482 {
483     rt_err_t result;
484 
485     for (rt_size_t i = 0; i < sizeof(spi_config) / sizeof(spi_config[0]); i++)
486     {
487         spi_bus_obj[i].config = &spi_config[i];
488         spi_bus_obj[i].spi_bus.parent.user_data = &spi_config[i];
489         spi_bus_obj[i].handle.Instance = spi_config[i].Instance;
490 
491         result = rt_spi_bus_register(&spi_bus_obj[i].spi_bus, spi_config[i].bus_name, &ch32_spi_ops);
492         RT_ASSERT(result == RT_EOK);
493 
494         LOG_D("%s bus init done", spi_config[i].bus_name);
495     }
496 
497     return result;
498 }
499 
500 /**
501   * Attach the spi device to SPI bus, this function must be used after initialization.
502   */
rt_hw_spi_device_attach(const char * bus_name,const char * device_name,GPIO_TypeDef * cs_gpiox,rt_uint16_t cs_gpio_pin)503 rt_err_t rt_hw_spi_device_attach(const char *bus_name, const char *device_name, GPIO_TypeDef *cs_gpiox, rt_uint16_t cs_gpio_pin)
504 {
505     RT_ASSERT(bus_name != RT_NULL);
506     RT_ASSERT(device_name != RT_NULL);
507 
508     rt_err_t result;
509     struct rt_spi_device *spi_device;
510     struct ch32_hw_spi_cs *cs_pin;
511 
512     /* initialize the cs pin && select the slave*/
513     GPIO_InitTypeDef GPIO_Initure;
514     GPIO_Initure.GPIO_Pin = cs_gpio_pin;
515     GPIO_Initure.GPIO_Mode = GPIO_Mode_Out_PP;
516     GPIO_Initure.GPIO_Speed = GPIO_Speed_50MHz;
517     GPIO_Init(cs_gpiox, &GPIO_Initure);
518     GPIO_WriteBit(cs_gpiox, cs_gpio_pin, Bit_SET);
519 
520     /* attach the device to spi bus*/
521     spi_device = (struct rt_spi_device *)rt_malloc(sizeof(struct rt_spi_device));
522     RT_ASSERT(spi_device != RT_NULL);
523     cs_pin = (struct ch32_hw_spi_cs *)rt_malloc(sizeof(struct ch32_hw_spi_cs));
524     RT_ASSERT(cs_pin != RT_NULL);
525     cs_pin->GPIOx = cs_gpiox;
526     cs_pin->GPIO_Pin = cs_gpio_pin;
527     result = rt_spi_bus_attach_device(spi_device, device_name, bus_name, (void *)cs_pin);
528 
529     if (result != RT_EOK)
530     {
531         LOG_E("%s attach to %s faild, %d\n", device_name, bus_name, result);
532     }
533 
534     RT_ASSERT(result == RT_EOK);
535 
536     LOG_D("%s attach to %s done", device_name, bus_name);
537 
538     return result;
539 }
540 
rt_hw_spi_init(void)541 int rt_hw_spi_init(void)
542 {
543     return rt_hw_spi_bus_init();
544 }
545 INIT_BOARD_EXPORT(rt_hw_spi_init);
546 
547 #endif /* BSP_USING_SPI  */
548