You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2243 lines
82 KiB

  1. /*
  2. * Copyright (c) 2015, Freescale Semiconductor, Inc.
  3. * Copyright 2016-2019 NXP
  4. * All rights reserved.
  5. *
  6. * SPDX-License-Identifier: BSD-3-Clause
  7. */
  8. #include "fsl_dspi.h"
  9. /*******************************************************************************
  10. * Definitions
  11. ******************************************************************************/
  12. /* Component ID definition, used by tools. */
  13. #ifndef FSL_COMPONENT_ID
  14. #define FSL_COMPONENT_ID "platform.drivers.dspi"
  15. #endif
  16. /*! @brief Typedef for master interrupt handler. */
  17. typedef void (*dspi_master_isr_t)(SPI_Type *base, dspi_master_handle_t *handle);
  18. /*! @brief Typedef for slave interrupt handler. */
  19. typedef void (*dspi_slave_isr_t)(SPI_Type *base, dspi_slave_handle_t *handle);
  20. /*******************************************************************************
  21. * Prototypes
  22. ******************************************************************************/
  23. /*!
  24. * @brief Configures the DSPI peripheral chip select polarity.
  25. *
  26. * This function takes in the desired peripheral chip select (Pcs) and it's corresponding desired polarity and
  27. * configures the Pcs signal to operate with the desired characteristic.
  28. *
  29. * @param base DSPI peripheral address.
  30. * @param pcs The particular peripheral chip select (parameter value is of type dspi_which_pcs_t) for which we wish to
  31. * apply the active high or active low characteristic.
  32. * @param activeLowOrHigh The setting for either "active high, inactive low (0)" or "active low, inactive high(1)" of
  33. * type dspi_pcs_polarity_config_t.
  34. */
  35. static void DSPI_SetOnePcsPolarity(SPI_Type *base, dspi_which_pcs_t pcs, dspi_pcs_polarity_config_t activeLowOrHigh);
  36. /*!
  37. * @brief Master fill up the TX FIFO with data.
  38. * This is not a public API.
  39. */
  40. static void DSPI_MasterTransferFillUpTxFifo(SPI_Type *base, dspi_master_handle_t *handle);
  41. /*!
  42. * @brief Master finish up a transfer.
  43. * It would call back if there is callback function and set the state to idle.
  44. * This is not a public API.
  45. */
  46. static void DSPI_MasterTransferComplete(SPI_Type *base, dspi_master_handle_t *handle);
  47. /*!
  48. * @brief Slave fill up the TX FIFO with data.
  49. * This is not a public API.
  50. */
  51. static void DSPI_SlaveTransferFillUpTxFifo(SPI_Type *base, dspi_slave_handle_t *handle);
  52. /*!
  53. * @brief Slave finish up a transfer.
  54. * It would call back if there is callback function and set the state to idle.
  55. * This is not a public API.
  56. */
  57. static void DSPI_SlaveTransferComplete(SPI_Type *base, dspi_slave_handle_t *handle);
  58. /*!
  59. * @brief DSPI common interrupt handler.
  60. *
  61. * @param base DSPI peripheral address.
  62. * @param handle pointer to g_dspiHandle which stores the transfer state.
  63. */
  64. static void DSPI_CommonIRQHandler(SPI_Type *base, void *param);
  65. /*!
  66. * @brief Master prepare the transfer.
  67. * Basically it set up dspi_master_handle .
  68. * This is not a public API.
  69. */
  70. static void DSPI_MasterTransferPrepare(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer);
  71. /*******************************************************************************
  72. * Variables
  73. ******************************************************************************/
  74. /* Defines constant value arrays for the baud rate pre-scalar and scalar divider values.*/
  75. static const uint32_t s_baudratePrescaler[] = {2, 3, 5, 7};
  76. static const uint32_t s_baudrateScaler[] = {2, 4, 6, 8, 16, 32, 64, 128,
  77. 256, 512, 1024, 2048, 4096, 8192, 16384, 32768};
  78. static const uint32_t s_delayPrescaler[] = {1, 3, 5, 7};
  79. static const uint32_t s_delayScaler[] = {2, 4, 8, 16, 32, 64, 128, 256,
  80. 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536};
  81. /*! @brief Pointers to dspi bases for each instance. */
  82. static SPI_Type *const s_dspiBases[] = SPI_BASE_PTRS;
  83. /*! @brief Pointers to dspi IRQ number for each instance. */
  84. static IRQn_Type const s_dspiIRQ[] = SPI_IRQS;
  85. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  86. /*! @brief Pointers to dspi clocks for each instance. */
  87. static clock_ip_name_t const s_dspiClock[] = DSPI_CLOCKS;
  88. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  89. /*! @brief Pointers to dspi handles for each instance. */
  90. static void *g_dspiHandle[ARRAY_SIZE(s_dspiBases)];
  91. /*! @brief Pointer to master IRQ handler for each instance. */
  92. static dspi_master_isr_t s_dspiMasterIsr;
  93. /*! @brief Pointer to slave IRQ handler for each instance. */
  94. static dspi_slave_isr_t s_dspiSlaveIsr;
  95. /* @brief Dummy data for each instance. This data is used when user's tx buffer is NULL*/
  96. volatile uint8_t g_dspiDummyData[ARRAY_SIZE(s_dspiBases)] = {0};
  97. /**********************************************************************************************************************
  98. * Code
  99. *********************************************************************************************************************/
  100. /*!
  101. * brief Get instance number for DSPI module.
  102. *
  103. * param base DSPI peripheral base address.
  104. */
  105. uint32_t DSPI_GetInstance(SPI_Type *base)
  106. {
  107. uint32_t instance;
  108. /* Find the instance index from base address mappings. */
  109. for (instance = 0; instance < ARRAY_SIZE(s_dspiBases); instance++)
  110. {
  111. if (s_dspiBases[instance] == base)
  112. {
  113. break;
  114. }
  115. }
  116. assert(instance < ARRAY_SIZE(s_dspiBases));
  117. return instance;
  118. }
  119. /*!
  120. * brief Dummy data for each instance.
  121. *
  122. * The purpose of this API is to avoid MISRA rule8.5 : Multiple declarations of
  123. * externally-linked object or function g_dspiDummyData.
  124. *
  125. * param base DSPI peripheral base address.
  126. */
  127. uint8_t DSPI_GetDummyDataInstance(SPI_Type *base)
  128. {
  129. uint8_t instance = g_dspiDummyData[DSPI_GetInstance(base)];
  130. return instance;
  131. }
  132. /*!
  133. * brief Set up the dummy data.
  134. *
  135. * param base DSPI peripheral address.
  136. * param dummyData Data to be transferred when tx buffer is NULL.
  137. */
  138. void DSPI_SetDummyData(SPI_Type *base, uint8_t dummyData)
  139. {
  140. uint32_t instance = DSPI_GetInstance(base);
  141. g_dspiDummyData[instance] = dummyData;
  142. }
  143. /*!
  144. * brief Initializes the DSPI master.
  145. *
  146. * This function initializes the DSPI master configuration. This is an example use case.
  147. * code
  148. * dspi_master_config_t masterConfig;
  149. * masterConfig.whichCtar = kDSPI_Ctar0;
  150. * masterConfig.ctarConfig.baudRate = 500000000U;
  151. * masterConfig.ctarConfig.bitsPerFrame = 8;
  152. * masterConfig.ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh;
  153. * masterConfig.ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge;
  154. * masterConfig.ctarConfig.direction = kDSPI_MsbFirst;
  155. * masterConfig.ctarConfig.pcsToSckDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ;
  156. * masterConfig.ctarConfig.lastSckToPcsDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ;
  157. * masterConfig.ctarConfig.betweenTransferDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ;
  158. * masterConfig.whichPcs = kDSPI_Pcs0;
  159. * masterConfig.pcsActiveHighOrLow = kDSPI_PcsActiveLow;
  160. * masterConfig.enableContinuousSCK = false;
  161. * masterConfig.enableRxFifoOverWrite = false;
  162. * masterConfig.enableModifiedTimingFormat = false;
  163. * masterConfig.samplePoint = kDSPI_SckToSin0Clock;
  164. * DSPI_MasterInit(base, &masterConfig, srcClock_Hz);
  165. * endcode
  166. *
  167. * param base DSPI peripheral address.
  168. * param masterConfig Pointer to the structure dspi_master_config_t.
  169. * param srcClock_Hz Module source input clock in Hertz.
  170. */
  171. void DSPI_MasterInit(SPI_Type *base, const dspi_master_config_t *masterConfig, uint32_t srcClock_Hz)
  172. {
  173. assert(NULL != masterConfig);
  174. uint32_t temp;
  175. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  176. /* enable DSPI clock */
  177. CLOCK_EnableClock(s_dspiClock[DSPI_GetInstance(base)]);
  178. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  179. DSPI_Enable(base, true);
  180. DSPI_StopTransfer(base);
  181. DSPI_SetOnePcsPolarity(base, masterConfig->whichPcs, masterConfig->pcsActiveHighOrLow);
  182. DSPI_SetMasterSlaveMode(base, kDSPI_Master);
  183. temp = base->MCR & (~(SPI_MCR_CONT_SCKE_MASK | SPI_MCR_MTFE_MASK | SPI_MCR_ROOE_MASK | SPI_MCR_SMPL_PT_MASK |
  184. SPI_MCR_DIS_TXF_MASK | SPI_MCR_DIS_RXF_MASK));
  185. base->MCR = temp | SPI_MCR_CONT_SCKE(masterConfig->enableContinuousSCK) |
  186. SPI_MCR_MTFE(masterConfig->enableModifiedTimingFormat) |
  187. SPI_MCR_ROOE(masterConfig->enableRxFifoOverWrite) | SPI_MCR_SMPL_PT(masterConfig->samplePoint) |
  188. SPI_MCR_DIS_TXF(0U) | SPI_MCR_DIS_RXF(0U);
  189. if (0U == DSPI_MasterSetBaudRate(base, masterConfig->whichCtar, masterConfig->ctarConfig.baudRate, srcClock_Hz))
  190. {
  191. assert(false);
  192. }
  193. temp = base->CTAR[masterConfig->whichCtar] &
  194. ~(SPI_CTAR_FMSZ_MASK | SPI_CTAR_CPOL_MASK | SPI_CTAR_CPHA_MASK | SPI_CTAR_LSBFE_MASK);
  195. base->CTAR[masterConfig->whichCtar] = temp | SPI_CTAR_FMSZ(masterConfig->ctarConfig.bitsPerFrame - 1U) |
  196. SPI_CTAR_CPOL(masterConfig->ctarConfig.cpol) |
  197. SPI_CTAR_CPHA(masterConfig->ctarConfig.cpha) |
  198. SPI_CTAR_LSBFE(masterConfig->ctarConfig.direction);
  199. (void)DSPI_MasterSetDelayTimes(base, masterConfig->whichCtar, kDSPI_PcsToSck, srcClock_Hz,
  200. masterConfig->ctarConfig.pcsToSckDelayInNanoSec);
  201. (void)DSPI_MasterSetDelayTimes(base, masterConfig->whichCtar, kDSPI_LastSckToPcs, srcClock_Hz,
  202. masterConfig->ctarConfig.lastSckToPcsDelayInNanoSec);
  203. (void)DSPI_MasterSetDelayTimes(base, masterConfig->whichCtar, kDSPI_BetweenTransfer, srcClock_Hz,
  204. masterConfig->ctarConfig.betweenTransferDelayInNanoSec);
  205. DSPI_SetDummyData(base, DSPI_DUMMY_DATA);
  206. DSPI_StartTransfer(base);
  207. }
  208. /*!
  209. * brief Sets the dspi_master_config_t structure to default values.
  210. *
  211. * The purpose of this API is to get the configuration structure initialized for the DSPI_MasterInit().
  212. * Users may use the initialized structure unchanged in the DSPI_MasterInit() or modify the structure
  213. * before calling the DSPI_MasterInit().
  214. * Example:
  215. * code
  216. * dspi_master_config_t masterConfig;
  217. * DSPI_MasterGetDefaultConfig(&masterConfig);
  218. * endcode
  219. * param masterConfig pointer to dspi_master_config_t structure
  220. */
  221. void DSPI_MasterGetDefaultConfig(dspi_master_config_t *masterConfig)
  222. {
  223. assert(NULL != masterConfig);
  224. /* Initializes the configure structure to zero. */
  225. (void)memset(masterConfig, 0, sizeof(*masterConfig));
  226. masterConfig->whichCtar = kDSPI_Ctar0;
  227. masterConfig->ctarConfig.baudRate = 500000;
  228. masterConfig->ctarConfig.bitsPerFrame = 8;
  229. masterConfig->ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh;
  230. masterConfig->ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge;
  231. masterConfig->ctarConfig.direction = kDSPI_MsbFirst;
  232. masterConfig->ctarConfig.pcsToSckDelayInNanoSec = 1000;
  233. masterConfig->ctarConfig.lastSckToPcsDelayInNanoSec = 1000;
  234. masterConfig->ctarConfig.betweenTransferDelayInNanoSec = 1000;
  235. masterConfig->whichPcs = kDSPI_Pcs0;
  236. masterConfig->pcsActiveHighOrLow = kDSPI_PcsActiveLow;
  237. masterConfig->enableContinuousSCK = false;
  238. masterConfig->enableRxFifoOverWrite = false;
  239. masterConfig->enableModifiedTimingFormat = false;
  240. masterConfig->samplePoint = kDSPI_SckToSin0Clock;
  241. }
  242. /*!
  243. * brief DSPI slave configuration.
  244. *
  245. * This function initializes the DSPI slave configuration. This is an example use case.
  246. * code
  247. * dspi_slave_config_t slaveConfig;
  248. * slaveConfig->whichCtar = kDSPI_Ctar0;
  249. * slaveConfig->ctarConfig.bitsPerFrame = 8;
  250. * slaveConfig->ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh;
  251. * slaveConfig->ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge;
  252. * slaveConfig->enableContinuousSCK = false;
  253. * slaveConfig->enableRxFifoOverWrite = false;
  254. * slaveConfig->enableModifiedTimingFormat = false;
  255. * slaveConfig->samplePoint = kDSPI_SckToSin0Clock;
  256. * DSPI_SlaveInit(base, &slaveConfig);
  257. * endcode
  258. *
  259. * param base DSPI peripheral address.
  260. * param slaveConfig Pointer to the structure dspi_master_config_t.
  261. */
  262. void DSPI_SlaveInit(SPI_Type *base, const dspi_slave_config_t *slaveConfig)
  263. {
  264. assert(NULL != slaveConfig);
  265. uint32_t temp = 0;
  266. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  267. /* enable DSPI clock */
  268. CLOCK_EnableClock(s_dspiClock[DSPI_GetInstance(base)]);
  269. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  270. DSPI_Enable(base, true);
  271. DSPI_StopTransfer(base);
  272. DSPI_SetMasterSlaveMode(base, kDSPI_Slave);
  273. temp = base->MCR & (~(SPI_MCR_CONT_SCKE_MASK | SPI_MCR_MTFE_MASK | SPI_MCR_ROOE_MASK | SPI_MCR_SMPL_PT_MASK |
  274. SPI_MCR_DIS_TXF_MASK | SPI_MCR_DIS_RXF_MASK));
  275. base->MCR = temp | SPI_MCR_CONT_SCKE(slaveConfig->enableContinuousSCK) |
  276. SPI_MCR_MTFE(slaveConfig->enableModifiedTimingFormat) |
  277. SPI_MCR_ROOE(slaveConfig->enableRxFifoOverWrite) | SPI_MCR_SMPL_PT(slaveConfig->samplePoint) |
  278. SPI_MCR_DIS_TXF(0U) | SPI_MCR_DIS_RXF(0U);
  279. DSPI_SetOnePcsPolarity(base, kDSPI_Pcs0, kDSPI_PcsActiveLow);
  280. temp = base->CTAR[slaveConfig->whichCtar] &
  281. ~(SPI_CTAR_FMSZ_MASK | SPI_CTAR_CPOL_MASK | SPI_CTAR_CPHA_MASK | SPI_CTAR_LSBFE_MASK);
  282. base->CTAR[slaveConfig->whichCtar] = temp | SPI_CTAR_SLAVE_FMSZ(slaveConfig->ctarConfig.bitsPerFrame - 1U) |
  283. SPI_CTAR_SLAVE_CPOL(slaveConfig->ctarConfig.cpol) |
  284. SPI_CTAR_SLAVE_CPHA(slaveConfig->ctarConfig.cpha);
  285. DSPI_SetDummyData(base, DSPI_DUMMY_DATA);
  286. DSPI_StartTransfer(base);
  287. }
  288. /*!
  289. * brief Sets the dspi_slave_config_t structure to a default value.
  290. *
  291. * The purpose of this API is to get the configuration structure initialized for the DSPI_SlaveInit().
  292. * Users may use the initialized structure unchanged in the DSPI_SlaveInit() or modify the structure
  293. * before calling the DSPI_SlaveInit().
  294. * This is an example.
  295. * code
  296. * dspi_slave_config_t slaveConfig;
  297. * DSPI_SlaveGetDefaultConfig(&slaveConfig);
  298. * endcode
  299. * param slaveConfig Pointer to the dspi_slave_config_t structure.
  300. */
  301. void DSPI_SlaveGetDefaultConfig(dspi_slave_config_t *slaveConfig)
  302. {
  303. assert(NULL != slaveConfig);
  304. /* Initializes the configure structure to zero. */
  305. (void)memset(slaveConfig, 0, sizeof(*slaveConfig));
  306. slaveConfig->whichCtar = kDSPI_Ctar0;
  307. slaveConfig->ctarConfig.bitsPerFrame = 8;
  308. slaveConfig->ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh;
  309. slaveConfig->ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge;
  310. slaveConfig->enableContinuousSCK = false;
  311. slaveConfig->enableRxFifoOverWrite = false;
  312. slaveConfig->enableModifiedTimingFormat = false;
  313. slaveConfig->samplePoint = kDSPI_SckToSin0Clock;
  314. }
  315. /*!
  316. * brief De-initializes the DSPI peripheral. Call this API to disable the DSPI clock.
  317. * param base DSPI peripheral address.
  318. */
  319. void DSPI_Deinit(SPI_Type *base)
  320. {
  321. DSPI_StopTransfer(base);
  322. DSPI_Enable(base, false);
  323. #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
  324. /* disable DSPI clock */
  325. CLOCK_DisableClock(s_dspiClock[DSPI_GetInstance(base)]);
  326. #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
  327. }
  328. static void DSPI_SetOnePcsPolarity(SPI_Type *base, dspi_which_pcs_t pcs, dspi_pcs_polarity_config_t activeLowOrHigh)
  329. {
  330. uint32_t temp;
  331. temp = base->MCR;
  332. if (activeLowOrHigh == kDSPI_PcsActiveLow)
  333. {
  334. temp |= SPI_MCR_PCSIS(pcs);
  335. }
  336. else
  337. {
  338. temp &= ~SPI_MCR_PCSIS(pcs);
  339. }
  340. base->MCR = temp;
  341. }
  342. /*!
  343. * brief Sets the DSPI baud rate in bits per second.
  344. *
  345. * This function takes in the desired baudRate_Bps (baud rate) and calculates the nearest possible baud rate without
  346. * exceeding the desired baud rate, and returns the calculated baud rate in bits-per-second. It requires that the
  347. * caller also provide the frequency of the module source clock (in Hertz).
  348. *
  349. * param base DSPI peripheral address.
  350. * param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of the type dspi_ctar_selection_t
  351. * param baudRate_Bps The desired baud rate in bits per second
  352. * param srcClock_Hz Module source input clock in Hertz
  353. * return The actual calculated baud rate
  354. */
  355. uint32_t DSPI_MasterSetBaudRate(SPI_Type *base,
  356. dspi_ctar_selection_t whichCtar,
  357. uint32_t baudRate_Bps,
  358. uint32_t srcClock_Hz)
  359. {
  360. /* for master mode configuration, if slave mode detected, return 0*/
  361. if (!DSPI_IsMaster(base))
  362. {
  363. return 0U;
  364. }
  365. uint32_t temp;
  366. uint32_t prescaler, bestPrescaler;
  367. uint32_t scaler, bestScaler;
  368. uint32_t dbr, bestDbr;
  369. uint32_t realBaudrate, bestBaudrate;
  370. uint32_t diff, min_diff;
  371. uint32_t baudrate = baudRate_Bps;
  372. /* find combination of prescaler and scaler resulting in baudrate closest to the requested value */
  373. min_diff = 0xFFFFFFFFU;
  374. bestPrescaler = 0;
  375. bestScaler = 0;
  376. bestDbr = 1;
  377. bestBaudrate = 0; /* required to avoid compilation warning */
  378. /* In all for loops, if min_diff = 0, the exit for loop*/
  379. for (prescaler = 0U; prescaler < 4U; prescaler++)
  380. {
  381. for (scaler = 0U; scaler < 16U; scaler++)
  382. {
  383. for (dbr = 1U; dbr < 3U; dbr++)
  384. {
  385. realBaudrate = ((srcClock_Hz * dbr) / (s_baudratePrescaler[prescaler] * (s_baudrateScaler[scaler])));
  386. /* calculate the baud rate difference based on the conditional statement that states that the calculated
  387. * baud rate must not exceed the desired baud rate.
  388. */
  389. if (baudrate >= realBaudrate)
  390. {
  391. diff = baudrate - realBaudrate;
  392. if (min_diff > diff)
  393. {
  394. /* a better match found */
  395. min_diff = diff;
  396. bestPrescaler = prescaler;
  397. bestScaler = scaler;
  398. bestBaudrate = realBaudrate;
  399. bestDbr = dbr;
  400. }
  401. }
  402. if (0U == min_diff)
  403. {
  404. break;
  405. }
  406. }
  407. if (0U == min_diff)
  408. {
  409. break;
  410. }
  411. }
  412. if (0U == min_diff)
  413. {
  414. break;
  415. }
  416. }
  417. /* write the best dbr, prescalar, and baud rate scalar to the CTAR */
  418. temp = base->CTAR[whichCtar] & ~(SPI_CTAR_DBR_MASK | SPI_CTAR_PBR_MASK | SPI_CTAR_BR_MASK);
  419. base->CTAR[whichCtar] = temp | ((bestDbr - 1U) << SPI_CTAR_DBR_SHIFT) | (bestPrescaler << SPI_CTAR_PBR_SHIFT) |
  420. (bestScaler << SPI_CTAR_BR_SHIFT);
  421. /* return the actual calculated baud rate */
  422. return bestBaudrate;
  423. }
  424. /*!
  425. * brief Manually configures the delay prescaler and scaler for a particular CTAR.
  426. *
  427. * This function configures the PCS to SCK delay pre-scalar (PcsSCK) and scalar (CSSCK), after SCK delay pre-scalar
  428. * (PASC) and scalar (ASC), and the delay after transfer pre-scalar (PDT) and scalar (DT).
  429. *
  430. * These delay names are available in the type dspi_delay_type_t.
  431. *
  432. * The user passes the delay to the configuration along with the prescaler and scaler value.
  433. * This allows the user to directly set the prescaler/scaler values if pre-calculated or
  434. * to manually increment either value.
  435. *
  436. * param base DSPI peripheral address.
  437. * param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type dspi_ctar_selection_t.
  438. * param prescaler The prescaler delay value (can be an integer 0, 1, 2, or 3).
  439. * param scaler The scaler delay value (can be any integer between 0 to 15).
  440. * param whichDelay The desired delay to configure; must be of type dspi_delay_type_t
  441. */
  442. void DSPI_MasterSetDelayScaler(
  443. SPI_Type *base, dspi_ctar_selection_t whichCtar, uint32_t prescaler, uint32_t scaler, dspi_delay_type_t whichDelay)
  444. {
  445. /* these settings are only relevant in master mode */
  446. if (DSPI_IsMaster(base))
  447. {
  448. switch (whichDelay)
  449. {
  450. case kDSPI_PcsToSck:
  451. base->CTAR[whichCtar] = (base->CTAR[whichCtar] & (~SPI_CTAR_PCSSCK_MASK) & (~SPI_CTAR_CSSCK_MASK)) |
  452. SPI_CTAR_PCSSCK(prescaler) | SPI_CTAR_CSSCK(scaler);
  453. break;
  454. case kDSPI_LastSckToPcs:
  455. base->CTAR[whichCtar] = (base->CTAR[whichCtar] & (~SPI_CTAR_PASC_MASK) & (~SPI_CTAR_ASC_MASK)) |
  456. SPI_CTAR_PASC(prescaler) | SPI_CTAR_ASC(scaler);
  457. break;
  458. case kDSPI_BetweenTransfer:
  459. base->CTAR[whichCtar] = (base->CTAR[whichCtar] & (~SPI_CTAR_PDT_MASK) & (~SPI_CTAR_DT_MASK)) |
  460. SPI_CTAR_PDT(prescaler) | SPI_CTAR_DT(scaler);
  461. break;
  462. default:
  463. /* All cases have been listed above, the default clause should not be reached. */
  464. assert(false);
  465. break;
  466. }
  467. }
  468. }
  469. /*!
  470. * brief Calculates the delay prescaler and scaler based on the desired delay input in nanoseconds.
  471. *
  472. * This function calculates the values for the following.
  473. * PCS to SCK delay pre-scalar (PCSSCK) and scalar (CSSCK), or
  474. * After SCK delay pre-scalar (PASC) and scalar (ASC), or
  475. * Delay after transfer pre-scalar (PDT) and scalar (DT).
  476. *
  477. * These delay names are available in the type dspi_delay_type_t.
  478. *
  479. * The user passes which delay to configure along with the desired delay value in nanoseconds. The function
  480. * calculates the values needed for the prescaler and scaler. Note that returning the calculated delay as an exact
  481. * delay match may not be possible. In this case, the closest match is calculated without going below the desired
  482. * delay value input.
  483. * It is possible to input a very large delay value that exceeds the capability of the part, in which case the maximum
  484. * supported delay is returned. The higher-level peripheral driver alerts the user of an out of range delay
  485. * input.
  486. *
  487. * param base DSPI peripheral address.
  488. * param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type dspi_ctar_selection_t.
  489. * param whichDelay The desired delay to configure, must be of type dspi_delay_type_t
  490. * param srcClock_Hz Module source input clock in Hertz
  491. * param delayTimeInNanoSec The desired delay value in nanoseconds.
  492. * return The actual calculated delay value.
  493. */
  494. uint32_t DSPI_MasterSetDelayTimes(SPI_Type *base,
  495. dspi_ctar_selection_t whichCtar,
  496. dspi_delay_type_t whichDelay,
  497. uint32_t srcClock_Hz,
  498. uint32_t delayTimeInNanoSec)
  499. {
  500. /* for master mode configuration, if slave mode detected, return 0 */
  501. if (!DSPI_IsMaster(base))
  502. {
  503. return 0U;
  504. }
  505. uint32_t prescaler, bestPrescaler;
  506. uint32_t scaler, bestScaler;
  507. uint32_t realDelay, bestDelay;
  508. uint32_t diff, min_diff;
  509. uint32_t initialDelayNanoSec;
  510. /* find combination of prescaler and scaler resulting in the delay closest to the
  511. * requested value
  512. */
  513. min_diff = 0xFFFFFFFFU;
  514. /* Initialize prescaler and scaler to their max values to generate the max delay */
  515. bestPrescaler = 0x3;
  516. bestScaler = 0xF;
  517. bestDelay = (((1000000000U * 4U) / srcClock_Hz) * s_delayPrescaler[bestPrescaler] * s_delayScaler[bestScaler]) / 4U;
  518. /* First calculate the initial, default delay */
  519. initialDelayNanoSec = 1000000000U / srcClock_Hz * 2U;
  520. /* If the initial, default delay is already greater than the desired delay, then
  521. * set the delays to their initial value (0) and return the delay. In other words,
  522. * there is no way to decrease the delay value further.
  523. */
  524. if (initialDelayNanoSec >= delayTimeInNanoSec)
  525. {
  526. DSPI_MasterSetDelayScaler(base, whichCtar, 0, 0, whichDelay);
  527. return initialDelayNanoSec;
  528. }
  529. /* In all for loops, if min_diff = 0, the exit for loop */
  530. for (prescaler = 0; prescaler < 4U; prescaler++)
  531. {
  532. for (scaler = 0; scaler < 16U; scaler++)
  533. {
  534. realDelay = ((4000000000U / srcClock_Hz) * s_delayPrescaler[prescaler] * s_delayScaler[scaler]) / 4U;
  535. /* calculate the delay difference based on the conditional statement
  536. * that states that the calculated delay must not be less then the desired delay
  537. */
  538. if (realDelay >= delayTimeInNanoSec)
  539. {
  540. diff = realDelay - delayTimeInNanoSec;
  541. if (min_diff > diff)
  542. {
  543. /* a better match found */
  544. min_diff = diff;
  545. bestPrescaler = prescaler;
  546. bestScaler = scaler;
  547. bestDelay = realDelay;
  548. }
  549. }
  550. if (0U == min_diff)
  551. {
  552. break;
  553. }
  554. }
  555. if (0U == min_diff)
  556. {
  557. break;
  558. }
  559. }
  560. /* write the best dbr, prescalar, and baud rate scalar to the CTAR */
  561. DSPI_MasterSetDelayScaler(base, whichCtar, bestPrescaler, bestScaler, whichDelay);
  562. /* return the actual calculated baud rate */
  563. return bestDelay;
  564. }
  565. /*!
  566. * brief Sets the dspi_command_data_config_t structure to default values.
  567. *
  568. * The purpose of this API is to get the configuration structure initialized for use in the DSPI_MasterWrite_xx().
  569. * Users may use the initialized structure unchanged in the DSPI_MasterWrite_xx() or modify the structure
  570. * before calling the DSPI_MasterWrite_xx().
  571. * This is an example.
  572. * code
  573. * dspi_command_data_config_t command;
  574. * DSPI_GetDefaultDataCommandConfig(&command);
  575. * endcode
  576. * param command Pointer to the dspi_command_data_config_t structure.
  577. */
  578. void DSPI_GetDefaultDataCommandConfig(dspi_command_data_config_t *command)
  579. {
  580. assert(NULL != command);
  581. /* Initializes the configure structure to zero. */
  582. (void)memset(command, 0, sizeof(*command));
  583. command->isPcsContinuous = false;
  584. command->whichCtar = (uint8_t)kDSPI_Ctar0;
  585. command->whichPcs = (uint8_t)kDSPI_Pcs0;
  586. command->isEndOfQueue = false;
  587. command->clearTransferCount = false;
  588. }
  589. /*!
  590. * brief Writes data into the data buffer master mode and waits till complete to return.
  591. *
  592. * In master mode, the 16-bit data is appended to the 16-bit command info. The command portion
  593. * provides characteristics of the data, such as the optional continuous chip select
  594. * operation between transfers, the desired Clock and Transfer Attributes register to use for the
  595. * associated SPI frame, the desired PCS signal to use for the data transfer, whether the current
  596. * transfer is the last in the queue, and whether to clear the transfer count (normally needed when
  597. * sending the first frame of a data packet). This is an example.
  598. * code
  599. * dspi_command_config_t commandConfig;
  600. * commandConfig.isPcsContinuous = true;
  601. * commandConfig.whichCtar = kDSPICtar0;
  602. * commandConfig.whichPcs = kDSPIPcs1;
  603. * commandConfig.clearTransferCount = false;
  604. * commandConfig.isEndOfQueue = false;
  605. * DSPI_MasterWriteDataBlocking(base, &commandConfig, dataWord);
  606. * endcode
  607. *
  608. * Note that this function does not return until after the transmit is complete. Also note that the DSPI must be
  609. * enabled and running to transmit data (MCR[MDIS] & [HALT] = 0). Because the SPI is a synchronous protocol,
  610. * the received data is available when the transmit completes.
  611. *
  612. * param base DSPI peripheral address.
  613. * param command Pointer to the command structure.
  614. * param data The data word to be sent.
  615. */
  616. void DSPI_MasterWriteDataBlocking(SPI_Type *base, dspi_command_data_config_t *command, uint16_t data)
  617. {
  618. assert(NULL != command);
  619. /* First, clear Transmit Complete Flag (TCF) */
  620. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxCompleteFlag);
  621. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  622. {
  623. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  624. }
  625. base->PUSHR = SPI_PUSHR_CONT(command->isPcsContinuous) | SPI_PUSHR_CTAS(command->whichCtar) |
  626. SPI_PUSHR_PCS(command->whichPcs) | SPI_PUSHR_EOQ(command->isEndOfQueue) |
  627. SPI_PUSHR_CTCNT(command->clearTransferCount) | SPI_PUSHR_TXDATA(data);
  628. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  629. /* Wait till TCF sets */
  630. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxCompleteFlag))
  631. {
  632. }
  633. }
  634. /*!
  635. * brief Writes a 32-bit data word (16-bit command appended with 16-bit data) into the data
  636. * buffer master mode and waits till complete to return.
  637. *
  638. * In this function, the user must append the 16-bit data to the 16-bit command information and then provide the total
  639. * 32-bit word
  640. * as the data to send.
  641. * The command portion provides characteristics of the data, such as the optional continuous chip select operation
  642. * between transfers, the desired Clock and Transfer Attributes register to use for the associated SPI frame, the
  643. * desired PCS
  644. * signal to use for the data transfer, whether the current transfer is the last in the queue, and whether to clear the
  645. * transfer count (normally needed when sending the first frame of a data packet). The user is responsible for
  646. * appending this command with the data to send. This is an example:
  647. * code
  648. * dataWord = <16-bit command> | <16-bit data>;
  649. * DSPI_MasterWriteCommandDataBlocking(base, dataWord);
  650. * endcode
  651. *
  652. * Note that this function does not return until after the transmit is complete. Also note that the DSPI must be
  653. * enabled and running to transmit data (MCR[MDIS] & [HALT] = 0).
  654. * Because the SPI is a synchronous protocol, the received data is available when the transmit completes.
  655. *
  656. * For a blocking polling transfer, see methods below.
  657. * Option 1:
  658. * uint32_t command_to_send = DSPI_MasterGetFormattedCommand(&command);
  659. * uint32_t data0 = command_to_send | data_need_to_send_0;
  660. * uint32_t data1 = command_to_send | data_need_to_send_1;
  661. * uint32_t data2 = command_to_send | data_need_to_send_2;
  662. *
  663. * DSPI_MasterWriteCommandDataBlocking(base,data0);
  664. * DSPI_MasterWriteCommandDataBlocking(base,data1);
  665. * DSPI_MasterWriteCommandDataBlocking(base,data2);
  666. *
  667. * Option 2:
  668. * DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_0);
  669. * DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_1);
  670. * DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_2);
  671. *
  672. * param base DSPI peripheral address.
  673. * param data The data word (command and data combined) to be sent.
  674. */
  675. void DSPI_MasterWriteCommandDataBlocking(SPI_Type *base, uint32_t data)
  676. {
  677. /* First, clear Transmit Complete Flag (TCF) */
  678. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxCompleteFlag);
  679. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  680. {
  681. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  682. }
  683. base->PUSHR = data;
  684. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  685. /* Wait till TCF sets */
  686. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxCompleteFlag))
  687. {
  688. }
  689. }
  690. /*!
  691. * brief Writes data into the data buffer in slave mode, waits till data was transmitted, and returns.
  692. *
  693. * In slave mode, up to 16-bit words may be written. The function first clears the transmit complete flag, writes data
  694. * into data register, and finally waits until the data is transmitted.
  695. *
  696. * param base DSPI peripheral address.
  697. * param data The data to send.
  698. */
  699. void DSPI_SlaveWriteDataBlocking(SPI_Type *base, uint32_t data)
  700. {
  701. /* First, clear Transmit Complete Flag (TCF) */
  702. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxCompleteFlag);
  703. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  704. {
  705. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  706. }
  707. base->PUSHR_SLAVE = data;
  708. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  709. /* Wait till TCF sets */
  710. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxCompleteFlag))
  711. {
  712. }
  713. }
  714. /*!
  715. * brief Enables the DSPI interrupts.
  716. *
  717. * This function configures the various interrupt masks of the DSPI. The parameters are a base and an interrupt mask.
  718. * Note, for Tx Fill and Rx FIFO drain requests, enable the interrupt request and disable the DMA request.
  719. * Do not use this API(write to RSER register) while DSPI is in running state.
  720. *
  721. * code
  722. * DSPI_EnableInterrupts(base, kDSPI_TxCompleteInterruptEnable | kDSPI_EndOfQueueInterruptEnable );
  723. * endcode
  724. *
  725. * param base DSPI peripheral address.
  726. * param mask The interrupt mask; use the enum _dspi_interrupt_enable.
  727. */
  728. void DSPI_EnableInterrupts(SPI_Type *base, uint32_t mask)
  729. {
  730. if (0U != (mask & SPI_RSER_TFFF_RE_MASK))
  731. {
  732. base->RSER &= ~SPI_RSER_TFFF_DIRS_MASK;
  733. }
  734. if (0U != (mask & SPI_RSER_RFDF_RE_MASK))
  735. {
  736. base->RSER &= ~SPI_RSER_RFDF_DIRS_MASK;
  737. }
  738. base->RSER |= mask;
  739. }
  740. /*Transactional APIs -- Master*/
  741. /*!
  742. * brief Initializes the DSPI master handle.
  743. *
  744. * This function initializes the DSPI handle, which can be used for other DSPI transactional APIs. Usually, for a
  745. * specified DSPI instance, call this API once to get the initialized handle.
  746. *
  747. * param base DSPI peripheral base address.
  748. * param handle DSPI handle pointer to dspi_master_handle_t.
  749. * param callback DSPI callback.
  750. * param userData Callback function parameter.
  751. */
  752. void DSPI_MasterTransferCreateHandle(SPI_Type *base,
  753. dspi_master_handle_t *handle,
  754. dspi_master_transfer_callback_t callback,
  755. void *userData)
  756. {
  757. assert(NULL != handle);
  758. /* Zero the handle. */
  759. (void)memset(handle, 0, sizeof(*handle));
  760. g_dspiHandle[DSPI_GetInstance(base)] = handle;
  761. handle->callback = callback;
  762. handle->userData = userData;
  763. }
  764. /*!
  765. * brief DSPI master transfer data using polling.
  766. *
  767. * This function transfers data using polling. This is a blocking function, which does not return until all transfers
  768. * have been completed.
  769. *
  770. * param base DSPI peripheral base address.
  771. * param transfer Pointer to the dspi_transfer_t structure.
  772. * return status of status_t.
  773. */
  774. status_t DSPI_MasterTransferBlocking(SPI_Type *base, dspi_transfer_t *transfer)
  775. {
  776. assert(NULL != transfer);
  777. uint16_t wordToSend = 0;
  778. uint16_t wordReceived = 0;
  779. uint8_t dummyData = DSPI_GetDummyDataInstance(base);
  780. uint8_t bitsPerFrame;
  781. uint32_t command;
  782. uint32_t lastCommand;
  783. uint8_t *txData;
  784. uint8_t *rxData;
  785. uint32_t remainingSendByteCount;
  786. uint32_t remainingReceiveByteCount;
  787. uint32_t fifoSize;
  788. uint32_t tmpMCR = 0;
  789. dspi_command_data_config_t commandStruct;
  790. /* If the transfer count is zero, then return immediately.*/
  791. if (transfer->dataSize == 0U)
  792. {
  793. return kStatus_InvalidArgument;
  794. }
  795. DSPI_StopTransfer(base);
  796. DSPI_DisableInterrupts(base, (uint32_t)kDSPI_AllInterruptEnable);
  797. DSPI_FlushFifo(base, true, true);
  798. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_AllStatusFlag);
  799. /*Calculate the command and lastCommand*/
  800. commandStruct.whichPcs =
  801. (uint8_t)((uint32_t)1U << ((transfer->configFlags & DSPI_MASTER_PCS_MASK) >> DSPI_MASTER_PCS_SHIFT));
  802. commandStruct.isEndOfQueue = false;
  803. commandStruct.clearTransferCount = false;
  804. commandStruct.whichCtar = (uint8_t)((transfer->configFlags & DSPI_MASTER_CTAR_MASK) >> DSPI_MASTER_CTAR_SHIFT);
  805. commandStruct.isPcsContinuous =
  806. (0U != (transfer->configFlags & (uint32_t)kDSPI_MasterPcsContinuous)) ? true : false;
  807. command = DSPI_MasterGetFormattedCommand(&(commandStruct));
  808. commandStruct.isEndOfQueue = true;
  809. commandStruct.isPcsContinuous =
  810. (0U != (transfer->configFlags & (uint32_t)kDSPI_MasterActiveAfterTransfer)) ? true : false;
  811. lastCommand = DSPI_MasterGetFormattedCommand(&(commandStruct));
  812. /*Calculate the bitsPerFrame*/
  813. bitsPerFrame = (uint8_t)(((base->CTAR[commandStruct.whichCtar] & SPI_CTAR_FMSZ_MASK) >> SPI_CTAR_FMSZ_SHIFT) + 1U);
  814. txData = transfer->txData;
  815. rxData = transfer->rxData;
  816. remainingSendByteCount = transfer->dataSize;
  817. remainingReceiveByteCount = transfer->dataSize;
  818. tmpMCR = base->MCR;
  819. if ((0U != (tmpMCR & SPI_MCR_DIS_RXF_MASK)) || (0U != (tmpMCR & SPI_MCR_DIS_TXF_MASK)))
  820. {
  821. fifoSize = 1U;
  822. }
  823. else
  824. {
  825. fifoSize = (uint32_t)FSL_FEATURE_DSPI_FIFO_SIZEn(base);
  826. }
  827. DSPI_StartTransfer(base);
  828. if (bitsPerFrame <= 8U)
  829. {
  830. while (remainingSendByteCount > 0U)
  831. {
  832. if (remainingSendByteCount == 1U)
  833. {
  834. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  835. {
  836. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  837. }
  838. if (txData != NULL)
  839. {
  840. base->PUSHR = (*txData) | (lastCommand);
  841. txData++;
  842. }
  843. else
  844. {
  845. base->PUSHR = (lastCommand) | (dummyData);
  846. }
  847. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  848. remainingSendByteCount--;
  849. while (remainingReceiveByteCount > 0U)
  850. {
  851. if ((uint32_t)kDSPI_RxFifoDrainRequestFlag ==
  852. (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoDrainRequestFlag))
  853. {
  854. if (rxData != NULL)
  855. {
  856. /* Read data from POPR*/
  857. *(rxData) = (uint8_t)DSPI_ReadData(base);
  858. rxData++;
  859. }
  860. else
  861. {
  862. (void)DSPI_ReadData(base);
  863. }
  864. remainingReceiveByteCount--;
  865. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoDrainRequestFlag);
  866. }
  867. }
  868. }
  869. else
  870. {
  871. /*Wait until Tx Fifo is not full*/
  872. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  873. {
  874. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  875. }
  876. if (txData != NULL)
  877. {
  878. base->PUSHR = command | (uint16_t)(*txData);
  879. txData++;
  880. }
  881. else
  882. {
  883. base->PUSHR = command | dummyData;
  884. }
  885. remainingSendByteCount--;
  886. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  887. while ((remainingReceiveByteCount - remainingSendByteCount) >= fifoSize)
  888. {
  889. if ((uint32_t)kDSPI_RxFifoDrainRequestFlag ==
  890. (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoDrainRequestFlag))
  891. {
  892. if (rxData != NULL)
  893. {
  894. *(rxData) = (uint8_t)DSPI_ReadData(base);
  895. rxData++;
  896. }
  897. else
  898. {
  899. (void)DSPI_ReadData(base);
  900. }
  901. remainingReceiveByteCount--;
  902. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoDrainRequestFlag);
  903. }
  904. }
  905. }
  906. }
  907. }
  908. else
  909. {
  910. while (remainingSendByteCount > 0U)
  911. {
  912. if (remainingSendByteCount <= 2U)
  913. {
  914. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  915. {
  916. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  917. }
  918. if (txData != NULL)
  919. {
  920. wordToSend = *(txData);
  921. ++txData;
  922. if (remainingSendByteCount > 1U)
  923. {
  924. wordToSend |= (uint16_t)(*(txData)) << 8U;
  925. ++txData;
  926. }
  927. }
  928. else
  929. {
  930. wordToSend = dummyData;
  931. }
  932. base->PUSHR = lastCommand | wordToSend;
  933. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  934. remainingSendByteCount = 0;
  935. while (remainingReceiveByteCount > 0U)
  936. {
  937. if ((uint32_t)kDSPI_RxFifoDrainRequestFlag ==
  938. (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoDrainRequestFlag))
  939. {
  940. wordReceived = (uint16_t)DSPI_ReadData(base);
  941. if (remainingReceiveByteCount != 1U)
  942. {
  943. if (rxData != NULL)
  944. {
  945. *(rxData) = (uint8_t)wordReceived;
  946. ++rxData;
  947. *(rxData) = (uint8_t)(wordReceived >> 8U);
  948. ++rxData;
  949. }
  950. remainingReceiveByteCount -= 2U;
  951. }
  952. else
  953. {
  954. if (rxData != NULL)
  955. {
  956. *(rxData) = (uint8_t)wordReceived;
  957. ++rxData;
  958. }
  959. remainingReceiveByteCount--;
  960. }
  961. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoDrainRequestFlag);
  962. }
  963. }
  964. }
  965. else
  966. {
  967. /*Wait until Tx Fifo is not full*/
  968. while (0U == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  969. {
  970. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  971. }
  972. if (txData != NULL)
  973. {
  974. wordToSend = *(txData);
  975. ++txData;
  976. wordToSend |= (uint16_t)(*(txData)) << 8U;
  977. ++txData;
  978. }
  979. else
  980. {
  981. wordToSend = dummyData;
  982. }
  983. base->PUSHR = command | wordToSend;
  984. remainingSendByteCount -= 2U;
  985. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  986. while (((remainingReceiveByteCount - remainingSendByteCount) / 2U) >= fifoSize)
  987. {
  988. if ((uint32_t)kDSPI_RxFifoDrainRequestFlag ==
  989. (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoDrainRequestFlag))
  990. {
  991. wordReceived = (uint16_t)DSPI_ReadData(base);
  992. if (rxData != NULL)
  993. {
  994. *rxData = (uint8_t)wordReceived;
  995. ++rxData;
  996. *rxData = (uint8_t)(wordReceived >> 8U);
  997. ++rxData;
  998. }
  999. remainingReceiveByteCount -= 2U;
  1000. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoDrainRequestFlag);
  1001. }
  1002. }
  1003. }
  1004. }
  1005. }
  1006. return kStatus_Success;
  1007. }
  1008. static void DSPI_MasterTransferPrepare(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer)
  1009. {
  1010. assert(NULL != handle);
  1011. assert(NULL != transfer);
  1012. uint32_t tmpMCR = 0;
  1013. dspi_command_data_config_t commandStruct = {false, (uint8_t)kDSPI_Ctar0, (uint8_t)kDSPI_Pcs0, false, false};
  1014. DSPI_StopTransfer(base);
  1015. DSPI_FlushFifo(base, true, true);
  1016. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_AllStatusFlag);
  1017. commandStruct.whichPcs =
  1018. (uint8_t)((uint32_t)1U << ((transfer->configFlags & DSPI_MASTER_PCS_MASK) >> DSPI_MASTER_PCS_SHIFT));
  1019. commandStruct.isEndOfQueue = false;
  1020. commandStruct.clearTransferCount = false;
  1021. commandStruct.whichCtar = (uint8_t)((transfer->configFlags & DSPI_MASTER_CTAR_MASK) >> DSPI_MASTER_CTAR_SHIFT);
  1022. commandStruct.isPcsContinuous =
  1023. (0U != (transfer->configFlags & (uint32_t)kDSPI_MasterPcsContinuous)) ? true : false;
  1024. handle->command = DSPI_MasterGetFormattedCommand(&(commandStruct));
  1025. commandStruct.isEndOfQueue = true;
  1026. commandStruct.isPcsContinuous =
  1027. (0U != (transfer->configFlags & (uint32_t)kDSPI_MasterActiveAfterTransfer)) ? true : false;
  1028. handle->lastCommand = DSPI_MasterGetFormattedCommand(&(commandStruct));
  1029. handle->bitsPerFrame = ((base->CTAR[commandStruct.whichCtar] & SPI_CTAR_FMSZ_MASK) >> SPI_CTAR_FMSZ_SHIFT) + 1U;
  1030. tmpMCR = base->MCR;
  1031. if ((0U != (tmpMCR & SPI_MCR_DIS_RXF_MASK)) || (0U != (tmpMCR & SPI_MCR_DIS_TXF_MASK)))
  1032. {
  1033. handle->fifoSize = 1U;
  1034. }
  1035. else
  1036. {
  1037. handle->fifoSize = (uint8_t)FSL_FEATURE_DSPI_FIFO_SIZEn(base);
  1038. }
  1039. handle->txData = transfer->txData;
  1040. handle->rxData = transfer->rxData;
  1041. handle->remainingSendByteCount = transfer->dataSize;
  1042. handle->remainingReceiveByteCount = transfer->dataSize;
  1043. handle->totalByteCount = transfer->dataSize;
  1044. }
  1045. /*!
  1046. * brief DSPI master transfer data using interrupts.
  1047. *
  1048. * This function transfers data using interrupts. This is a non-blocking function, which returns right away. When all
  1049. * data is transferred, the callback function is called.
  1050. * param base DSPI peripheral base address.
  1051. * param handle Pointer to the dspi_master_handle_t structure which stores the transfer state.
  1052. * param transfer Pointer to the dspi_transfer_t structure.
  1053. * return status of status_t.
  1054. */
  1055. status_t DSPI_MasterTransferNonBlocking(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer)
  1056. {
  1057. assert(NULL != handle);
  1058. assert(NULL != transfer);
  1059. /* If the transfer count is zero, then return immediately.*/
  1060. if (transfer->dataSize == 0U)
  1061. {
  1062. return kStatus_InvalidArgument;
  1063. }
  1064. /* Check that we're not busy.*/
  1065. if (handle->state == (uint8_t)kDSPI_Busy)
  1066. {
  1067. return kStatus_DSPI_Busy;
  1068. }
  1069. handle->state = (uint8_t)kDSPI_Busy;
  1070. /* Disable the NVIC for DSPI peripheral. */
  1071. (void)DisableIRQ(s_dspiIRQ[DSPI_GetInstance(base)]);
  1072. DSPI_MasterTransferPrepare(base, handle, transfer);
  1073. /* RX FIFO Drain request: RFDF_RE to enable RFDF interrupt
  1074. * Since SPI is a synchronous interface, we only need to enable the RX interrupt.
  1075. * The IRQ handler will get the status of RX and TX interrupt flags.
  1076. */
  1077. s_dspiMasterIsr = DSPI_MasterTransferHandleIRQ;
  1078. DSPI_EnableInterrupts(base, (uint32_t)kDSPI_RxFifoDrainRequestInterruptEnable);
  1079. DSPI_StartTransfer(base);
  1080. /* Fill up the Tx FIFO to trigger the transfer. */
  1081. DSPI_MasterTransferFillUpTxFifo(base, handle);
  1082. /* Enable the NVIC for DSPI peripheral. */
  1083. (void)EnableIRQ(s_dspiIRQ[DSPI_GetInstance(base)]);
  1084. return kStatus_Success;
  1085. }
  1086. /*!
  1087. * brief Transfers a block of data using a polling method.
  1088. *
  1089. * This function will do a half-duplex transfer for DSPI master, This is a blocking function,
  1090. * which does not retuen until all transfer have been completed. And data transfer will be half-duplex,
  1091. * users can set transmit first or receive first.
  1092. *
  1093. * param base DSPI base pointer
  1094. * param xfer pointer to dspi_half_duplex_transfer_t structure
  1095. * return status of status_t.
  1096. */
  1097. status_t DSPI_MasterHalfDuplexTransferBlocking(SPI_Type *base, dspi_half_duplex_transfer_t *xfer)
  1098. {
  1099. assert(NULL != xfer);
  1100. dspi_transfer_t tempXfer = {0};
  1101. status_t status;
  1102. if (true == xfer->isTransmitFirst)
  1103. {
  1104. tempXfer.txData = xfer->txData;
  1105. tempXfer.rxData = NULL;
  1106. tempXfer.dataSize = xfer->txDataSize;
  1107. }
  1108. else
  1109. {
  1110. tempXfer.txData = NULL;
  1111. tempXfer.rxData = xfer->rxData;
  1112. tempXfer.dataSize = xfer->rxDataSize;
  1113. }
  1114. /* If the pcs pin keep assert between transmit and receive. */
  1115. if (true == xfer->isPcsAssertInTransfer)
  1116. {
  1117. tempXfer.configFlags = (xfer->configFlags) | (uint32_t)kDSPI_MasterActiveAfterTransfer;
  1118. }
  1119. else
  1120. {
  1121. tempXfer.configFlags = (xfer->configFlags) & (~(uint32_t)kDSPI_MasterActiveAfterTransfer);
  1122. }
  1123. status = DSPI_MasterTransferBlocking(base, &tempXfer);
  1124. if (status != kStatus_Success)
  1125. {
  1126. return status;
  1127. }
  1128. if (true == xfer->isTransmitFirst)
  1129. {
  1130. tempXfer.txData = NULL;
  1131. tempXfer.rxData = xfer->rxData;
  1132. tempXfer.dataSize = xfer->rxDataSize;
  1133. }
  1134. else
  1135. {
  1136. tempXfer.txData = xfer->txData;
  1137. tempXfer.rxData = NULL;
  1138. tempXfer.dataSize = xfer->txDataSize;
  1139. }
  1140. tempXfer.configFlags = xfer->configFlags;
  1141. /* DSPI transfer blocking. */
  1142. status = DSPI_MasterTransferBlocking(base, &tempXfer);
  1143. return status;
  1144. }
  1145. /*!
  1146. * brief Performs a non-blocking DSPI interrupt transfer.
  1147. *
  1148. * This function transfers data using interrupts, the transfer mechanism is half-duplex. This is a non-blocking
  1149. * function,
  1150. * which returns right away. When all data is transferred, the callback function is called.
  1151. *
  1152. * param base DSPI peripheral base address.
  1153. * param handle pointer to dspi_master_handle_t structure which stores the transfer state
  1154. * param xfer pointer to dspi_half_duplex_transfer_t structure
  1155. * return status of status_t.
  1156. */
  1157. status_t DSPI_MasterHalfDuplexTransferNonBlocking(SPI_Type *base,
  1158. dspi_master_handle_t *handle,
  1159. dspi_half_duplex_transfer_t *xfer)
  1160. {
  1161. assert(NULL != xfer);
  1162. assert(NULL != handle);
  1163. dspi_transfer_t tempXfer = {0};
  1164. status_t status;
  1165. if (true == xfer->isTransmitFirst)
  1166. {
  1167. tempXfer.txData = xfer->txData;
  1168. tempXfer.rxData = NULL;
  1169. tempXfer.dataSize = xfer->txDataSize;
  1170. }
  1171. else
  1172. {
  1173. tempXfer.txData = NULL;
  1174. tempXfer.rxData = xfer->rxData;
  1175. tempXfer.dataSize = xfer->rxDataSize;
  1176. }
  1177. /* If the pcs pin keep assert between transmit and receive. */
  1178. if (true == xfer->isPcsAssertInTransfer)
  1179. {
  1180. tempXfer.configFlags = (xfer->configFlags) | (uint32_t)kDSPI_MasterActiveAfterTransfer;
  1181. }
  1182. else
  1183. {
  1184. tempXfer.configFlags = (xfer->configFlags) & (~(uint32_t)kDSPI_MasterActiveAfterTransfer);
  1185. }
  1186. status = DSPI_MasterTransferBlocking(base, &tempXfer);
  1187. if (status != kStatus_Success)
  1188. {
  1189. return status;
  1190. }
  1191. if (true == xfer->isTransmitFirst)
  1192. {
  1193. tempXfer.txData = NULL;
  1194. tempXfer.rxData = xfer->rxData;
  1195. tempXfer.dataSize = xfer->rxDataSize;
  1196. }
  1197. else
  1198. {
  1199. tempXfer.txData = xfer->txData;
  1200. tempXfer.rxData = NULL;
  1201. tempXfer.dataSize = xfer->txDataSize;
  1202. }
  1203. tempXfer.configFlags = xfer->configFlags;
  1204. status = DSPI_MasterTransferNonBlocking(base, handle, &tempXfer);
  1205. return status;
  1206. }
  1207. /*!
  1208. * brief Gets the master transfer count.
  1209. *
  1210. * This function gets the master transfer count.
  1211. *
  1212. * param base DSPI peripheral base address.
  1213. * param handle Pointer to the dspi_master_handle_t structure which stores the transfer state.
  1214. * param count The number of bytes transferred by using the non-blocking transaction.
  1215. * return status of status_t.
  1216. */
  1217. status_t DSPI_MasterTransferGetCount(SPI_Type *base, dspi_master_handle_t *handle, size_t *count)
  1218. {
  1219. assert(NULL != handle);
  1220. if (NULL == count)
  1221. {
  1222. return kStatus_InvalidArgument;
  1223. }
  1224. /* Catch when there is not an active transfer. */
  1225. if (handle->state != (uint8_t)kDSPI_Busy)
  1226. {
  1227. *count = 0;
  1228. return kStatus_NoTransferInProgress;
  1229. }
  1230. *count = handle->totalByteCount - handle->remainingReceiveByteCount;
  1231. return kStatus_Success;
  1232. }
  1233. static void DSPI_MasterTransferComplete(SPI_Type *base, dspi_master_handle_t *handle)
  1234. {
  1235. assert(NULL != handle);
  1236. /* Disable interrupt requests*/
  1237. DSPI_DisableInterrupts(
  1238. base, ((uint32_t)kDSPI_RxFifoDrainRequestInterruptEnable | (uint32_t)kDSPI_TxFifoFillRequestInterruptEnable));
  1239. status_t status = 0;
  1240. if (handle->state == (uint8_t)kDSPI_Error)
  1241. {
  1242. status = kStatus_DSPI_Error;
  1243. }
  1244. else
  1245. {
  1246. status = kStatus_Success;
  1247. }
  1248. if ((NULL != handle->callback) && ((uint8_t)kDSPI_Idle != handle->state))
  1249. {
  1250. handle->state = (uint8_t)kDSPI_Idle;
  1251. handle->callback(base, handle, status, handle->userData);
  1252. }
  1253. }
  1254. static void DSPI_MasterTransferFillUpTxFifo(SPI_Type *base, dspi_master_handle_t *handle)
  1255. {
  1256. assert(NULL != handle);
  1257. uint16_t wordToSend = 0;
  1258. uint8_t dummyData = DSPI_GetDummyDataInstance(base);
  1259. size_t tmpRemainingSendByteCount = handle->remainingSendByteCount;
  1260. size_t tmpRemainingReceiveByteCount = handle->remainingReceiveByteCount;
  1261. uint8_t tmpFifoSize = handle->fifoSize;
  1262. /* If bits/frame is greater than one byte */
  1263. if (handle->bitsPerFrame > 8U)
  1264. {
  1265. /* Fill the fifo until it is full or until the send word count is 0 or until the difference
  1266. * between the remainingReceiveByteCount and remainingSendByteCount equals the FIFO depth.
  1267. * The reason for checking the difference is to ensure we only send as much as the
  1268. * RX FIFO can receive.
  1269. * For this case where bitsPerFrame > 8, each entry in the FIFO contains 2 bytes of the
  1270. * send data, hence the difference between the remainingReceiveByteCount and
  1271. * remainingSendByteCount must be divided by 2 to convert this difference into a
  1272. * 16-bit (2 byte) value.
  1273. */
  1274. while ((0U != (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag)) &&
  1275. (((tmpRemainingReceiveByteCount - tmpRemainingSendByteCount) / 2U) < tmpFifoSize))
  1276. {
  1277. if (handle->remainingSendByteCount <= 2U)
  1278. {
  1279. if (NULL != handle->txData)
  1280. {
  1281. if (handle->remainingSendByteCount == 1U)
  1282. {
  1283. wordToSend = *(handle->txData);
  1284. }
  1285. else
  1286. {
  1287. wordToSend = *(handle->txData);
  1288. ++handle->txData; /* increment to next data byte */
  1289. wordToSend |= (uint16_t)(*(handle->txData)) << 8U;
  1290. }
  1291. }
  1292. else
  1293. {
  1294. wordToSend = dummyData;
  1295. }
  1296. handle->remainingSendByteCount = 0;
  1297. base->PUSHR = handle->lastCommand | wordToSend;
  1298. }
  1299. /* For all words except the last word */
  1300. else
  1301. {
  1302. if (NULL != handle->txData)
  1303. {
  1304. wordToSend = *(handle->txData);
  1305. ++handle->txData; /* increment to next data byte */
  1306. wordToSend |= (uint16_t)(*(handle->txData)) << 8U;
  1307. ++handle->txData; /* increment to next data byte */
  1308. }
  1309. else
  1310. {
  1311. wordToSend = dummyData;
  1312. }
  1313. handle->remainingSendByteCount -= 2U; /* decrement remainingSendByteCount by 2 */
  1314. base->PUSHR = handle->command | wordToSend;
  1315. }
  1316. /* Try to clear the TFFF; if the TX FIFO is full this will clear */
  1317. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  1318. /* exit loop if send count is zero, else update local variables for next loop.
  1319. * If this is the first time write to the PUSHR, write only once.
  1320. */
  1321. tmpRemainingSendByteCount = handle->remainingSendByteCount;
  1322. if ((tmpRemainingSendByteCount == 0U) || (tmpRemainingSendByteCount == handle->totalByteCount - 2U))
  1323. {
  1324. break;
  1325. }
  1326. tmpRemainingReceiveByteCount = handle->remainingReceiveByteCount;
  1327. tmpRemainingSendByteCount = handle->remainingSendByteCount;
  1328. tmpFifoSize = handle->fifoSize;
  1329. } /* End of TX FIFO fill while loop */
  1330. }
  1331. /* Optimized for bits/frame less than or equal to one byte. */
  1332. else
  1333. {
  1334. /* Fill the fifo until it is full or until the send word count is 0 or until the difference
  1335. * between the remainingReceiveByteCount and remainingSendByteCount equals the FIFO depth.
  1336. * The reason for checking the difference is to ensure we only send as much as the
  1337. * RX FIFO can receive.
  1338. */
  1339. while ((0U != (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag)) &&
  1340. ((tmpRemainingReceiveByteCount - tmpRemainingSendByteCount) < tmpFifoSize))
  1341. {
  1342. if (NULL != handle->txData)
  1343. {
  1344. wordToSend = *(handle->txData);
  1345. ++handle->txData;
  1346. }
  1347. else
  1348. {
  1349. wordToSend = dummyData;
  1350. }
  1351. if (handle->remainingSendByteCount == 1U)
  1352. {
  1353. base->PUSHR = handle->lastCommand | wordToSend;
  1354. }
  1355. else
  1356. {
  1357. base->PUSHR = handle->command | wordToSend;
  1358. }
  1359. /* Try to clear the TFFF; if the TX FIFO is full this will clear */
  1360. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  1361. --handle->remainingSendByteCount;
  1362. /* exit loop if send count is zero, else update local variables for next loop
  1363. * If this is the first time write to the PUSHR, write only once.
  1364. */
  1365. tmpRemainingSendByteCount = handle->remainingSendByteCount;
  1366. if ((tmpRemainingSendByteCount == 0U) || (tmpRemainingSendByteCount == (handle->totalByteCount - 1U)))
  1367. {
  1368. break;
  1369. }
  1370. tmpRemainingReceiveByteCount = handle->remainingReceiveByteCount;
  1371. tmpRemainingSendByteCount = handle->remainingSendByteCount;
  1372. tmpFifoSize = handle->fifoSize;
  1373. }
  1374. }
  1375. }
  1376. /*!
  1377. * brief DSPI master aborts a transfer using an interrupt.
  1378. *
  1379. * This function aborts a transfer using an interrupt.
  1380. *
  1381. * param base DSPI peripheral base address.
  1382. * param handle Pointer to the dspi_master_handle_t structure which stores the transfer state.
  1383. */
  1384. void DSPI_MasterTransferAbort(SPI_Type *base, dspi_master_handle_t *handle)
  1385. {
  1386. assert(NULL != handle);
  1387. DSPI_StopTransfer(base);
  1388. /* Disable interrupt requests*/
  1389. DSPI_DisableInterrupts(
  1390. base, ((uint32_t)kDSPI_RxFifoDrainRequestInterruptEnable | (uint32_t)kDSPI_TxFifoFillRequestInterruptEnable));
  1391. handle->state = (uint8_t)kDSPI_Idle;
  1392. }
  1393. /*!
  1394. * brief DSPI Master IRQ handler function.
  1395. *
  1396. * This function processes the DSPI transmit and receive IRQ.
  1397. * param base DSPI peripheral base address.
  1398. * param handle Pointer to the dspi_master_handle_t structure which stores the transfer state.
  1399. */
  1400. void DSPI_MasterTransferHandleIRQ(SPI_Type *base, dspi_master_handle_t *handle)
  1401. {
  1402. assert(NULL != handle);
  1403. /* RECEIVE IRQ handler: Check read buffer only if there are remaining bytes to read. */
  1404. if (0U != (handle->remainingReceiveByteCount))
  1405. {
  1406. /* Check read buffer.*/
  1407. uint16_t wordReceived; /* Maximum supported data bit length in master mode is 16-bits */
  1408. /* If bits/frame is greater than one byte */
  1409. if (handle->bitsPerFrame > 8U)
  1410. {
  1411. while ((uint32_t)kDSPI_RxFifoDrainRequestFlag ==
  1412. (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoDrainRequestFlag))
  1413. {
  1414. wordReceived = (uint16_t)DSPI_ReadData(base);
  1415. /* clear the rx fifo drain request, needed for non-DMA applications as this flag
  1416. * will remain set even if the rx fifo is empty. By manually clearing this flag, it
  1417. * either remain clear if no more data is in the fifo, or it will set if there is
  1418. * more data in the fifo.
  1419. */
  1420. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoDrainRequestFlag);
  1421. /* Store read bytes into rx buffer only if a buffer pointer was provided */
  1422. if (NULL != handle->rxData)
  1423. {
  1424. /* For the last word received, if there is an extra byte due to the odd transfer
  1425. * byte count, only save the last byte and discard the upper byte
  1426. */
  1427. if (handle->remainingReceiveByteCount == 1U)
  1428. {
  1429. *handle->rxData = (uint8_t)wordReceived; /* Write first data byte */
  1430. --handle->remainingReceiveByteCount;
  1431. }
  1432. else
  1433. {
  1434. *handle->rxData = (uint8_t)wordReceived; /* Write first data byte */
  1435. ++handle->rxData; /* increment to next data byte */
  1436. *handle->rxData = (uint8_t)(wordReceived >> 8U); /* Write second data byte */
  1437. ++handle->rxData; /* increment to next data byte */
  1438. handle->remainingReceiveByteCount -= 2U;
  1439. }
  1440. }
  1441. else
  1442. {
  1443. if (handle->remainingReceiveByteCount == 1U)
  1444. {
  1445. --handle->remainingReceiveByteCount;
  1446. }
  1447. else
  1448. {
  1449. handle->remainingReceiveByteCount -= 2U;
  1450. }
  1451. }
  1452. if (handle->remainingReceiveByteCount == 0U)
  1453. {
  1454. break;
  1455. }
  1456. } /* End of RX FIFO drain while loop */
  1457. }
  1458. /* Optimized for bits/frame less than or equal to one byte. */
  1459. else
  1460. {
  1461. while ((uint32_t)kDSPI_RxFifoDrainRequestFlag ==
  1462. (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoDrainRequestFlag))
  1463. {
  1464. wordReceived = (uint16_t)DSPI_ReadData(base);
  1465. /* clear the rx fifo drain request, needed for non-DMA applications as this flag
  1466. * will remain set even if the rx fifo is empty. By manually clearing this flag, it
  1467. * either remain clear if no more data is in the fifo, or it will set if there is
  1468. * more data in the fifo.
  1469. */
  1470. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoDrainRequestFlag);
  1471. /* Store read bytes into rx buffer only if a buffer pointer was provided */
  1472. if (NULL != handle->rxData)
  1473. {
  1474. *handle->rxData = (uint8_t)wordReceived;
  1475. ++handle->rxData;
  1476. }
  1477. --handle->remainingReceiveByteCount;
  1478. if (handle->remainingReceiveByteCount == 0U)
  1479. {
  1480. break;
  1481. }
  1482. } /* End of RX FIFO drain while loop */
  1483. }
  1484. }
  1485. /* Check write buffer. We always have to send a word in order to keep the transfer
  1486. * moving. So if the caller didn't provide a send buffer, we just send a zero.
  1487. */
  1488. if (0U != (handle->remainingSendByteCount))
  1489. {
  1490. DSPI_MasterTransferFillUpTxFifo(base, handle);
  1491. }
  1492. /* Check if we're done with this transfer.*/
  1493. if (handle->remainingSendByteCount == 0U)
  1494. {
  1495. if (handle->remainingReceiveByteCount == 0U)
  1496. {
  1497. /* Complete the transfer and disable the interrupts */
  1498. DSPI_MasterTransferComplete(base, handle);
  1499. }
  1500. }
  1501. }
  1502. /*Transactional APIs -- Slave*/
  1503. /*!
  1504. * brief Initializes the DSPI slave handle.
  1505. *
  1506. * This function initializes the DSPI handle, which can be used for other DSPI transactional APIs. Usually, for a
  1507. * specified DSPI instance, call this API once to get the initialized handle.
  1508. *
  1509. * param handle DSPI handle pointer to the dspi_slave_handle_t.
  1510. * param base DSPI peripheral base address.
  1511. * param callback DSPI callback.
  1512. * param userData Callback function parameter.
  1513. */
  1514. void DSPI_SlaveTransferCreateHandle(SPI_Type *base,
  1515. dspi_slave_handle_t *handle,
  1516. dspi_slave_transfer_callback_t callback,
  1517. void *userData)
  1518. {
  1519. assert(NULL != handle);
  1520. /* Zero the handle. */
  1521. (void)memset(handle, 0, sizeof(*handle));
  1522. g_dspiHandle[DSPI_GetInstance(base)] = handle;
  1523. handle->callback = callback;
  1524. handle->userData = userData;
  1525. }
  1526. /*!
  1527. * brief DSPI slave transfers data using an interrupt.
  1528. *
  1529. * This function transfers data using an interrupt. This is a non-blocking function, which returns right away. When all
  1530. * data is transferred, the callback function is called.
  1531. *
  1532. * param base DSPI peripheral base address.
  1533. * param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state.
  1534. * param transfer Pointer to the dspi_transfer_t structure.
  1535. * return status of status_t.
  1536. */
  1537. status_t DSPI_SlaveTransferNonBlocking(SPI_Type *base, dspi_slave_handle_t *handle, dspi_transfer_t *transfer)
  1538. {
  1539. assert(NULL != handle);
  1540. assert(NULL != transfer);
  1541. /* If receive length is zero */
  1542. if (transfer->dataSize == 0U)
  1543. {
  1544. return kStatus_InvalidArgument;
  1545. }
  1546. /* If both send buffer and receive buffer is null */
  1547. if ((NULL == (transfer->txData)) && (NULL == (transfer->rxData)))
  1548. {
  1549. return kStatus_InvalidArgument;
  1550. }
  1551. /* Check that we're not busy.*/
  1552. if (handle->state == (uint8_t)kDSPI_Busy)
  1553. {
  1554. return kStatus_DSPI_Busy;
  1555. }
  1556. handle->state = (uint8_t)kDSPI_Busy;
  1557. /* Enable the NVIC for DSPI peripheral. */
  1558. (void)EnableIRQ(s_dspiIRQ[DSPI_GetInstance(base)]);
  1559. /* Store transfer information */
  1560. handle->txData = transfer->txData;
  1561. handle->rxData = transfer->rxData;
  1562. handle->remainingSendByteCount = transfer->dataSize;
  1563. handle->remainingReceiveByteCount = transfer->dataSize;
  1564. handle->totalByteCount = transfer->dataSize;
  1565. handle->errorCount = 0;
  1566. uint8_t whichCtar = (uint8_t)((transfer->configFlags & DSPI_SLAVE_CTAR_MASK) >> DSPI_SLAVE_CTAR_SHIFT);
  1567. handle->bitsPerFrame =
  1568. (((base->CTAR_SLAVE[whichCtar]) & SPI_CTAR_SLAVE_FMSZ_MASK) >> SPI_CTAR_SLAVE_FMSZ_SHIFT) + 1U;
  1569. DSPI_StopTransfer(base);
  1570. DSPI_FlushFifo(base, true, true);
  1571. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_AllStatusFlag);
  1572. s_dspiSlaveIsr = DSPI_SlaveTransferHandleIRQ;
  1573. /* Enable RX FIFO drain request, the slave only use this interrupt */
  1574. DSPI_EnableInterrupts(base, (uint32_t)kDSPI_RxFifoDrainRequestInterruptEnable);
  1575. if (NULL != handle->rxData)
  1576. {
  1577. /* RX FIFO overflow request enable */
  1578. DSPI_EnableInterrupts(base, (uint32_t)kDSPI_RxFifoOverflowInterruptEnable);
  1579. }
  1580. if (NULL != handle->txData)
  1581. {
  1582. /* TX FIFO underflow request enable */
  1583. DSPI_EnableInterrupts(base, (uint32_t)kDSPI_TxFifoUnderflowInterruptEnable);
  1584. }
  1585. DSPI_StartTransfer(base);
  1586. /* Prepare data to transmit */
  1587. DSPI_SlaveTransferFillUpTxFifo(base, handle);
  1588. return kStatus_Success;
  1589. }
  1590. /*!
  1591. * brief Gets the slave transfer count.
  1592. *
  1593. * This function gets the slave transfer count.
  1594. *
  1595. * param base DSPI peripheral base address.
  1596. * param handle Pointer to the dspi_master_handle_t structure which stores the transfer state.
  1597. * param count The number of bytes transferred by using the non-blocking transaction.
  1598. * return status of status_t.
  1599. */
  1600. status_t DSPI_SlaveTransferGetCount(SPI_Type *base, dspi_slave_handle_t *handle, size_t *count)
  1601. {
  1602. assert(NULL != handle);
  1603. if (NULL == count)
  1604. {
  1605. return kStatus_InvalidArgument;
  1606. }
  1607. /* Catch when there is not an active transfer. */
  1608. if (handle->state != (uint8_t)kDSPI_Busy)
  1609. {
  1610. *count = 0;
  1611. return kStatus_NoTransferInProgress;
  1612. }
  1613. *count = handle->totalByteCount - handle->remainingReceiveByteCount;
  1614. return kStatus_Success;
  1615. }
  1616. static void DSPI_SlaveTransferFillUpTxFifo(SPI_Type *base, dspi_slave_handle_t *handle)
  1617. {
  1618. assert(NULL != handle);
  1619. uint16_t transmitData = 0;
  1620. uint8_t dummyPattern = DSPI_GetDummyDataInstance(base);
  1621. /* Service the transmitter, if transmit buffer provided, transmit the data,
  1622. * else transmit dummy pattern
  1623. */
  1624. while ((uint32_t)kDSPI_TxFifoFillRequestFlag == (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoFillRequestFlag))
  1625. {
  1626. /* Transmit data */
  1627. if (handle->remainingSendByteCount > 0U)
  1628. {
  1629. /* Have data to transmit, update the transmit data and push to FIFO */
  1630. if (handle->bitsPerFrame <= 8U)
  1631. {
  1632. /* bits/frame is 1 byte */
  1633. if (NULL != handle->txData)
  1634. {
  1635. /* Update transmit data and transmit pointer */
  1636. transmitData = *handle->txData;
  1637. handle->txData++;
  1638. }
  1639. else
  1640. {
  1641. transmitData = dummyPattern;
  1642. }
  1643. /* Decrease remaining dataSize */
  1644. --handle->remainingSendByteCount;
  1645. }
  1646. /* bits/frame is 2 bytes */
  1647. else
  1648. {
  1649. /* With multibytes per frame transmission, the transmit frame contains data from
  1650. * transmit buffer until sent dataSize matches user request. Other bytes will set to
  1651. * dummy pattern value.
  1652. */
  1653. if (NULL != handle->txData)
  1654. {
  1655. /* Update first byte of transmit data and transmit pointer */
  1656. transmitData = *handle->txData;
  1657. handle->txData++;
  1658. if (handle->remainingSendByteCount == 1U)
  1659. {
  1660. /* Decrease remaining dataSize */
  1661. --handle->remainingSendByteCount;
  1662. /* Update second byte of transmit data to second byte of dummy pattern */
  1663. transmitData = transmitData | (uint16_t)(((uint16_t)dummyPattern) << 8U);
  1664. }
  1665. else
  1666. {
  1667. /* Update second byte of transmit data and transmit pointer */
  1668. transmitData = transmitData | (uint16_t)((uint16_t)(*handle->txData) << 8U);
  1669. handle->txData++;
  1670. handle->remainingSendByteCount -= 2U;
  1671. }
  1672. }
  1673. else
  1674. {
  1675. if (handle->remainingSendByteCount == 1U)
  1676. {
  1677. --handle->remainingSendByteCount;
  1678. }
  1679. else
  1680. {
  1681. handle->remainingSendByteCount -= 2U;
  1682. }
  1683. transmitData = (uint16_t)((uint16_t)(dummyPattern) << 8U) | dummyPattern;
  1684. }
  1685. }
  1686. }
  1687. else
  1688. {
  1689. break;
  1690. }
  1691. /* Write the data to the DSPI data register */
  1692. base->PUSHR_SLAVE = transmitData;
  1693. /* Try to clear TFFF by writing a one to it; it will not clear if TX FIFO not full */
  1694. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  1695. }
  1696. }
  1697. static void DSPI_SlaveTransferComplete(SPI_Type *base, dspi_slave_handle_t *handle)
  1698. {
  1699. assert(NULL != handle);
  1700. /* Disable interrupt requests */
  1701. DSPI_DisableInterrupts(
  1702. base, ((uint32_t)kDSPI_TxFifoUnderflowInterruptEnable | (uint32_t)kDSPI_TxFifoFillRequestInterruptEnable |
  1703. (uint32_t)kDSPI_RxFifoOverflowInterruptEnable | (uint32_t)kDSPI_RxFifoDrainRequestInterruptEnable));
  1704. /* The transfer is complete. */
  1705. handle->txData = NULL;
  1706. handle->rxData = NULL;
  1707. handle->remainingReceiveByteCount = 0;
  1708. handle->remainingSendByteCount = 0;
  1709. status_t status;
  1710. if (handle->state == (uint8_t)kDSPI_Error)
  1711. {
  1712. status = kStatus_DSPI_Error;
  1713. }
  1714. else
  1715. {
  1716. status = kStatus_Success;
  1717. }
  1718. handle->state = (uint8_t)kDSPI_Idle;
  1719. if (NULL != handle->callback)
  1720. {
  1721. handle->callback(base, handle, status, handle->userData);
  1722. }
  1723. }
  1724. /*!
  1725. * brief DSPI slave aborts a transfer using an interrupt.
  1726. *
  1727. * This function aborts a transfer using an interrupt.
  1728. *
  1729. * param base DSPI peripheral base address.
  1730. * param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state.
  1731. */
  1732. void DSPI_SlaveTransferAbort(SPI_Type *base, dspi_slave_handle_t *handle)
  1733. {
  1734. assert(NULL != handle);
  1735. DSPI_StopTransfer(base);
  1736. /* Disable interrupt requests */
  1737. DSPI_DisableInterrupts(
  1738. base, ((uint32_t)kDSPI_TxFifoUnderflowInterruptEnable | (uint32_t)kDSPI_TxFifoFillRequestInterruptEnable |
  1739. (uint32_t)kDSPI_RxFifoOverflowInterruptEnable | (uint32_t)kDSPI_RxFifoDrainRequestInterruptEnable));
  1740. handle->state = (uint8_t)kDSPI_Idle;
  1741. handle->remainingSendByteCount = 0;
  1742. handle->remainingReceiveByteCount = 0;
  1743. }
  1744. /*!
  1745. * brief DSPI Master IRQ handler function.
  1746. *
  1747. * This function processes the DSPI transmit and receive IRQ.
  1748. *
  1749. * param base DSPI peripheral base address.
  1750. * param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state.
  1751. */
  1752. void DSPI_SlaveTransferHandleIRQ(SPI_Type *base, dspi_slave_handle_t *handle)
  1753. {
  1754. assert(NULL != handle);
  1755. uint8_t dummyPattern = DSPI_GetDummyDataInstance(base);
  1756. uint32_t dataReceived;
  1757. uint32_t dataSend = 0;
  1758. uint32_t tmpRemainingReceiveByteCount = 0;
  1759. /* Because SPI protocol is synchronous, the number of bytes that that slave received from the
  1760. * master is the actual number of bytes that the slave transmitted to the master. So we only
  1761. * monitor the received dataSize to know when the transfer is complete.
  1762. */
  1763. if (handle->remainingReceiveByteCount > 0U)
  1764. {
  1765. while ((uint32_t)kDSPI_RxFifoDrainRequestFlag ==
  1766. (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoDrainRequestFlag))
  1767. {
  1768. /* Have received data in the buffer. */
  1769. dataReceived = base->POPR;
  1770. /*Clear the rx fifo drain request, needed for non-DMA applications as this flag
  1771. * will remain set even if the rx fifo is empty. By manually clearing this flag, it
  1772. * either remain clear if no more data is in the fifo, or it will set if there is
  1773. * more data in the fifo.
  1774. */
  1775. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoDrainRequestFlag);
  1776. /* If bits/frame is one byte */
  1777. if (handle->bitsPerFrame <= 8U)
  1778. {
  1779. if (NULL != handle->rxData)
  1780. {
  1781. /* Receive buffer is not null, store data into it */
  1782. *handle->rxData = (uint8_t)dataReceived;
  1783. ++handle->rxData;
  1784. }
  1785. /* Descrease remaining receive byte count */
  1786. --handle->remainingReceiveByteCount;
  1787. if (handle->remainingSendByteCount > 0U)
  1788. {
  1789. if (NULL != handle->txData)
  1790. {
  1791. dataSend = *handle->txData;
  1792. ++handle->txData;
  1793. }
  1794. else
  1795. {
  1796. dataSend = dummyPattern;
  1797. }
  1798. --handle->remainingSendByteCount;
  1799. /* Write the data to the DSPI data register */
  1800. base->PUSHR_SLAVE = dataSend;
  1801. }
  1802. }
  1803. else /* If bits/frame is 2 bytes */
  1804. {
  1805. /* With multibytes frame receiving, we only receive till the received dataSize
  1806. * matches user request. Other bytes will be ignored.
  1807. */
  1808. if (NULL != handle->rxData)
  1809. {
  1810. /* Receive buffer is not null, store first byte into it */
  1811. *handle->rxData = (uint8_t)dataReceived;
  1812. ++handle->rxData;
  1813. if (handle->remainingReceiveByteCount == 1U)
  1814. {
  1815. /* Decrease remaining receive byte count */
  1816. --handle->remainingReceiveByteCount;
  1817. }
  1818. else
  1819. {
  1820. /* Receive buffer is not null, store second byte into it */
  1821. *handle->rxData = (uint8_t)(dataReceived >> 8U);
  1822. ++handle->rxData;
  1823. handle->remainingReceiveByteCount -= 2U;
  1824. }
  1825. }
  1826. /* If no handle->rxData*/
  1827. else
  1828. {
  1829. if (handle->remainingReceiveByteCount == 1U)
  1830. {
  1831. /* Decrease remaining receive byte count */
  1832. --handle->remainingReceiveByteCount;
  1833. }
  1834. else
  1835. {
  1836. handle->remainingReceiveByteCount -= 2U;
  1837. }
  1838. }
  1839. if (handle->remainingSendByteCount > 0U)
  1840. {
  1841. if (NULL != handle->txData)
  1842. {
  1843. dataSend = *handle->txData;
  1844. ++handle->txData;
  1845. if (handle->remainingSendByteCount == 1U)
  1846. {
  1847. --handle->remainingSendByteCount;
  1848. dataSend |= (uint16_t)((uint16_t)(dummyPattern) << 8U);
  1849. }
  1850. else
  1851. {
  1852. dataSend |= (uint32_t)(*handle->txData) << 8U;
  1853. ++handle->txData;
  1854. handle->remainingSendByteCount -= 2U;
  1855. }
  1856. }
  1857. /* If no handle->txData*/
  1858. else
  1859. {
  1860. if (handle->remainingSendByteCount == 1U)
  1861. {
  1862. --handle->remainingSendByteCount;
  1863. }
  1864. else
  1865. {
  1866. handle->remainingSendByteCount -= 2U;
  1867. }
  1868. dataSend = ((uint32_t)(dummyPattern) << 8U) | dummyPattern;
  1869. }
  1870. /* Write the data to the DSPI data register */
  1871. base->PUSHR_SLAVE = dataSend;
  1872. }
  1873. }
  1874. /* Try to clear TFFF by writing a one to it; it will not clear if TX FIFO not full */
  1875. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoFillRequestFlag);
  1876. if (handle->remainingReceiveByteCount == 0U)
  1877. {
  1878. break;
  1879. }
  1880. }
  1881. }
  1882. /* Check if remaining receive byte count matches user request */
  1883. tmpRemainingReceiveByteCount = handle->remainingReceiveByteCount;
  1884. if ((handle->state == (uint8_t)(kDSPI_Error)) || (tmpRemainingReceiveByteCount == 0U))
  1885. {
  1886. /* Other cases, stop the transfer. */
  1887. DSPI_SlaveTransferComplete(base, handle);
  1888. return;
  1889. }
  1890. /* Catch tx fifo underflow conditions, service only if tx under flow interrupt enabled */
  1891. if (0U != (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_TxFifoUnderflowFlag))
  1892. {
  1893. if (0U != (base->RSER & SPI_RSER_TFUF_RE_MASK))
  1894. {
  1895. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_TxFifoUnderflowFlag);
  1896. /* Change state to error and clear flag */
  1897. if (NULL != handle->txData)
  1898. {
  1899. handle->state = (uint8_t)kDSPI_Error;
  1900. }
  1901. handle->errorCount++;
  1902. }
  1903. }
  1904. /* Catch rx fifo overflow conditions, service only if rx over flow interrupt enabled */
  1905. if (0U != (DSPI_GetStatusFlags(base) & (uint32_t)kDSPI_RxFifoOverflowFlag))
  1906. {
  1907. if (0U != (base->RSER & SPI_RSER_RFOF_RE_MASK))
  1908. {
  1909. DSPI_ClearStatusFlags(base, (uint32_t)kDSPI_RxFifoOverflowFlag);
  1910. /* Change state to error and clear flag */
  1911. if (NULL != handle->txData)
  1912. {
  1913. handle->state = (uint8_t)kDSPI_Error;
  1914. }
  1915. handle->errorCount++;
  1916. }
  1917. }
  1918. }
  1919. static void DSPI_CommonIRQHandler(SPI_Type *base, void *param)
  1920. {
  1921. if (DSPI_IsMaster(base))
  1922. {
  1923. s_dspiMasterIsr(base, (dspi_master_handle_t *)param);
  1924. }
  1925. else
  1926. {
  1927. s_dspiSlaveIsr(base, (dspi_slave_handle_t *)param);
  1928. }
  1929. SDK_ISR_EXIT_BARRIER;
  1930. }
  1931. #if defined(SPI0)
  1932. void SPI0_DriverIRQHandler(void)
  1933. {
  1934. assert(NULL != g_dspiHandle[0]);
  1935. DSPI_CommonIRQHandler(SPI0, g_dspiHandle[0]);
  1936. }
  1937. #endif
  1938. #if defined(SPI1)
  1939. void SPI1_DriverIRQHandler(void)
  1940. {
  1941. assert(NULL != g_dspiHandle[1]);
  1942. DSPI_CommonIRQHandler(SPI1, g_dspiHandle[1]);
  1943. }
  1944. #endif
  1945. #if defined(SPI2)
  1946. void SPI2_DriverIRQHandler(void)
  1947. {
  1948. assert(NULL != g_dspiHandle[2]);
  1949. DSPI_CommonIRQHandler(SPI2, g_dspiHandle[2]);
  1950. }
  1951. #endif
  1952. #if defined(SPI3)
  1953. void SPI3_DriverIRQHandler(void)
  1954. {
  1955. assert(NULL != g_dspiHandle[3]);
  1956. DSPI_CommonIRQHandler(SPI3, g_dspiHandle[3]);
  1957. }
  1958. #endif
  1959. #if defined(SPI4)
  1960. void SPI4_DriverIRQHandler(void)
  1961. {
  1962. assert(NULL != g_dspiHandle[4]);
  1963. DSPI_CommonIRQHandler(SPI4, g_dspiHandle[4]);
  1964. }
  1965. #endif
  1966. #if defined(SPI5)
  1967. void SPI5_DriverIRQHandler(void)
  1968. {
  1969. assert(NULL != g_dspiHandle[5]);
  1970. DSPI_CommonIRQHandler(SPI5, g_dspiHandle[5]);
  1971. }
  1972. #endif
  1973. #if (FSL_FEATURE_SOC_DSPI_COUNT > 6)
  1974. #error "Should write the SPIx_DriverIRQHandler function that instance greater than 5 !"
  1975. #endif