1919
2020// #define SPI_USE_DMA
2121
22+ #define SPI_TIMEOUT_US (500)
23+
2224struct stm32_spi_bus {
2325 struct rt_spi_bus parent ;
2426 SPI_TypeDef * SPI ;
@@ -39,6 +41,18 @@ struct stm32_spi_cs {
3941 uint16_t GPIO_Pin ;
4042};
4143
44+ static fmt_err_t wait_flag_until_timeout (const SPI_TypeDef * SPIx , uint32_t flag , uint32_t status , uint64_t timeout_us )
45+ {
46+ uint64_t time_start = systime_now_us ();
47+
48+ while (((READ_BIT (SPIx -> SR , flag ) == flag ) ? 1UL : 0UL ) == status ) {
49+ if ((systime_now_us () - time_start ) > timeout_us ) {
50+ return FMT_ETIMEOUT ;
51+ }
52+ }
53+ return FMT_EOK ;
54+ }
55+
4256/**
4357 * @brief Configure spi device
4458 *
@@ -172,16 +186,14 @@ static rt_uint32_t transfer(struct rt_spi_device* device, struct rt_spi_message*
172186 LL_SPI_StartMasterTransfer (SPI );
173187
174188 /* Wait until the transmit buffer is empty */
175- while (LL_SPI_IsActiveFlag_TXP (SPI ) == RESET )
176- ;
189+ wait_flag_until_timeout (SPI , SPI_SR_TXP , RESET , SPI_TIMEOUT_US );
177190
178191 /* Send the byte */
179192 LL_SPI_TransmitData8 (SPI , data );
180193
181194 /* Wait until a data is received */
182- while (LL_SPI_IsActiveFlag_RXP (SPI ) == RESET )
183- ;
184- // RT_ASSERT(RT_EOK);
195+ wait_flag_until_timeout (SPI , SPI_SR_RXP , RESET , SPI_TIMEOUT_US );
196+
185197
186198 /* Get the received data */
187199 data = LL_SPI_ReceiveData8 (SPI );
@@ -204,14 +216,12 @@ static rt_uint32_t transfer(struct rt_spi_device* device, struct rt_spi_message*
204216 data = * send_ptr ++ ;
205217 }
206218 /* Wait until the transmit buffer is empty */
207- while (LL_SPI_IsActiveFlag_TXP (SPI ) == RESET )
208- ;
219+ wait_flag_until_timeout (SPI , SPI_SR_TXP , RESET , SPI_TIMEOUT_US );
209220
210221 /* Send the byte */
211222 LL_SPI_TransmitData16 (SPI , data );
212223 /* Wait until a data is received */
213- while (LL_SPI_IsActiveFlag_RXP (SPI ) == RESET )
214- ;
224+ wait_flag_until_timeout (SPI , SPI_SR_RXP , RESET , SPI_TIMEOUT_US );
215225
216226 /* Get the received data */
217227 data = LL_SPI_ReceiveData16 (SPI );
0 commit comments