[STM32L0] STM32L0系列之【串口收发】

[复制链接]
1258|1
 楼主| 两只袜子 发表于 2023-6-16 15:14 | 显示全部楼层 |阅读模式

1.串口1 USART1初始化 [注意使能接收中断]

  • /**

  •   * @brief USART1 Initialization Function

  •   * @param None

  •   * @retval None

  •   */

  • UART_HandleTypeDef huart1;

  • void MX_USART1_UART_Init(void)

  • {

  •   huart1.Instance = USART1;

  •   huart1.Init.BaudRate = 115200;

  •   huart1.Init.WordLength = UART_WORDLENGTH_8B;

  •   huart1.Init.StopBits = UART_STOPBITS_1;

  •   huart1.Init.Parity = UART_PARITY_NONE;

  •   huart1.Init.Mode = UART_MODE_TX_RX;

  •   huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;

  •   huart1.Init.OverSampling = UART_OVERSAMPLING_16;

  •   huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;

  •   huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;

  •   if (HAL_UART_Init(&huart1) != HAL_OK)

  •   {

  •     Error_Handler();

  •   }

  •   //使能接收中断

  •   HAL_UART_Receive_IT(&huart1,usart1_RxBuf_temp,1);          // Enable the USART1 Interrupt

  • }


复制代码


2.串口接收中断

  • /**

  •   * @brief This function handles USART1 global interrupt / USART1 wake-up interrupt through EXTI line 25.

  •   */

  • void USART1_IRQHandler(void)

  • {

  •   HAL_UART_IRQHandler(&huart1);

  • }


复制代码


3.串口接收中断完成回调函数

  • /**

  •   * @brief  Rx Transfer completed callback

  •   * @param  UartHandle: UART handle

  •   * @NOTE   This example shows a simple way to report end of IT Rx transfer, and

  •   *         you can add your own implementation.

  •   * @retval None

  •   */

  • void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)

  • {

  •     if(UartHandle->Instance == USART1)

  •     {

  •         Netctrlp_Receive(usart1_RxBuf_temp[0]);

  •         HAL_UART_Receive_IT(&huart1,usart1_RxBuf_temp,1);      // 重新使能串口1接收中断

  •     }

  • }


复制代码


4.重定向输入输出,将输出重定向至printf

  • uint8_t ch;

  • uint8_t ch_r;

  • //重写这个函数,重定向printf函数到串口,意思就是说printf直接输出到串口,其默认输出到控制台的

  • /*fputc*/

  • int fputc(int c, FILE * f)

  • {

  •     ch=c;

  • //    HAL_UART_Transmit_IT(&huart1,&ch,1);//发送串口

  •     HAL_UART_Transmit(&huart1,&ch,1,100);//发送串口

  •     return ch;

  • }


  • //重定向scanf函数到串口 意思就是说接受串口发过来的数据,其默认是接受控制台的数据

  • /*fgetc*/

  • int fgetc(FILE * F)   

  • {

  •     HAL_UART_Receive_IT(&huart1,&ch_r,1);//接收

  •     return ch_r;

  • }


复制代码
 楼主| 两只袜子 发表于 2023-6-16 15:15 | 显示全部楼层
5.main.c 主函数

int main(void) //SLAVE

{

    HAL_Init();

    /* Configure the system clock */

    SystemClock_Config();

    MX_USART1_UART_Init();



         while(1){

      DBG_print(DBG_DEBUG, " A.");

      HAL_Delay(100);

    }

}
您需要登录后才可以回帖 登录 | 注册

本版积分规则

2122

主题

8121

帖子

11

粉丝
快速回复 在线客服 返回列表 返回顶部