这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界» 论坛首页» 嵌入式开发» STM32» STM32L0系列之【串口收发】

共3条 1/1 1 跳转至

STM32L0系列之【串口收发】

院士
2023-05-24 23:34:37 打赏

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

  1. /**

  2. * @brief USART1 Initialization Function

  3. * @param None

  4. * @retval None

  5. */

  6. UART_HandleTypeDef huart1;

  7. void MX_USART1_UART_Init(void)

  8. {

  9. huart1.Instance = USART1;

  10. huart1.Init.BaudRate = 115200;

  11. huart1.Init.WordLength = UART_WORDLENGTH_8B;

  12. huart1.Init.StopBits = UART_STOPBITS_1;

  13. huart1.Init.Parity = UART_PARITY_NONE;

  14. huart1.Init.Mode = UART_MODE_TX_RX;

  15. huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;

  16. huart1.Init.OverSampling = UART_OVERSAMPLING_16;

  17. huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;

  18. huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;

  19. if (HAL_UART_Init(&huart1) != HAL_OK)

  20. {

  21. Error_Handler();

  22. }

  23. //使能接收中断

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

  25. }

复制代码


2.串口接收中断

  1. /**

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

  3. */

  4. void USART1_IRQHandler(void)

  5. {

  6. HAL_UART_IRQHandler(&huart1);

  7. }

复制代码


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

  1. /**

  2. * @brief Rx Transfer completed callback

  3. * @param UartHandle: UART handle

  4. * @note This example shows a simple way to report end of IT Rx transfer, and

  5. * you can add your own implementation.

  6. * @retval None

  7. */

  8. void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)

  9. {

  10. if(UartHandle->Instance == USART1)

  11. {

  12. Netctrlp_Receive(usart1_RxBuf_temp[0]);

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

  14. }

  15. }

复制代码


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

  1. uint8_t ch;

  2. uint8_t ch_r;

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

  4. /*fputc*/

  5. int fputc(int c, FILE * f)

  6. {

  7. ch=c;

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

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

  10. return ch;

  11. }


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

  13. /*fgetc*/

  14. int fgetc(FILE * F)

  15. {

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

  17. return ch_r;

  18. }

复制代码


5.main.c 主函数

  1. int main(void) //SLAVE

  2. {

  3. HAL_Init();

  4. /* Configure the system clock */

  5. SystemClock_Config();

  6. MX_USART1_UART_Init();


  7. while(1){

  8. DBG_print(DBG_DEBUG, " A.");

  9. HAL_Delay(100);

  10. }

  11. }




专家
2023-05-25 01:30:29 打赏
2楼

感谢楼主的分享,很实用了。


专家
2023-05-25 01:34:15 打赏
3楼

感谢楼主的分享,很实用了。


共3条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册]