打印
[STM32L0]

STM32L0系列之【串口收发】

[复制链接]
185|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);

    }

}

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1884

主题

6474

帖子

8

粉丝