STM32 LL库踩坑系列四(SPI和UART随记)

STM32 LL库踩坑系列四(SPI和UART随记)

这个作者很懒,想到什么就写什么!

写在前面:这个是记录学习LL库的踩坑系列,这个资料很少,想要找例程可以在电脑用户文件下的STM32Cube\Repository里,前提是下载好那个单片机的pack,部分没有例程的可以借鉴同系列的文件。

生成的代码还需要添加
SPI添加

LL_SPI_Enable();

加一个SPI读写共用函数

uint8_t SPI1_ReadWriteByte(uint8_t TxData)
{		
	uint8_t retry = 0;				 
 
	/* Check if Tx buffer is empty */
	while (!LL_SPI_IsActiveFlag_TXE(SPI1)) 
	{
		retry++;
		if(retry > 200) return 0;
	}			  
 
	/* Write character in Data register.
	TXE flag is cleared by reading data in DR register */
	LL_SPI_TransmitData8(SPI1, TxData);
	retry = 0;
 
	/* Check if Rx buffer is not empty */
	while (!LL_SPI_IsActiveFlag_RXNE(SPI1)) 
	{
		retry++;
		if(retry > 200) return 0;
	}	  						    
 
	/* received byte from SPI lines. */
	return LL_SPI_ReceiveData8(SPI1); 				    
}

注意STM32F302系列的需要增加才能正常运行

LL_SPI_SetRxFIFOThreshold(SPI1, LL_SPI_RX_FIFO_TH_QUARTER);

UART添加函数

如果配置为中断接收模式

一. 使能中断接收

  /* Clear Overrun flag, in case characters have already been sent to USART */
  LL_USART_ClearFlag_ORE();
  
  /* Enable RXNE and Error interrupts */
  LL_USART_EnableIT_RXNE();

二. 添加中断处理函数

/**
  * @brief  Function called from USART IRQ Handler when RXNE flag is set
  *         Function is in charge of reading character received on USART RX line.
  * @param  None
  * @retval None
  */
void USART1_CharReception_Callback(void)
{
  __IO uint8_t received_char;

  /* Read Received character. RXNE flag is cleared by reading of RDR register */
  received_char = LL_USART_ReceiveData8(USART1);
	
}

三. 在对应的中断函数文件下

/**
  * @brief This function handles USART1 global interrupt.
  */
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */
  /* Check RXNE flag value in SR register */
  if(LL_USART_IsActiveFlag_RXNE(USART1) && LL_USART_IsEnabledIT_RXNE(USART1))
  {
    /* RXNE flag will be cleared by reading of DR register (done in call) */
    /* Call function in charge of handling Character reception */
    USART1_CharReception_Callback();
  }
  /* USER CODE END USART1_IRQn 0 */
  /* USER CODE BEGIN USART1_IRQn 1 */

  /* USER CODE END USART1_IRQn 1 */
}

加一个串口发送的

unsigned short int UART_W(USART_TypeDef *USARTx,unsigned char *pbuf,unsigned short int len)
{
	while (len--)
	{
		LL_USART_TransmitData8(USARTx, *pbuf);
		while (!LL_USART_IsActiveFlag_TXE(USARTx));
		pbuf ++ ;
	}

	return len ;
}

你可能感兴趣的:(单片机,STM32,LL库,CubeMX)