From 843105da52e15761303232f595cd37116936a549 Mon Sep 17 00:00:00 2001 From: AceVest Date: Fri, 7 Jun 2019 21:31:13 +0800 Subject: [PATCH] =?utf8?q?usart1=20usart2=20=E4=B9=8B=E9=97=B4=E9=87=8D?= =?utf8?q?=E5=AE=9A=E5=90=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- learn/stm32/USART.md | 76 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/learn/stm32/USART.md b/learn/stm32/USART.md index 080af4f..12076be 100644 --- a/learn/stm32/USART.md +++ b/learn/stm32/USART.md @@ -25,4 +25,78 @@ PUTCHAR_PROTOTYPE `Mode: Asynchronous` -`Hadware Flow Control (RS233): Disable` \ No newline at end of file +`Hadware Flow Control (RS233): Disable` + + + +# USART1、USART2转发 + +需要开启这两个串口的中断 + +``` +#define USART_RX_BUFSZ 10 +typedef struct { + uint8_t rxdata; + uint8_t rxbuf[USART_RX_BUFSZ]; + uint16_t rxwp; + uint16_t rxrp; +} UsartData_t; + +UsartData_t usart1_data; +UsartData_t usart2_data; + + +void InitUsartTransfer(){ + usart1_data.rxrp = usart1_data.rxwp = 0; + usart2_data.rxrp = usart2_data.rxwp = 0; + if(HAL_OK != HAL_UART_Receive_IT(&huart1, &usart1_data.rxdata, 1)) { + Error_Handler(); + } + + if(HAL_OK != HAL_UART_Receive_IT(&huart2, &usart2_data.rxdata, 1)) { + Error_Handler(); + } +} + +void TransferToUsart(UsartData_t *data, UART_HandleTypeDef *to_huart){ + uint16_t rxwp = data->rxwp; + if(data->rxrp == rxwp) { + // empty + return ; + } + HAL_UART_Transmit(to_huart, data->rxbuf+data->rxrp, 1, 0xFFFF); + data->rxrp = (data->rxrp + 1) % USART_RX_BUFSZ; +} + +void TransferUsartData() { + TransferToUsart(&usart1_data, &huart2); + TransferToUsart(&usart2_data, &huart1); +} + +void ReceiveUsartData(UsartData_t *data, UART_HandleTypeDef *huart) { + if((data->rxwp + 1) % USART_RX_BUFSZ == data->rxrp) { + // full + goto end; + } + + data->rxbuf[data->rxwp] = data->rxdata; + + data->rxwp =(data->rxwp + 1) % USART_RX_BUFSZ; + +end: + if(HAL_OK != HAL_UART_Receive_IT(huart, &data->rxdata, 1)) { + //Error_Handler(); + } +} + + +void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { + if(huart->Instance == USART1) { + return ReceiveUsartData(&usart1_data, huart); + } + + if(huart->Instance == USART2) { + return ReceiveUsartData(&usart2_data, huart); + } +} +``` \ No newline at end of file -- 2.44.0