stm_spi_api.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /* mbed Microcontroller Library
  2. *******************************************************************************
  3. * Copyright (c) 2015, STMicroelectronics
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. * 3. Neither the name of STMicroelectronics nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  19. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  22. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  24. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  26. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *******************************************************************************
  29. */
  30. #include "mbed_assert.h"
  31. #include "mbed_error.h"
  32. #include "mbed_debug.h"
  33. #include "spi_api.h"
  34. #if DEVICE_SPI
  35. #include <stdbool.h>
  36. #include <math.h>
  37. #include <string.h>
  38. #include "cmsis.h"
  39. #include "pinmap.h"
  40. #include "PeripheralPins.h"
  41. #include "spi_device.h"
  42. #if DEVICE_SPI_ASYNCH
  43. #define SPI_INST(obj) ((SPI_TypeDef *)(obj->spi.spi))
  44. #else
  45. #define SPI_INST(obj) ((SPI_TypeDef *)(obj->spi))
  46. #endif
  47. #if DEVICE_SPI_ASYNCH
  48. #define SPI_S(obj) (( struct spi_s *)(&(obj->spi)))
  49. #else
  50. #define SPI_S(obj) (( struct spi_s *)(obj))
  51. #endif
  52. #ifndef DEBUG_STDIO
  53. # define DEBUG_STDIO 0
  54. #endif
  55. #if DEBUG_STDIO
  56. # include <stdio.h>
  57. # define DEBUG_PRINTF(...) do { printf(__VA_ARGS__); } while(0)
  58. #else
  59. # define DEBUG_PRINTF(...) {}
  60. #endif
  61. /* Consider 10ms as the default timeout for sending/receving 1 byte */
  62. #define TIMEOUT_1_BYTE 10
  63. #if defined(SPI_FLAG_FRLVL) // STM32F0 STM32F3 STM32F7 STM32L4
  64. extern HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(SPI_HandleTypeDef *hspi);
  65. #endif
  66. void init_spi(spi_t *obj)
  67. {
  68. struct spi_s *spiobj = SPI_S(obj);
  69. SPI_HandleTypeDef *handle = &(spiobj->handle);
  70. __HAL_SPI_DISABLE(handle);
  71. DEBUG_PRINTF("init_spi: instance=0x%8X\r\n", (int)handle->Instance);
  72. if (HAL_SPI_Init(handle) != HAL_OK) {
  73. error("Cannot initialize SPI");
  74. }
  75. /* In case of standard 4 wires SPI,PI can be kept enabled all time
  76. * and SCK will only be generated during the write operations. But in case
  77. * of 3 wires, it should be only enabled during rd/wr unitary operations,
  78. * which is handled inside STM32 HAL layer.
  79. */
  80. if (handle->Init.Direction == SPI_DIRECTION_2LINES) {
  81. __HAL_SPI_ENABLE(handle);
  82. }
  83. }
  84. void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel)
  85. {
  86. struct spi_s *spiobj = SPI_S(obj);
  87. SPI_HandleTypeDef *handle = &(spiobj->handle);
  88. // Determine the SPI to use
  89. SPIName spi_mosi = (SPIName)pinmap_peripheral(mosi, PinMap_SPI_MOSI);
  90. SPIName spi_miso = (SPIName)pinmap_peripheral(miso, PinMap_SPI_MISO);
  91. SPIName spi_sclk = (SPIName)pinmap_peripheral(sclk, PinMap_SPI_SCLK);
  92. SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL);
  93. SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso);
  94. SPIName spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel);
  95. spiobj->spi = (SPIName)pinmap_merge(spi_data, spi_cntl);
  96. MBED_ASSERT(spiobj->spi != (SPIName)NC);
  97. #if defined SPI1_BASE
  98. // Enable SPI clock
  99. if (spiobj->spi == SPI_1) {
  100. __HAL_RCC_SPI1_CLK_ENABLE();
  101. spiobj->spiIRQ = SPI1_IRQn;
  102. }
  103. #endif
  104. #if defined SPI2_BASE
  105. if (spiobj->spi == SPI_2) {
  106. __HAL_RCC_SPI2_CLK_ENABLE();
  107. spiobj->spiIRQ = SPI2_IRQn;
  108. }
  109. #endif
  110. #if defined SPI3_BASE
  111. if (spiobj->spi == SPI_3) {
  112. __HAL_RCC_SPI3_CLK_ENABLE();
  113. spiobj->spiIRQ = SPI3_IRQn;
  114. }
  115. #endif
  116. #if defined SPI4_BASE
  117. if (spiobj->spi == SPI_4) {
  118. __HAL_RCC_SPI4_CLK_ENABLE();
  119. spiobj->spiIRQ = SPI4_IRQn;
  120. }
  121. #endif
  122. #if defined SPI5_BASE
  123. if (spiobj->spi == SPI_5) {
  124. __HAL_RCC_SPI5_CLK_ENABLE();
  125. spiobj->spiIRQ = SPI5_IRQn;
  126. }
  127. #endif
  128. #if defined SPI6_BASE
  129. if (spiobj->spi == SPI_6) {
  130. __HAL_RCC_SPI6_CLK_ENABLE();
  131. spiobj->spiIRQ = SPI6_IRQn;
  132. }
  133. #endif
  134. // Configure the SPI pins
  135. pinmap_pinout(mosi, PinMap_SPI_MOSI);
  136. pinmap_pinout(miso, PinMap_SPI_MISO);
  137. pinmap_pinout(sclk, PinMap_SPI_SCLK);
  138. spiobj->pin_miso = miso;
  139. spiobj->pin_mosi = mosi;
  140. spiobj->pin_sclk = sclk;
  141. spiobj->pin_ssel = ssel;
  142. if (ssel != NC) {
  143. pinmap_pinout(ssel, PinMap_SPI_SSEL);
  144. handle->Init.NSS = SPI_NSS_HARD_OUTPUT;
  145. } else {
  146. handle->Init.NSS = SPI_NSS_SOFT;
  147. }
  148. /* Fill default value */
  149. handle->Instance = SPI_INST(obj);
  150. handle->Init.Mode = SPI_MODE_MASTER;
  151. handle->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
  152. if (miso != NC) {
  153. handle->Init.Direction = SPI_DIRECTION_2LINES;
  154. } else {
  155. handle->Init.Direction = SPI_DIRECTION_1LINE;
  156. }
  157. handle->Init.CLKPhase = SPI_PHASE_1EDGE;
  158. handle->Init.CLKPolarity = SPI_POLARITY_LOW;
  159. handle->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  160. handle->Init.CRCPolynomial = 7;
  161. handle->Init.DataSize = SPI_DATASIZE_8BIT;
  162. handle->Init.FirstBit = SPI_FIRSTBIT_MSB;
  163. handle->Init.TIMode = SPI_TIMODE_DISABLE;
  164. init_spi(obj);
  165. }
  166. void spi_free(spi_t *obj)
  167. {
  168. struct spi_s *spiobj = SPI_S(obj);
  169. SPI_HandleTypeDef *handle = &(spiobj->handle);
  170. DEBUG_PRINTF("spi_free\r\n");
  171. __HAL_SPI_DISABLE(handle);
  172. HAL_SPI_DeInit(handle);
  173. #if defined SPI1_BASE
  174. // Reset SPI and disable clock
  175. if (spiobj->spi == SPI_1) {
  176. __HAL_RCC_SPI1_FORCE_RESET();
  177. __HAL_RCC_SPI1_RELEASE_RESET();
  178. __HAL_RCC_SPI1_CLK_DISABLE();
  179. }
  180. #endif
  181. #if defined SPI2_BASE
  182. if (spiobj->spi == SPI_2) {
  183. __HAL_RCC_SPI2_FORCE_RESET();
  184. __HAL_RCC_SPI2_RELEASE_RESET();
  185. __HAL_RCC_SPI2_CLK_DISABLE();
  186. }
  187. #endif
  188. #if defined SPI3_BASE
  189. if (spiobj->spi == SPI_3) {
  190. __HAL_RCC_SPI3_FORCE_RESET();
  191. __HAL_RCC_SPI3_RELEASE_RESET();
  192. __HAL_RCC_SPI3_CLK_DISABLE();
  193. }
  194. #endif
  195. #if defined SPI4_BASE
  196. if (spiobj->spi == SPI_4) {
  197. __HAL_RCC_SPI4_FORCE_RESET();
  198. __HAL_RCC_SPI4_RELEASE_RESET();
  199. __HAL_RCC_SPI4_CLK_DISABLE();
  200. }
  201. #endif
  202. #if defined SPI5_BASE
  203. if (spiobj->spi == SPI_5) {
  204. __HAL_RCC_SPI5_FORCE_RESET();
  205. __HAL_RCC_SPI5_RELEASE_RESET();
  206. __HAL_RCC_SPI5_CLK_DISABLE();
  207. }
  208. #endif
  209. #if defined SPI6_BASE
  210. if (spiobj->spi == SPI_6) {
  211. __HAL_RCC_SPI6_FORCE_RESET();
  212. __HAL_RCC_SPI6_RELEASE_RESET();
  213. __HAL_RCC_SPI6_CLK_DISABLE();
  214. }
  215. #endif
  216. // Configure GPIOs
  217. pin_function(spiobj->pin_miso, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0));
  218. pin_function(spiobj->pin_mosi, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0));
  219. pin_function(spiobj->pin_sclk, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0));
  220. if (handle->Init.NSS != SPI_NSS_SOFT) {
  221. pin_function(spiobj->pin_ssel, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0));
  222. }
  223. }
  224. void spi_format(spi_t *obj, int bits, int mode, int slave)
  225. {
  226. struct spi_s *spiobj = SPI_S(obj);
  227. SPI_HandleTypeDef *handle = &(spiobj->handle);
  228. DEBUG_PRINTF("spi_format, bits:%d, mode:%d, slave?:%d\r\n", bits, mode, slave);
  229. // Save new values
  230. handle->Init.DataSize = (bits == 16) ? SPI_DATASIZE_16BIT : SPI_DATASIZE_8BIT;
  231. switch (mode) {
  232. case 0:
  233. handle->Init.CLKPolarity = SPI_POLARITY_LOW;
  234. handle->Init.CLKPhase = SPI_PHASE_1EDGE;
  235. break;
  236. case 1:
  237. handle->Init.CLKPolarity = SPI_POLARITY_LOW;
  238. handle->Init.CLKPhase = SPI_PHASE_2EDGE;
  239. break;
  240. case 2:
  241. handle->Init.CLKPolarity = SPI_POLARITY_HIGH;
  242. handle->Init.CLKPhase = SPI_PHASE_1EDGE;
  243. break;
  244. default:
  245. handle->Init.CLKPolarity = SPI_POLARITY_HIGH;
  246. handle->Init.CLKPhase = SPI_PHASE_2EDGE;
  247. break;
  248. }
  249. if (handle->Init.NSS != SPI_NSS_SOFT) {
  250. handle->Init.NSS = (slave) ? SPI_NSS_HARD_INPUT : SPI_NSS_HARD_OUTPUT;
  251. }
  252. handle->Init.Mode = (slave) ? SPI_MODE_SLAVE : SPI_MODE_MASTER;
  253. if (slave && (handle->Init.Direction == SPI_DIRECTION_1LINE)) {
  254. /* SPI slave implemtation in MBED does not support the 3 wires SPI.
  255. * (e.g. when MISO is not connected). So we're forcing slave in
  256. * 2LINES mode. As MISO is not connected, slave will only read
  257. * from master, and cannot write to it. Inform user.
  258. */
  259. debug("3 wires SPI slave not supported - slave will only read\r\n");
  260. handle->Init.Direction = SPI_DIRECTION_2LINES;
  261. }
  262. init_spi(obj);
  263. }
  264. /*
  265. * Only the IP clock input is family dependant so it computed
  266. * separately in spi_get_clock_freq
  267. */
  268. extern int spi_get_clock_freq(spi_t *obj);
  269. static const uint16_t baudrate_prescaler_table[] = {SPI_BAUDRATEPRESCALER_2,
  270. SPI_BAUDRATEPRESCALER_4,
  271. SPI_BAUDRATEPRESCALER_8,
  272. SPI_BAUDRATEPRESCALER_16,
  273. SPI_BAUDRATEPRESCALER_32,
  274. SPI_BAUDRATEPRESCALER_64,
  275. SPI_BAUDRATEPRESCALER_128,
  276. SPI_BAUDRATEPRESCALER_256
  277. };
  278. void spi_frequency(spi_t *obj, int hz)
  279. {
  280. struct spi_s *spiobj = SPI_S(obj);
  281. int spi_hz = 0;
  282. uint8_t prescaler_rank = 0;
  283. uint8_t last_index = (sizeof(baudrate_prescaler_table) / sizeof(baudrate_prescaler_table[0])) - 1;
  284. SPI_HandleTypeDef *handle = &(spiobj->handle);
  285. /* Calculate the spi clock for prescaler_rank 0: SPI_BAUDRATEPRESCALER_2 */
  286. spi_hz = spi_get_clock_freq(obj) / 2;
  287. /* Define pre-scaler in order to get highest available frequency below requested frequency */
  288. while ((spi_hz > hz) && (prescaler_rank < last_index)) {
  289. spi_hz = spi_hz / 2;
  290. prescaler_rank++;
  291. }
  292. /* Use the best fit pre-scaler */
  293. handle->Init.BaudRatePrescaler = baudrate_prescaler_table[prescaler_rank];
  294. /* In case maximum pre-scaler still gives too high freq, raise an error */
  295. if (spi_hz > hz) {
  296. DEBUG_PRINTF("WARNING: lowest SPI freq (%d) higher than requested (%d)\r\n", spi_hz, hz);
  297. }
  298. DEBUG_PRINTF("spi_frequency, request:%d, select:%d\r\n", hz, spi_hz);
  299. init_spi(obj);
  300. }
  301. static inline int ssp_readable(spi_t *obj)
  302. {
  303. int status;
  304. struct spi_s *spiobj = SPI_S(obj);
  305. SPI_HandleTypeDef *handle = &(spiobj->handle);
  306. // Check if data is received
  307. status = ((__HAL_SPI_GET_FLAG(handle, SPI_FLAG_RXNE) != RESET) ? 1 : 0);
  308. return status;
  309. }
  310. static inline int ssp_writeable(spi_t *obj)
  311. {
  312. int status;
  313. struct spi_s *spiobj = SPI_S(obj);
  314. SPI_HandleTypeDef *handle = &(spiobj->handle);
  315. // Check if data is transmitted
  316. status = ((__HAL_SPI_GET_FLAG(handle, SPI_FLAG_TXE) != RESET) ? 1 : 0);
  317. return status;
  318. }
  319. static inline int ssp_busy(spi_t *obj)
  320. {
  321. int status;
  322. struct spi_s *spiobj = SPI_S(obj);
  323. SPI_HandleTypeDef *handle = &(spiobj->handle);
  324. status = ((__HAL_SPI_GET_FLAG(handle, SPI_FLAG_BSY) != RESET) ? 1 : 0);
  325. return status;
  326. }
  327. int spi_master_write(spi_t *obj, int value)
  328. {
  329. struct spi_s *spiobj = SPI_S(obj);
  330. SPI_HandleTypeDef *handle = &(spiobj->handle);
  331. if (handle->Init.Direction == SPI_DIRECTION_1LINE) {
  332. return HAL_SPI_Transmit(handle, (uint8_t *)&value, 1, TIMEOUT_1_BYTE);
  333. }
  334. #if defined(LL_SPI_RX_FIFO_TH_HALF)
  335. /* Configure the default data size */
  336. if (handle->Init.DataSize == SPI_DATASIZE_16BIT) {
  337. LL_SPI_SetRxFIFOThreshold(SPI_INST(obj), LL_SPI_RX_FIFO_TH_HALF);
  338. } else {
  339. LL_SPI_SetRxFIFOThreshold(SPI_INST(obj), LL_SPI_RX_FIFO_TH_QUARTER);
  340. }
  341. #endif
  342. /* Here we're using LL which means direct registers access
  343. * There is no error management, so we may end up looping
  344. * infinitely here in case of faulty device for insatnce,
  345. * but this will increase performances significantly
  346. */
  347. /* Wait TXE flag to transmit data */
  348. while (!LL_SPI_IsActiveFlag_TXE(SPI_INST(obj)));
  349. if (handle->Init.DataSize == SPI_DATASIZE_16BIT) {
  350. LL_SPI_TransmitData16(SPI_INST(obj), value);
  351. } else {
  352. LL_SPI_TransmitData8(SPI_INST(obj), (uint8_t) value);
  353. }
  354. /* Then wait RXE flag before reading */
  355. while (!LL_SPI_IsActiveFlag_RXNE(SPI_INST(obj)));
  356. if (handle->Init.DataSize == SPI_DATASIZE_16BIT) {
  357. return LL_SPI_ReceiveData16(SPI_INST(obj));
  358. } else {
  359. return LL_SPI_ReceiveData8(SPI_INST(obj));
  360. }
  361. }
  362. int spi_master_block_write(spi_t *obj, const char *tx_buffer, int tx_length,
  363. char *rx_buffer, int rx_length, char write_fill)
  364. {
  365. struct spi_s *spiobj = SPI_S(obj);
  366. SPI_HandleTypeDef *handle = &(spiobj->handle);
  367. int total = (tx_length > rx_length) ? tx_length : rx_length;
  368. int i = 0;
  369. if (handle->Init.Direction == SPI_DIRECTION_2LINES) {
  370. for (i = 0; i < total; i++) {
  371. char out = (i < tx_length) ? tx_buffer[i] : write_fill;
  372. char in = spi_master_write(obj, out);
  373. if (i < rx_length) {
  374. rx_buffer[i] = in;
  375. }
  376. }
  377. } else {
  378. /* In case of 1 WIRE only, first handle TX, then Rx */
  379. if (tx_length != 0) {
  380. if (HAL_OK != HAL_SPI_Transmit(handle, (uint8_t *)tx_buffer, tx_length, tx_length * TIMEOUT_1_BYTE)) {
  381. /* report an error */
  382. total = 0;
  383. }
  384. }
  385. if (rx_length != 0) {
  386. if (HAL_OK != HAL_SPI_Receive(handle, (uint8_t *)rx_buffer, rx_length, rx_length * TIMEOUT_1_BYTE)) {
  387. /* report an error */
  388. total = 0;
  389. }
  390. }
  391. }
  392. return total;
  393. }
  394. int spi_slave_receive(spi_t *obj)
  395. {
  396. return ((ssp_readable(obj) && !ssp_busy(obj)) ? 1 : 0);
  397. };
  398. int spi_slave_read(spi_t *obj)
  399. {
  400. struct spi_s *spiobj = SPI_S(obj);
  401. SPI_HandleTypeDef *handle = &(spiobj->handle);
  402. while (!ssp_readable(obj));
  403. if (handle->Init.DataSize == SPI_DATASIZE_16BIT) {
  404. return LL_SPI_ReceiveData16(SPI_INST(obj));
  405. } else {
  406. return LL_SPI_ReceiveData8(SPI_INST(obj));
  407. }
  408. }
  409. void spi_slave_write(spi_t *obj, int value)
  410. {
  411. SPI_TypeDef *spi = SPI_INST(obj);
  412. struct spi_s *spiobj = SPI_S(obj);
  413. SPI_HandleTypeDef *handle = &(spiobj->handle);
  414. while (!ssp_writeable(obj));
  415. if (handle->Init.DataSize == SPI_DATASIZE_8BIT) {
  416. // Force 8-bit access to the data register
  417. uint8_t *p_spi_dr = 0;
  418. p_spi_dr = (uint8_t *) & (spi->DR);
  419. *p_spi_dr = (uint8_t)value;
  420. } else { // SPI_DATASIZE_16BIT
  421. spi->DR = (uint16_t)value;
  422. }
  423. }
  424. int spi_busy(spi_t *obj)
  425. {
  426. return ssp_busy(obj);
  427. }
  428. #ifdef DEVICE_SPI_ASYNCH
  429. typedef enum {
  430. SPI_TRANSFER_TYPE_NONE = 0,
  431. SPI_TRANSFER_TYPE_TX = 1,
  432. SPI_TRANSFER_TYPE_RX = 2,
  433. SPI_TRANSFER_TYPE_TXRX = 3,
  434. } transfer_type_t;
  435. /// @returns the number of bytes transferred, or `0` if nothing transferred
  436. static int spi_master_start_asynch_transfer(spi_t *obj, transfer_type_t transfer_type, const void *tx, void *rx, size_t length)
  437. {
  438. struct spi_s *spiobj = SPI_S(obj);
  439. SPI_HandleTypeDef *handle = &(spiobj->handle);
  440. bool is16bit = (handle->Init.DataSize == SPI_DATASIZE_16BIT);
  441. // the HAL expects number of transfers instead of number of bytes
  442. // so for 16 bit transfer width the count needs to be halved
  443. size_t words;
  444. DEBUG_PRINTF("SPI inst=0x%8X Start: %u, %u\r\n", (int)handle->Instance, transfer_type, length);
  445. obj->spi.transfer_type = transfer_type;
  446. if (is16bit) {
  447. words = length / 2;
  448. } else {
  449. words = length;
  450. }
  451. // enable the interrupt
  452. IRQn_Type irq_n = spiobj->spiIRQ;
  453. NVIC_DisableIRQ(irq_n);
  454. NVIC_ClearPendingIRQ(irq_n);
  455. NVIC_SetPriority(irq_n, 1);
  456. NVIC_EnableIRQ(irq_n);
  457. // flush FIFO
  458. #if defined(SPI_FLAG_FRLVL) // STM32F0 STM32F3 STM32F7 STM32L4
  459. HAL_SPIEx_FlushRxFifo(handle);
  460. #endif
  461. // enable the right hal transfer
  462. int rc = 0;
  463. switch (transfer_type) {
  464. case SPI_TRANSFER_TYPE_TXRX:
  465. rc = HAL_SPI_TransmitReceive_IT(handle, (uint8_t *)tx, (uint8_t *)rx, words);
  466. break;
  467. case SPI_TRANSFER_TYPE_TX:
  468. rc = HAL_SPI_Transmit_IT(handle, (uint8_t *)tx, words);
  469. break;
  470. case SPI_TRANSFER_TYPE_RX:
  471. // the receive function also "transmits" the receive buffer so in order
  472. // to guarantee that 0xff is on the line, we explicitly memset it here
  473. memset(rx, SPI_FILL_WORD, length);
  474. rc = HAL_SPI_Receive_IT(handle, (uint8_t *)rx, words);
  475. break;
  476. default:
  477. length = 0;
  478. }
  479. if (rc) {
  480. DEBUG_PRINTF("SPI: RC=%u\n", rc);
  481. length = 0;
  482. }
  483. return length;
  484. }
  485. // asynchronous API
  486. void spi_master_transfer(spi_t *obj, const void *tx, size_t tx_length, void *rx, size_t rx_length, uint8_t bit_width, uint32_t handler, uint32_t event, DMAUsage hint)
  487. {
  488. struct spi_s *spiobj = SPI_S(obj);
  489. SPI_HandleTypeDef *handle = &(spiobj->handle);
  490. // TODO: DMA usage is currently ignored
  491. (void) hint;
  492. // check which use-case we have
  493. bool use_tx = (tx != NULL && tx_length > 0);
  494. bool use_rx = (rx != NULL && rx_length > 0);
  495. bool is16bit = (handle->Init.DataSize == SPI_DATASIZE_16BIT);
  496. // don't do anything, if the buffers aren't valid
  497. if (!use_tx && !use_rx) {
  498. return;
  499. }
  500. // copy the buffers to the SPI object
  501. obj->tx_buff.buffer = (void *) tx;
  502. obj->tx_buff.length = tx_length;
  503. obj->tx_buff.pos = 0;
  504. obj->tx_buff.width = is16bit ? 16 : 8;
  505. obj->rx_buff.buffer = rx;
  506. obj->rx_buff.length = rx_length;
  507. obj->rx_buff.pos = 0;
  508. obj->rx_buff.width = obj->tx_buff.width;
  509. obj->spi.event = event;
  510. DEBUG_PRINTF("SPI: Transfer: %u, %u\n", tx_length, rx_length);
  511. // register the thunking handler
  512. IRQn_Type irq_n = spiobj->spiIRQ;
  513. NVIC_SetVector(irq_n, (uint32_t)handler);
  514. // enable the right hal transfer
  515. if (use_tx && use_rx) {
  516. // we cannot manage different rx / tx sizes, let's use smaller one
  517. size_t size = (tx_length < rx_length) ? tx_length : rx_length;
  518. if (tx_length != rx_length) {
  519. DEBUG_PRINTF("SPI: Full duplex transfer only 1 size: %d\n", size);
  520. obj->tx_buff.length = size;
  521. obj->rx_buff.length = size;
  522. }
  523. spi_master_start_asynch_transfer(obj, SPI_TRANSFER_TYPE_TXRX, tx, rx, size);
  524. } else if (use_tx) {
  525. spi_master_start_asynch_transfer(obj, SPI_TRANSFER_TYPE_TX, tx, NULL, tx_length);
  526. } else if (use_rx) {
  527. spi_master_start_asynch_transfer(obj, SPI_TRANSFER_TYPE_RX, NULL, rx, rx_length);
  528. }
  529. }
  530. inline uint32_t spi_irq_handler_asynch(spi_t *obj)
  531. {
  532. int event = 0;
  533. // call the CubeF4 handler, this will update the handle
  534. HAL_SPI_IRQHandler(&obj->spi.handle);
  535. if (obj->spi.handle.State == HAL_SPI_STATE_READY) {
  536. // When HAL SPI is back to READY state, check if there was an error
  537. int error = obj->spi.handle.ErrorCode;
  538. if (error != HAL_SPI_ERROR_NONE) {
  539. // something went wrong and the transfer has definitely completed
  540. event = SPI_EVENT_ERROR | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE;
  541. if (error & HAL_SPI_ERROR_OVR) {
  542. // buffer overrun
  543. event |= SPI_EVENT_RX_OVERFLOW;
  544. }
  545. } else {
  546. // else we're done
  547. event = SPI_EVENT_COMPLETE | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE;
  548. }
  549. // enable the interrupt
  550. NVIC_DisableIRQ(obj->spi.spiIRQ);
  551. NVIC_ClearPendingIRQ(obj->spi.spiIRQ);
  552. }
  553. return (event & (obj->spi.event | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE));
  554. }
  555. uint8_t spi_active(spi_t *obj)
  556. {
  557. struct spi_s *spiobj = SPI_S(obj);
  558. SPI_HandleTypeDef *handle = &(spiobj->handle);
  559. HAL_SPI_StateTypeDef state = HAL_SPI_GetState(handle);
  560. switch (state) {
  561. case HAL_SPI_STATE_RESET:
  562. case HAL_SPI_STATE_READY:
  563. case HAL_SPI_STATE_ERROR:
  564. return 0;
  565. default:
  566. return 1;
  567. }
  568. }
  569. void spi_abort_asynch(spi_t *obj)
  570. {
  571. struct spi_s *spiobj = SPI_S(obj);
  572. SPI_HandleTypeDef *handle = &(spiobj->handle);
  573. // disable interrupt
  574. IRQn_Type irq_n = spiobj->spiIRQ;
  575. NVIC_ClearPendingIRQ(irq_n);
  576. NVIC_DisableIRQ(irq_n);
  577. // clean-up
  578. __HAL_SPI_DISABLE(handle);
  579. HAL_SPI_DeInit(handle);
  580. HAL_SPI_Init(handle);
  581. __HAL_SPI_ENABLE(handle);
  582. }
  583. #endif //DEVICE_SPI_ASYNCH
  584. #endif